"use client"

import * as React from "react"
import { useForm } from "react-hook-form"

import { Button } from "@/components/ui/button"
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
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 { toast } from "sonner"

import { 
  modifyShipbuildingItem,
  modifyOffshoreTopItem,
  modifyOffshoreHullItem
} from "../service"
import { ItemType } from "./delete-items-dialog"

const shipbuildingWorkTypes = [
  { value: "기장", label: "기장" },
  { value: "전장", label: "전장" },
  { value: "선실", label: "선실" },
  { value: "배관", label: "배관" },
  { value: "철의", label: "철의" },
  { value: "선체", label: "선체" },
] as const

const offshoreTopWorkTypes = [
  { value: "TM", label: "TM" },
  { value: "TS", label: "TS" },
  { value: "TE", label: "TE" },
  { value: "TP", label: "TP" },
] as const

const offshoreHullWorkTypes = [
  { value: "HA", label: "HA" },
  { value: "HE", label: "HE" },
  { value: "HH", label: "HH" },
  { value: "HM", label: "HM" },
  { value: "HO", label: "HO" },
  { value: "HP", label: "HP" },
  { value: "NC", label: "NC" },
] as const


type ShipbuildingItem = {
  id: number
  itemCode: string
  workType: "기장" | "전장" | "선실" | "배관" | "철의" | "선체"
  shipTypes: string
  itemList: string | null
}

type OffshoreTopItem = {
  id: number
  itemCode: string
  workType: "TM" | "TS" | "TE" | "TP"
  itemList: string | null
  subItemList: string | null
}

type OffshoreHullItem = {
  id: number
  itemCode: string
  workType: "HA" | "HE" | "HH" | "HM" | "HO" | "HP" | "NC"
  itemList: string | null
  subItemList: string | null
}

type UpdateItemSchema = {
  itemCode?: string
  workType?: string
  shipTypes?: string
  itemList?: string
}

interface UpdateItemSheetProps {
  item: ShipbuildingItem | OffshoreTopItem | OffshoreHullItem
  itemType: ItemType
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function UpdateItemSheet({ item, itemType, open, onOpenChange }: UpdateItemSheetProps) {
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  
  // 초기값 설정
  const form = useForm<UpdateItemSchema>({
    defaultValues: {
      workType: item.workType,
      ...getItemTypeSpecificDefaults(item, itemType),
    },
  })

  function getItemTypeSpecificDefaults(
    item: ShipbuildingItem | OffshoreTopItem | OffshoreHullItem, 
    itemType: ItemType
  ) {
    switch (itemType) {
      case 'shipbuilding':
        return {
          shipTypes: (item as ShipbuildingItem).shipTypes,
          itemList: (item as ShipbuildingItem).itemList || "",
        };
      case 'offshoreTop':
      case 'offshoreHull':
        const offshoreItem = item as OffshoreTopItem | OffshoreHullItem;
        return {
          itemList: offshoreItem.itemList || "",
          subItemList: offshoreItem.subItemList || ""
        };
      default:
        return {};
    }
  }

  async function onSubmit(data: UpdateItemSchema) {
    try {
      setIsSubmitting(true)
      let result;
      
      switch (itemType) {
        case 'shipbuilding':
          result = await modifyShipbuildingItem({ 
            ...data, 
            id: item.id,
            itemCode: item.itemCode // itemCode는 변경 불가, 원래 값 사용
          });
          break;
        case 'offshoreTop':
          result = await modifyOffshoreTopItem({ 
            ...data, 
            id: item.id,
            itemCode: item.itemCode // itemCode는 변경 불가, 원래 값 사용
          });
          break;
        case 'offshoreHull':
          result = await modifyOffshoreHullItem({ 
            ...data, 
            id: item.id,
            itemCode: item.itemCode // itemCode는 변경 불가, 원래 값 사용
          });
          break;
        default:
          toast.error("지원하지 않는 아이템 타입입니다");
          return;
      }
      
      if (result.success) {
        toast.success(result.message || "아이템이 수정되었습니다.")
        onOpenChange(false)
      } else {
        toast.error(result.error || "아이템 수정 중 오류가 발생했습니다. 다시 시도해주세요.")
      }
    } catch (error) {
      toast.error("오류가 발생했습니다.")
      console.error(error)
    } finally {
      setIsSubmitting(false)
    }
  }

  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 (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent>
        <SheetHeader>
          <SheetTitle>{getItemTypeLabel()} 수정</SheetTitle>
          <SheetDescription>
            {getItemTypeLabel()} 정보를 수정합니다. 수정할 필드를 입력해주세요.
          </SheetDescription>
        </SheetHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            {/* Material Group을 Form 안으로 이동 */}
            <div className="mt-4">
              <div className="grid gap-2">
                <label className="text-sm font-medium leading-none">
                  Material Group (수정 불가)
                </label>
                <Input value={item.itemCode} disabled readOnly />
              </div>
            </div>
            
            <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>
                      <FormControl>
                        <Input placeholder="선종을 입력하세요" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </>
            )}
                <FormField
                  control={form.control}
                  name="itemList"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>아이템 리스트</FormLabel>
                      <FormControl>
                        <Input placeholder="아이템 리스트를 입력하세요" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
            <SheetFooter>
              <SheetClose asChild>
                <Button variant="outline">취소</Button>
              </SheetClose>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? "수정 중..." : "수정"}
              </Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
} 