"use client"

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

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { toast } from "sonner"

import { createShipbuildingItem, createOffshoreTopItem, createOffshoreHullItem } from "../service"
import { ItemType } from "./delete-items-dialog"

// 조선 공종 유형 정의
const shipbuildingWorkTypes = [
  { label: "기장", value: "기장" },
  { label: "전장", value: "전장" },
  { label: "선실", value: "선실" },
  { label: "배관", value: "배관" },
  { label: "철의", value: "철의" },
] as const

// 선종 유형 정의
const shipTypes = [
  { label: "A-MAX", value: "A-MAX" },
  { label: "S-MAX", value: "S-MAX" },
  { label: "LNGC", value: "LNGC" },
  { label: "VLCC", value: "VLCC" },
  { label: "CONT", value: "CONT" },
] as const

// 해양 TOP 공종 유형 정의
const offshoreTopWorkTypes = [
  { label: "TM", value: "TM" },
  { label: "TS", value: "TS" },
  { label: "TE", value: "TE" },
  { label: "TP", value: "TP" },
] as const

// 해양 HULL 공종 유형 정의
const offshoreHullWorkTypes = [
  { label: "HA", value: "HA" },
  { label: "HE", value: "HE" },
  { label: "HH", value: "HH" },
  { label: "HM", value: "HM" },
  { label: "NC", value: "NC" },
] as const

// 기본 아이템 스키마
const itemFormSchema = z.object({
  itemCode: z.string().min(1, "아이템 코드는 필수입니다"),
  itemName: z.string().min(1, "아이템 명은 필수입니다"),
  description: z.string().optional(),
  workType: z.string().min(1, "공종은 필수입니다"),
  // 조선 아이템 전용 필드
  shipTypes: z.string().optional(),
  // 해양 아이템 전용 필드
  itemList1: z.string().optional(),
  itemList2: z.string().optional(),
  itemList3: z.string().optional(),
  itemList4: z.string().optional(),
})

type ItemFormValues = z.infer<typeof itemFormSchema>

interface AddItemDialogProps {
  itemType: ItemType
}

export function AddItemDialog({ itemType }: AddItemDialogProps) {
  const router = useRouter()
  const [open, setOpen] = React.useState(false)

  // 기본값 설정
  const getDefaultValues = () => {
    const defaults: ItemFormValues = {
      itemCode: "",
      itemName: "",
      description: "",
      workType: getDefaultWorkType(),
    }

    if (itemType === 'shipbuilding') {
      defaults.shipTypes = "A-MAX"
    } else {
      defaults.itemList1 = ""
      defaults.itemList2 = ""
      defaults.itemList3 = ""
      defaults.itemList4 = ""
    }

    return defaults
  }

  const getDefaultWorkType = () => {
    switch (itemType) {
      case 'shipbuilding':
        return "기장"
      case 'offshoreTop':
        return "TM"
      case 'offshoreHull':
        return "HA"
      default:
        return ""
    }
  }

  const form = useForm<ItemFormValues>({
    resolver: zodResolver(itemFormSchema),
    defaultValues: getDefaultValues(),
  })

  const onSubmit = async (data: ItemFormValues) => {
    try {
      switch (itemType) {
        case 'shipbuilding':
          if (!data.shipTypes) {
            toast.error("선종은 필수입니다")
            return
          }
          
          await createShipbuildingItem({
            itemCode: data.itemCode,
            itemName: data.itemName,
            workType: data.workType,
            shipTypes: data.shipTypes,
            description: data.description || null
          });
          break;
        
        case 'offshoreTop':
          await createOffshoreTopItem({
            itemCode: data.itemCode,
            itemName: data.itemName,
            workType: data.workType as "TM" | "TS" | "TE" | "TP",
            description: data.description || null,
            itemList1: data.itemList1 || null,
            itemList2: data.itemList2 || null,
            itemList3: data.itemList3 || null,
            itemList4: data.itemList4 || null
          });
          break;
        
        case 'offshoreHull':
          await createOffshoreHullItem({
            itemCode: data.itemCode,
            itemName: data.itemName,
            workType: data.workType as "HA" | "HE" | "HH" | "HM" | "NC",
            description: data.description || null,
            itemList1: data.itemList1 || null,
            itemList2: data.itemList2 || null,
            itemList3: data.itemList3 || null,
            itemList4: data.itemList4 || null
          });
          break;
        
        default:
          toast.error("지원하지 않는 아이템 타입입니다");
          return;
      }
      
      toast.success("아이템이 성공적으로 추가되었습니다")
      setOpen(false)
      form.reset(getDefaultValues())
      router.refresh()
    } catch (error) {
      toast.error("아이템 추가 중 오류가 발생했습니다")
      console.error(error)
    }
  }

  const getItemTypeLabel = () => {
    switch (itemType) {
      case 'shipbuilding':
        return '조선 아이템';
      case 'offshoreTop':
        return '해양 TOP 아이템';
      case 'offshoreHull':
        return '해양 HULL 아이템';
      default:
        return '아이템';
    }
  }

  const getWorkTypeOptions = () => {
    switch (itemType) {
      case 'shipbuilding':
        return shipbuildingWorkTypes;
      case 'offshoreTop':
        return offshoreTopWorkTypes;
      case 'offshoreHull':
        return offshoreHullWorkTypes;
      default:
        return [];
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button>
          <Plus className="mr-2 h-4 w-4" />
          {getItemTypeLabel()} 추가
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>
            {getItemTypeLabel()} 추가
          </DialogTitle>
          <DialogDescription>
            새로운 {getItemTypeLabel()}을 추가합니다.
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="itemCode"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>아이템 코드</FormLabel>
                  <FormControl>
                    <Input {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="itemName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>아이템 명</FormLabel>
                  <FormControl>
                    <Input {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="workType"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>공종</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="공종을 선택하세요" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {getWorkTypeOptions().map((type) => (
                        <SelectItem key={type.value} value={type.value}>
                          {type.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            {itemType === 'shipbuilding' && (
              <FormField
                control={form.control}
                name="shipTypes"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>선종</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="선종을 선택하세요" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {shipTypes.map((type) => (
                          <SelectItem key={type.value} value={type.value}>
                            {type.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}
            {(itemType === 'offshoreTop' || itemType === 'offshoreHull') && (
              <>
                <FormField
                  control={form.control}
                  name="itemList1"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>아이템 리스트 1</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="itemList2"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>아이템 리스트 2</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="itemList3"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>아이템 리스트 3</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="itemList4"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>아이템 리스트 4</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </>
            )}
            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>설명</FormLabel>
                  <FormControl>
                    <Textarea {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="flex justify-end space-x-2">
              <Button type="button" variant="outline" onClick={() => setOpen(false)}>
                취소
              </Button>
              <Button type="submit">추가</Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}