"use client"

import * as React from "react"
import { useState } from "react"
import { toast } from "sonner"

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { MaterialGroupSelector } from "@/components/common/material/material-group-selector"
import { MaterialSearchItem } from "@/lib/material/material-group-service"
import { updateMajorItems } from "../service"

interface MajorItemsUpdateDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  registrationId?: number
  vendorName?: string
  currentItems?: string | null
  onSuccess?: () => void
}

export function MajorItemsUpdateDialog({
  open,
  onOpenChange,
  registrationId,
  vendorName,
  currentItems,
  onSuccess,
}: MajorItemsUpdateDialogProps) {
  const [isLoading, setIsLoading] = useState(false)
  const [selectedMaterials, setSelectedMaterials] = useState<MaterialSearchItem[]>([])

  // 기존 아이템들 파싱 및 초기화
  React.useEffect(() => {
    if (open && currentItems) {
      try {
        const parsedItems = JSON.parse(currentItems)
        if (Array.isArray(parsedItems)) {
          // materialGroupCode와 materialGroupDescription이 있는 항목들만 변환
          const materials = parsedItems
            .filter((item: any) => item.materialGroupCode && item.materialGroupDescription)
            .map((item: any) => ({
              materialGroupCode: item.materialGroupCode,
              materialGroupDescription: item.materialGroupDescription,
              materialGroupUom: item.materialGroupUom,
              displayText: `${item.materialGroupCode} - ${item.materialGroupDescription}`,
            }))
          setSelectedMaterials(materials)
        }
      } catch (error) {
        console.error("기존 주요품목 파싱 오류:", error)
        setSelectedMaterials([])
      }
    } else if (open) {
      setSelectedMaterials([])
    }
  }, [open, currentItems])

  const handleSave = async () => {
    if (!registrationId) {
      toast.error("등록 ID가 없습니다.")
      return
    }

    setIsLoading(true)
    try {
      // MaterialSearchItem을 DB 저장 형식으로 변환
      const itemsToSave = selectedMaterials.map(material => ({
        materialGroupCode: material.materialGroupCode,
        materialGroupDescription: material.materialGroupDescription,
        materialGroupUom: material.materialGroupUom,
      }))

      const result = await updateMajorItems(
        registrationId,
        JSON.stringify(itemsToSave)
      )

      if (result.success) {
        toast.success("주요품목이 업데이트되었습니다.")
        onOpenChange(false)
        onSuccess?.()
      } else {
        toast.error(result.error || "주요품목 업데이트에 실패했습니다.")
      }
    } catch (error) {
      console.error("주요품목 업데이트 오류:", error)
      toast.error("주요품목 업데이트 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="w-[400px] sm:w-[540px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>주요품목 등록</DialogTitle>
          <DialogDescription>
            {vendorName && `${vendorName}의 `}주요품목을 등록해주세요.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 mt-6">
          <div className="space-y-2">
            <Label>자재그룹 검색 및 선택</Label>
            <MaterialGroupSelector
              selectedMaterials={selectedMaterials}
              onMaterialsChange={setSelectedMaterials}
              singleSelect={false}
              placeholder="자재그룹을 검색하세요..."
              noValuePlaceHolder="자재그룹을 선택해주세요"
              closeOnSelect={false}
              showInitialData={true}
            />
            <div className="text-xs text-muted-foreground">
              선택됨: {selectedMaterials.length}개
            </div>
          </div>
        </div>

        <div className="flex justify-end space-x-2 mt-6">
          <Button
            type="button"
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isLoading}
          >
            취소
          </Button>
          <Button 
            onClick={handleSave} 
            disabled={isLoading}
          >
            {isLoading ? "저장 중..." : "저장"}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}
