"use client"

import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { DatePicker } from "@/components/ui/date-picker"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import { Loader2, Plus } from "lucide-react"

// 프로젝트 목록을 위한 임시 타입 (실제로는 projects에서 가져와야 함)
interface Project {
  id: number
  name: string
  code: string
}

const pqListFormSchema = z.object({
  name: z.string().min(1, "PQ 목록 명을 입력해주세요"),
  type: z.enum(["GENERAL", "PROJECT", "NON_INSPECTION"], {
    required_error: "PQ 유형을 선택해주세요"
  }),
  projectId: z.number().optional().nullable(),
  validTo: z.date().optional().nullable(),
}).refine((data) => {
  // 프로젝트 PQ인 경우 프로젝트 선택 필수
  if (data.type === "PROJECT" && !data.projectId) {
    return false
  }
  return true
}, {
  message: "프로젝트 PQ인 경우 프로젝트를 선택해야 합니다",
  path: ["projectId"]
})

type PqListFormData = z.infer<typeof pqListFormSchema>

interface PqListFormProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  initialData?: Partial<PqListFormData> & { id?: number }
  projects?: Project[]
  onSubmit: (data: PqListFormData & { id?: number }) => Promise<void>
  isLoading?: boolean
}

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

export function AddPqDialog({
  open,
  onOpenChange,
  initialData,
  projects = [],
  onSubmit,
  isLoading = false
}: PqListFormProps) {
  const isEditing = !!initialData?.id

  const form = useForm<PqListFormData>({
    resolver: zodResolver(pqListFormSchema),
    defaultValues: {
      name: initialData?.name || "",
      type: initialData?.type || "GENERAL",
      projectId: initialData?.projectId || null,
      validTo: initialData?.validTo || undefined,
    }
  })

  const selectedType = form.watch("type")
  const formState = form.formState

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Plus className="h-5 w-5" />
            {isEditing ? "PQ 목록 수정" : "신규 PQ 목록 생성"}
          </DialogTitle>
          <DialogDescription>
            {isEditing ? "PQ 목록 정보를 수정합니다." : "새로운 PQ 목록을 생성합니다."}
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
            {/* PQ 유형 */}
            <FormField
              control={form.control}
              name="type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="flex items-center gap-1">
                    PQ 유형 <span className="text-red-500">*</span>
                  </FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="PQ 유형을 선택하세요" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {Object.entries(typeLabels).map(([value, label]) => (
                        <SelectItem key={value} value={value}>
                          {label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            {/* PQ 목록 명 */}
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="flex items-center gap-1">
                    PQ 리스트명 <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input
                      placeholder="예: General PQ v2.0, EPC-1234 Project PQ"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 프로젝트 선택 (프로젝트 PQ인 경우만) */}
            {selectedType === "PROJECT" && (
              <FormField
                control={form.control}
                name="projectId"
                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="프로젝트를 선택하세요" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {projects.map((project) => (
                          <SelectItem key={project.id} value={project.id.toString()}>
                            {project.code} - {project.name}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            {/* 유효기간 (프로젝트 PQ인 경우) */}
            {selectedType === "PROJECT" && (
              <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="유효일 선택"
                      />
                    </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" />}
                {isEditing ? "수정" : "생성"}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
} 