import React, { useCallback, PropsWithChildren } from "react";
import { XIcon, Circle, LucideCheckCircle } from "lucide-react";
import { useFormContext, useFieldArray } from "react-hook-form";
import { useFormGroupName } from "react-compose-form";
import { InputField } from "@/components/form/field/input.field";
import { ProfilePicker } from "@/components/dashboard/profile/profile-picker";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { api } from "@/lib/trpc/client";

type ProfileCollectionProps = PropsWithChildren<{
    label?: string;
    name: string;
    main?: string;
}>;

export const ProfileCollection: React.FC<ProfileCollectionProps> = (props) => {
    const {
        name,
        main: mainName,
        label
    } = props;

    const {watch, setValue} = useFormContext();

    const mainId = mainName ? watch(mainName) : "";
    const fullName = useFormGroupName(name);

    const {append, remove, fields} = useFieldArray<{
        [key: typeof fullName]: { profileId: string }[];
    }>({
        name: fullName
    });

    const ids = fields.map((field) => field.profileId);

    const {
        data: profiles = []
    } = api.profile.list.useQuery({
        ids
    }, {
        enabled: ids.length > 0
    });

    const handleSelect = (ids: string[]) => {
        for(const id of ids) {
            const field = fields.find((field) => field.profileId === id);

            if(!field) {
                append({
                    profileId: id
                });
            }
        }
    };

    const handlePrimary = useCallback((id: string) => {
        if(!mainName) {
            return;
        }

        setValue(mainName, id);
    }, [mainName, setValue]);

    return (
        <React.Fragment>
            {label && (
                <label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 mb-2 block">
                    {label}
                </label>
            )}

            <div className="grid grid-cols-2 gap-2">
                {fields.map((field, index) => {
                    const profile = profiles.find((profile) => profile.id === field.profileId);

                    return (
                        <div
                          key={field.id}
                          className="relative h-[125px] w-[125px] overflow-hidden rounded-md border flex flex-col items-center justify-center p-2">
                            <InputField type="hidden" name="profileId" />

                            {profile && (
                                <React.Fragment>
                                    <Avatar className="size-16 mb-1">
                                        <AvatarImage src={profile.avatar?.url} alt={profile.name} />
                                        <AvatarFallback>{profile.name.charAt(0)}</AvatarFallback>
                                    </Avatar>
                                    <div className="text-[10px] text-center font-medium line-clamp-2 px-1">
                                        {profile.name}
                                    </div>
                                </React.Fragment>
                            )}

                            {!profile && (
                                <div className="text-[10px] text-muted-foreground">Loading...</div>
                            )}

                            {mainName && (
                                <Button
                                  type="button"
                                  className="absolute top-1 left-1 size-6"
                                  size="icon"
                                  variant={field.profileId === mainId ? "default" : "outline"}
                                  onClick={() => handlePrimary(field.profileId)}>
                                    {field.profileId === mainId && <LucideCheckCircle className="size-4" />}
                                    {field.profileId !== mainId && <Circle className="size-4" />}
                                </Button>
                            )}

                            <Button
                              type="button"
                              className="absolute top-1 right-1 size-6"
                              size="icon"
                              variant="destructive"
                              onClick={() => remove(index)}>
                                <XIcon className="size-4" />
                            </Button>
                        </div>
                    );
                })}

                <div className="flex h-[125px] w-[125px] items-center justify-center overflow-hidden rounded-md border border-dashed border-black">
                    <ProfilePicker multiple selected={ids} onSelect={handleSelect} />
                </div>
            </div>

            {mainName && <InputField type="hidden" name={mainName} />}
        </React.Fragment>
    );
};
