import React, { useCallback } from "react";
import { useTranslations } from "next-intl";
import { FormFieldProps } from "react-compose-form";
import { FormFieldContext, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form";
import { ProfilePreview } from "@/components/dashboard/profile/profile-preview";
import { useProfilePicker } from "@/components/ui/profile-picker";
import { api } from "@/lib/trpc/client";

export type ProfileFieldProps = FormFieldProps<{
    label?: string;
    personal?: boolean;
}>;

export const ProfileField: React.FC<ProfileFieldProps> = (props) => {
    const {
        personal,
        label,
        name,
        value,
        onChange
    } = props;

    const t = useTranslations("dashboard.profile");

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

    const profilePicker = useProfilePicker();

    const handleEditProfile = useCallback(async () => {
        if(!value) {
            return;
        }

        const selected = await profilePicker.edit(value);

        if(selected && selected.length > 0) {
            onChange?.(selected[0]);
        }
    }, [value, profilePicker, onChange]);

    const handlePickProfile = useCallback(async () => {
        try {
            const selected = await profilePicker.pick({
                autosubmit: true,
                personal,
                selected: value ? [value] : []
            });

            if(selected && selected.length > 0) {
                onChange?.(selected[0]);
            }
        }
        catch {}
    }, [value, profilePicker, personal, onChange]);

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

                <FormControl>
                    <div className="flex items-center justify-between">
                        {!value && (
                            <ProfilePreview
                              className="w-[120px]"
                              name={t("actions.select")}
                              onReplace={handlePickProfile} />
                        )}

                        {value && (
                            <ProfilePreview
                              className="w-[120px]"
                              loading={isLoading}
                              avatar={profile?.avatar}
                              name={profile?.name}
                              jobInfo={profile?.jobInfo}
                              onEdit={handleEditProfile}
                              onReplace={handlePickProfile} />
                        )}
                    </div>
                </FormControl>

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