"use client"

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

import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { useToast } from "@/hooks/use-toast"
import { createPq, invalidatePqCache } from "../service"

// PQ 생성을 위한 Zod 스키마 정의
const createPqSchema = z.object({
  code: z.string().min(1, "Code is required"),
  checkPoint: z.string().min(1, "Check point is required"),
  groupName: z.string().min(1, "Group is required"),
  description: z.string().optional(),
  remarks: z.string().optional()
});

type CreatePqInputType = z.infer<typeof createPqSchema>;

// 그룹 이름 옵션
const groupOptions = [
  "GENERAL",
  "Quality Management System",
  "Workshop & Environment",
  "Warranty",
];

// 설명 예시 텍스트
const descriptionExample = `Address :
Tel. / Fax :
e-mail :`;

export function AddPqDialog() {
  const [open, setOpen] = React.useState(false)
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const router = useRouter()
  const { toast } = useToast()

  // react-hook-form 설정
  const form = useForm<CreatePqInputType>({
    resolver: zodResolver(createPqSchema),
    defaultValues: {
      code: "",
      checkPoint: "",
      groupName: groupOptions[0],
      description: "",
      remarks: ""
    },
  })

  // 예시 텍스트를 description 필드에 채우는 함수
  const fillExampleText = () => {
    form.setValue("description", descriptionExample);
  };

  async function onSubmit(data: CreatePqInputType) {
    try {
      setIsSubmitting(true)
      
      // 서버 액션 호출
      const result = await createPq(data)
      
      if (!result.success) {
        toast({
          title: "Error",
          description: result.message || "Failed to create PQ criteria",
          variant: "destructive",
        })
        return
      }

      await invalidatePqCache();
      
      // 성공 시 처리
      toast({
        title: "Success",
        description: "PQ criteria created successfully",
      })
      
      // 모달 닫고 폼 리셋
      form.reset()
      setOpen(false)
      
      // 페이지 새로고침
      router.refresh()
      
    } catch (error) {
      console.error('Error creating PQ criteria:', error)
      toast({
        title: "Error",
        description: "An unexpected error occurred",
        variant: "destructive",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  function handleDialogOpenChange(nextOpen: boolean) {
    if (!nextOpen) {
      form.reset()
    }
    setOpen(nextOpen)
  }

  return (
    <Dialog open={open} onOpenChange={handleDialogOpenChange}>
      {/* 모달을 열기 위한 버튼 */}
      <DialogTrigger asChild>
        <Button variant="default" size="sm">
          <Plus className="size-4" />
          Add PQ
        </Button>
      </DialogTrigger>

      <DialogContent className="sm:max-w-[550px]">
        <DialogHeader>
          <DialogTitle>Create New PQ Criteria</DialogTitle>
          <DialogDescription>
            새 PQ 기준 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
          </DialogDescription>
        </DialogHeader>

        {/* shadcn/ui Form을 이용해 react-hook-form과 연결 */}
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4 py-2">
            {/* Code 필드 */}
            <FormField
              control={form.control}
              name="code"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Code <span className="text-destructive">*</span></FormLabel>
                  <FormControl>
                    <Input
                      placeholder="예: 1-1, A.2.3"
                      {...field}
                    />
                  </FormControl>
                  <FormDescription>
                    PQ 항목의 고유 코드를 입력하세요 (예: "1-1", "A.2.3")
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Check Point 필드 */}
            <FormField
              control={form.control}
              name="checkPoint"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Check Point <span className="text-destructive">*</span></FormLabel>
                  <FormControl>
                    <Input
                      placeholder="검증 항목을 입력하세요"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Group Name 필드 (Select) */}
            <FormField
              control={form.control}
              name="groupName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Group <span className="text-destructive">*</span></FormLabel>
                  <Select 
                    onValueChange={field.onChange} 
                    defaultValue={field.value}
                    value={field.value}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="그룹을 선택하세요" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {groupOptions.map((group) => (
                        <SelectItem key={group} value={group}>
                          {group}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormDescription>
                    PQ 항목의 분류 그룹을 선택하세요
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Description 필드 - 예시 템플릿 버튼 추가 */}
            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <div className="flex items-center justify-between">
                    <FormLabel>Description</FormLabel>
                    <Button 
                      type="button" 
                      variant="outline" 
                      size="sm" 
                      onClick={fillExampleText}
                    >
                      예시 채우기
                    </Button>
                  </div>
                  <FormControl>
                    <Textarea
                      placeholder={`줄바꿈을 포함한 상세 설명을 입력하세요\n예:\n${descriptionExample}`}
                      className="min-h-[120px] font-mono"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormDescription>
                    줄바꿈이 필요한 경우 Enter 키를 누르세요. 입력한 대로 저장됩니다.
                  </FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Remarks 필드 */}
            <FormField
              control={form.control}
              name="remarks"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Remarks</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="비고 사항을 입력하세요"
                      className="min-h-[80px]"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                    form.reset(); 
                    setOpen(false);
                  }}
              >
                Cancel
              </Button>
              <Button 
                type="submit" 
                disabled={isSubmitting}
              >
                {isSubmitting ? "Creating..." : "Create"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}