"use client"

// import { useState } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import { DatePicker } from "@/components/ui/date-picker"
import { Loader2, Copy } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
// import { Card, CardContent } from "@/components/ui/card"

interface PQList {
  id: number
  name: string
  type: "GENERAL" | "PROJECT" | "NON_INSPECTION"
  projectId?: number | null
  criteriaCount?: number
  createdAt: Date
}

interface Project {
  id: number
  name: string
  code: string
}

const copyPqSchema = z.object({
  sourcePqListId: z.number({
    required_error: "복사할 PQ 목록을 선택해주세요"
  }),
  targetProjectId: z.number().optional(),
  validTo: z.date(),
  newName: z.string(),
}).refine((data) => {
  // 미실사 PQ가 아닌 경우에만 targetProjectId 필수
  if (data.targetProjectId !== undefined) return true
  // 미실사 PQ인 경우 targetProjectId는 선택사항
  return true
}, {
  message: "프로젝트 PQ인 경우 대상 프로젝트를 선택해야 합니다",
  path: ["targetProjectId"]
})

type CopyPqFormData = z.infer<typeof copyPqSchema>

interface CopyPqDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  pqLists: PQList[]
  projects: Project[]
  onCopy: (data: CopyPqFormData) => Promise<void>
  isLoading?: boolean
}

const typeLabels = {
  GENERAL: "일반 PQ",
  PROJECT: "프로젝트 PQ",
  NON_INSPECTION: "미실사 PQ"
}

const typeColors = {
  GENERAL: "bg-blue-100 text-blue-800",
  PROJECT: "bg-green-100 text-green-800",
  NON_INSPECTION: "bg-orange-100 text-orange-800"
}

export function CopyPqDialog({
  open,
  onOpenChange,
  pqLists,
  projects,
  onCopy,
  isLoading = false
}: CopyPqDialogProps) {
  const form = useForm<CopyPqFormData>({
    resolver: zodResolver(copyPqSchema),
  })
  const formState = form.formState

  const selectedSourceId = form.watch("sourcePqListId")
  const selectedPqList = pqLists.find(list => list.id === selectedSourceId)

  const handleSubmit = async (data: CopyPqFormData) => {
    try {
      await onCopy(data)
      form.reset()
      onOpenChange(false)
    } catch (error) {
      // 에러는 상위 컴포넌트에서 처리
      console.error("Failed to copy PQ list:", error)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Copy className="h-5 w-5" />
            PQ 목록 불러오기
          </DialogTitle>
          <DialogDescription>
            기존 PQ 목록을 선택하여 새로운 프로젝트 PQ를 생성합니다.
            선택한 PQ의 모든 항목이 새 프로젝트로 복사됩니다.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
            {/* 복사할 PQ 목록 선택 */}
            <FormField
              control={form.control}
              name="sourcePqListId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="flex items-center gap-1">
                    복사할 PQ 리스트 <span className="text-red-500">*</span>
                  </FormLabel>
                  <Select 
                    onValueChange={(value) => field.onChange(parseInt(value))} 
                    defaultValue={field.value?.toString()}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="복사할 PQ 리스트를 선택하세요" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {pqLists
                        .filter(pqList => pqList.type !== "GENERAL" && pqList.type !== "NON_INSPECTION") // 일반 PQ 제외 미실사 PQ 제외
                        .map((pqList) => (
                        <SelectItem key={pqList.id} value={pqList.id.toString()}>
                          <div className="flex items-center gap-2">
                            <Badge className={typeColors[pqList.type]}>
                              {typeLabels[pqList.type]}
                            </Badge>
                            <span>{pqList.name}</span>
                            {pqList.criteriaCount && (
                              <span className="text-xs text-muted-foreground">
                                ({pqList.criteriaCount}개 항목)
                              </span>
                            )}
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  {selectedPqList && (
                    <div className="text-sm text-muted-foreground mt-1">
                      선택된 PQ 리스트: <strong>{selectedPqList.name}</strong>
                      {selectedPqList.criteriaCount && (
                        <span> ({selectedPqList.criteriaCount}개 항목)</span>
                      )}
                    </div>
                  )}
                  <FormMessage />
                </FormItem>
              )}
            />
            {/* 대상 프로젝트 선택 (미실사 PQ가 아닌 경우에만) */}
            {selectedPqList?.type !== "NON_INSPECTION" && (
              <FormField
                control={form.control}
                name="targetProjectId"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="flex items-center gap-1">
                      대상 프로젝트 <span className="text-red-500">*</span>
                    </FormLabel>
                    <Select
                      onValueChange={(value) => field.onChange(parseInt(value))}
                      defaultValue={field.value?.toString()}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="PQ를 적용할 프로젝트를 선택하세요" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {projects.map((project) => (
                          <SelectItem key={project.id} value={project.id.toString()}>
                            {project.code} - {project.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            {/* 새 PQ 목록 명 */}
            <FormField
              control={form.control}
              name="newName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="flex items-center gap-1">
                    새 PQ 리스트명 <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input {...field} value={field.value ?? ""} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            {/* 유효기간 설정 */}
            <FormField
              control={form.control}
              name="validTo"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="flex items-center gap-1">
                    유효기간 <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <DatePicker
                      date={field.value ?? undefined}
                      onSelect={(date) => field.onChange(date ?? null)}
                      placeholder="유효기간 선택"
                      minDate={new Date()}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 버튼들 */}
            <div className="flex justify-end space-x-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isLoading}
              >
                취소
              </Button>
              <Button type="submit" disabled={isLoading || !formState.isValid}>
                {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                복사하여 생성
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
} 