import React, { useCallback } from "react";
import { FormFieldProps } from "react-compose-form";
import { FormFieldContext, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form";
import { useMediaPicker } from "@/components/ui/media-picker";
import { MediaPreview } from "@/components/dashboard/media/media-preview";
import { api } from "@/lib/trpc/client";
import { MediaScope } from "@/server/modules/media/types/media-scope.enum";

export type MediaFieldProps = FormFieldProps<{
    withAttachments?: boolean;
    autosubmit?: boolean;
    label?: string;
    scope?: MediaScope;
    acceptedFileTypes?: string[];
    mimeType?: string | string[];
}>;

export const MediaField: React.FC<MediaFieldProps> = (props) => {
    const {
        withAttachments,
        autosubmit,
        label,
        mimeType,
        scope,
        acceptedFileTypes,
        name,
        value,
        onChange
    } = props;

    const mediaPicker = useMediaPicker();

    const {
        isLoading,
        data: media = null
    } = api.media.get.useQuery({
        id: value
    }, {
        enabled: !!value
    });

    const handleSelectMedia = useCallback(async () => {
        try {
            const [id] = await mediaPicker.pick({
                withAttachments,
                autosubmit,
                acceptedFileTypes,
                selected: value ? [value] : [],
                defaultAttached: true,
                scope,
                mimeType
            });

            if(onChange) {
                onChange(id);
            }
        }
        catch {}
    }, [mediaPicker, withAttachments, autosubmit, scope, acceptedFileTypes, mimeType, value, onChange]);

    return (
        <FormFieldContext
          value={{ name: name as string }}>
            <FormItem>
                {label && (
                    <FormLabel>{label}</FormLabel>
                )}

                <FormControl>
                    <div className="flex items-center justify-between">
                        <MediaPreview
                          size={125}
                          loading={isLoading}
                          originalName={media?.originalName}
                          mimeType={media?.mimeType}
                          caption={media?.caption || ""}
                          author={media?.author || ""}
                          alt={media?.alt || ""}
                          url={media?.url}
                          onReplace={handleSelectMedia} />
                    </div>
                </FormControl>

                <FormMessage />
            </FormItem>
        </FormFieldContext>
    );
};
