"use client"

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

import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
// react-hook-form + shadcn/ui Form
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
// shadcn/ui Select
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { createItemSchema, CreateItemSchema } from "../validations"
import { createItem } from "../service"
import { Textarea } from "@/components/ui/textarea"



export function AddItemDialog() {
  const [open, setOpen] = React.useState(false)

  // react-hook-form 세팅
  const form = useForm<CreateItemSchema>({
    resolver: zodResolver(createItemSchema),
    defaultValues: {
      itemCode: "",
      itemName: "",
      description: "",
      parentItemCode: "",
      itemLevel: 5, // 기본값 5
      deleteFlag: "N", // 기본값 N
      unitOfMeasure: "",
      steelType: "",
      gradeMaterial: "",
      changeDate: "",
      baseUnitOfMeasure: "",
    },
  })

  async function onSubmit(data: CreateItemSchema) {
    const result = await createItem({
      itemCode: data.itemCode,
      itemName: data.itemName,
      description: data.description ?? null,
      parentItemCode: data.parentItemCode ?? null,
      itemLevel: data.itemLevel ?? null,
      deleteFlag: data.deleteFlag ?? null,
      unitOfMeasure: data.unitOfMeasure ?? null,
      steelType: data.steelType ?? null,
      gradeMaterial: data.gradeMaterial ?? null,
      changeDate: data.changeDate ?? null,
      baseUnitOfMeasure: data.baseUnitOfMeasure ?? null,
    })
    if (result.error) {
      alert(`에러: ${result.error}`)
      return
    }
    // 성공 시 모달 닫고 폼 리셋
    form.reset()
    setOpen(false)
  }

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

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

      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create New Item</DialogTitle>
          <DialogDescription>
            새 Item 정보를 입력하고 <b>Create</b> 버튼을 누르세요.
          </DialogDescription>
        </DialogHeader>

        {/* shadcn/ui Form을 이용해 react-hook-form과 연결 */}
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="space-y-4 py-4">
              <p className="text-red-500 font-bold text-center">※ MDG에서 수신만 하기에 비활성화할 기능입니다. <br />직접 업로드는 기술영업만 가능</p>
              <FormField
                control={form.control}
                name="itemCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>자재그룹코드 *</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="예: BOLT001"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="itemName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>자재그룹명 *</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="예: 육각볼트 M8x20"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>상세</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="예: 표준 육각 볼트 스테인리스 스틸"
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 2열 레이아웃 */}
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="itemLevel"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>레벨</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min="1"
                          max="5"
                          placeholder="1-5"
                          {...field}
                          value={field.value || ""}
                          onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : null)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="deleteFlag"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>삭제 플래그</FormLabel>
                      <FormControl>
                        <Select onValueChange={field.onChange} defaultValue={field.value || "N"}>
                          <SelectTrigger>
                            <SelectValue placeholder="선택" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="N">N (사용)</SelectItem>
                            <SelectItem value="Y">Y (삭제)</SelectItem>
                          </SelectContent>
                        </Select>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="parentItemCode"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>부모 아이템 코드</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="예: BOLT001"
                          {...field}
                          value={field.value || ""}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="steelType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>강종</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="예: SS, CS, AL"
                          maxLength={2}
                          {...field}
                          value={field.value || ""}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="unitOfMeasure"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>단위</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="예: EA, SET, KG"
                          maxLength={3}
                          {...field}
                          value={field.value || ""}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="baseUnitOfMeasure"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>기본단위</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="예: EA, SET, KG"
                          maxLength={3}
                          {...field}
                          value={field.value || ""}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="gradeMaterial"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>등급 재질</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="예: Marine Grade A"
                          {...field}
                          value={field.value || ""}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="changeDate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>변경일자</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="YYYYMMDD"
                          maxLength={8}
                          {...field}
                          value={field.value || ""}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

            </div>

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