"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"

import { Button } from "@/components/ui/button"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { UserCombobox } from "../../pq/pq-review-table-new/user-combobox"
import { getQMManagers } from "@/lib/pq/service"
import { updateQMManagerAction } from "../service"
import { toast } from "sonner"

// QM 사용자 타입
interface QMUser {
    id: number
    name: string
    email: string
    department?: string
}

const changeQMSchema = z.object({
    qmManagerId: z.number({
        required_error: "QM 담당자를 선택해주세요.",
    }),
})

type ChangeQMFormValues = z.infer<typeof changeQMSchema>

interface ChangeQMManagerDialogProps {
    isOpen: boolean
    onClose: () => void
    investigationId: number
    currentQMManagerId?: number
    currentQMManagerName?: string
    onSuccess?: () => void
}

export function ChangeQMManagerDialog({
    isOpen,
    onClose,
    investigationId,
    currentQMManagerId,
    currentQMManagerName,
    onSuccess,
}: ChangeQMManagerDialogProps) {
    const [isPending, setIsPending] = React.useState(false)
    const [qmManagers, setQMManagers] = React.useState<QMUser[]>([])
    const [isLoadingManagers, setIsLoadingManagers] = React.useState(false)

    // form 객체 생성
    const form = useForm<ChangeQMFormValues>({
        resolver: zodResolver(changeQMSchema),
        defaultValues: {
            qmManagerId: currentQMManagerId || undefined,
        },
    })

    // Dialog가 열릴 때마다 초기값으로 폼 재설정
    React.useEffect(() => {
        if (isOpen) {
            form.reset({
                qmManagerId: currentQMManagerId || undefined,
            });
        }
    }, [isOpen, currentQMManagerId, form]);

    // Dialog가 열릴 때 QM 담당자 목록 로드
    React.useEffect(() => {
        if (isOpen && qmManagers.length === 0) {
            const loadQMManagers = async () => {
                setIsLoadingManagers(true)
                try {
                    const result = await getQMManagers()
                    if (result.success && result.data) {
                        setQMManagers(result.data)
                    }
                } catch (error) {
                    console.error("QM 담당자 로드 오류:", error)
                } finally {
                    setIsLoadingManagers(false)
                }
            }

            loadQMManagers()
        }
    }, [isOpen, qmManagers.length])

    async function handleSubmit(data: ChangeQMFormValues) {
        setIsPending(true)
        try {
            const result = await updateQMManagerAction({
                investigationId,
                qmManagerId: data.qmManagerId,
            })

            if (result.success) {
                toast.success(result.message || "QM 담당자가 변경되었습니다.")
                onClose()
                onSuccess?.()
            } else {
                toast.error(result.error || "QM 담당자 변경에 실패했습니다.")
            }
        } catch (error) {
            console.error("QM 담당자 변경 오류:", error)
            toast.error("QM 담당자 변경 중 오류가 발생했습니다.")
        } finally {
            setIsPending(false)
        }
    }

    return (
        <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
            <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                    <DialogTitle>QM 담당자 변경</DialogTitle>
                    <DialogDescription>
                        실사의 QM 담당자를 변경합니다.
                        {currentQMManagerName && (
                            <div className="mt-2 text-sm text-muted-foreground">
                                현재 담당자: {currentQMManagerName}
                            </div>
                        )}
                    </DialogDescription>
                </DialogHeader>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
                        <FormField
                            control={form.control}
                            name="qmManagerId"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>QM 담당자</FormLabel>
                                    <FormControl>
                                        <UserCombobox
                                            users={qmManagers}
                                            value={field.value}
                                            onChange={field.onChange}
                                            placeholder={isLoadingManagers ? "담당자 로딩 중..." : "담당자 선택..."}
                                            disabled={isPending || isLoadingManagers}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <DialogFooter>
                            <Button
                                type="button"
                                variant="outline"
                                onClick={onClose}
                                disabled={isPending}
                            >
                                취소
                            </Button>
                            <Button type="submit" disabled={isPending || isLoadingManagers}>
                                {isPending ? "변경 중..." : "변경"}
                            </Button>
                        </DialogFooter>
                    </form>
                </Form>
            </DialogContent>
        </Dialog>
    )
}

