import { useState } from "react";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useListPeople, useCreatePerson } from "@/features/people/use-people";
import { useAssignFace } from "@/features/faces/use-faces";
import { ScrollArea } from "@/components/ui/scroll-area";
import { UserSquare, Plus } from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";

type PersonAssignmentDialogProps = {
    isOpen: boolean;
    onOpenChange: (open: boolean) => void;
    faceId: string;
    mediaId: string;
    currentPersonId: string | null;
};

export function PersonAssignmentDialog({
    isOpen,
    onOpenChange,
    faceId,
    mediaId,
    currentPersonId,
}: PersonAssignmentDialogProps) {
    const [searchQuery, setSearchQuery] = useState("");
    const [isCreating, setIsCreating] = useState(false);
    const [newPersonName, setNewPersonName] = useState("");

    const { data: people } = useListPeople();
    const assignFace = useAssignFace(faceId, mediaId);
    const createPerson = useCreatePerson();

    const filteredPeople = people?.filter((person) =>
        person.name.toLowerCase().includes(searchQuery.toLowerCase())
    );

    const handleAssign = (personId: string) => {
        assignFace.mutate(
            { person_id: personId },
            {
                onSuccess: () => {
                    onOpenChange(false);
                },
            }
        );
    };

    const handleCreateAndAssign = () => {
        if (!newPersonName.trim()) return;

        createPerson.mutate(
            { name: newPersonName },
            {
                onSuccess: (newPerson) => {
                    handleAssign(newPerson.id);
                },
            }
        );
    };

    return (
        <Dialog open={isOpen} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[425px]">
                <DialogHeader>
                    <DialogTitle>Assign Person</DialogTitle>
                </DialogHeader>

                {isCreating ? (
                    <div className="space-y-4 py-4">
                        <Input
                            placeholder="Enter person name"
                            value={newPersonName}
                            onChange={(e) => setNewPersonName(e.target.value)}
                            autoFocus
                        />
                        <div className="flex justify-end gap-2">
                            <Button variant="outline" onClick={() => setIsCreating(false)}>
                                Cancel
                            </Button>
                            <Button onClick={handleCreateAndAssign} disabled={!newPersonName.trim()}>
                                Create & Assign
                            </Button>
                        </div>
                    </div>
                ) : (
                    <div className="space-y-4">
                        <Input
                            placeholder="Search people..."
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                        />

                        <ScrollArea className="h-[300px] pr-4">
                            <div className="space-y-2">
                                <Button
                                    variant="ghost"
                                    className="w-full justify-start gap-2"
                                    onClick={() => setIsCreating(true)}
                                >
                                    <div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center">
                                        <Plus size={16} />
                                    </div>
                                    <span>Create "{searchQuery || "New Person"}"</span>
                                </Button>

                                {filteredPeople?.map((person) => (
                                    <Button
                                        key={person.id}
                                        variant={currentPersonId === person.id ? "secondary" : "ghost"}
                                        className="w-full justify-start gap-2"
                                        onClick={() => handleAssign(person.id)}
                                    >
                                        <Avatar className="h-8 w-8">
                                            {/* TODO: Add thumbnail URL if available */}
                                            <AvatarFallback>
                                                <UserSquare size={16} />
                                            </AvatarFallback>
                                        </Avatar>
                                        <span>{person.name}</span>
                                    </Button>
                                ))}
                            </div>
                        </ScrollArea>
                    </div>
                )}
            </DialogContent>
        </Dialog>
    );
}
