import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Badge } from "./ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "./ui/alert-dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Label } from "./ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Checkbox } from "./ui/checkbox";
import { RadioGroup, RadioGroupItem } from "./ui/radio-group";
import { Separator } from "./ui/separator";
import { 
  Box, 
  Plus, 
  Search, 
  Edit, 
  Trash2,
  Package,
  ChevronRight,
  Settings2,
  FileText
} from "lucide-react";

interface Product {
  id: string;
  code: string;
  name: string;
  lotNumber: string;
  description: string;
  status: "활성" | "비활성";
  category?: string;
  bomItems?: BOMItem[];
}

interface BOMItem {
  id: string;
  type: "인정" | "비인정";
  itemType: "자재" | "부품";
  itemCode: string;
  itemName: string;
  specification: string;
  quantity: number;
  unit: string;
  // 비인정인 경우 사이즈 정보
  width?: number;
  height?: number;
  length?: number;
  thickness?: number;
  note?: string;
}

interface AvailableItem {
  id: string;
  type: string;
  code: string;
  name: string;
  specification: string;
  unit: string;
  defaultQty: number;
}

export function ProductManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("all");
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [currentTab, setCurrentTab] = useState("basic");
  
  // BOM 관리
  const [bomCategory, setBomCategory] = useState("BOM관리");
  const [isItemSelectOpen, setIsItemSelectOpen] = useState(false);
  const [currentBomGroup, setCurrentBomGroup] = useState<string | null>(null);
  const [bomItems, setBomItems] = useState<BOMItem[]>([]);
  const [itemSearchTerm, setItemSearchTerm] = useState("");
  
  // 인정/비인정 BOM 항목 추가
  const [recognitionType, setRecognitionType] = useState<"인정" | "비인정">("인정");
  const [selectedItemType, setSelectedItemType] = useState<"자재" | "부품">("자재");
  
  // 비인정 직접 입력 폼
  const [manualBomItem, setManualBomItem] = useState({
    itemCode: "",
    itemName: "",
    specification: "",
    quantity: 1,
    unit: "EA",
    width: 0,
    height: 0,
    length: 0,
    thickness: 0,
    note: ""
  });
  
  // 신규 제품
  const [newProduct, setNewProduct] = useState<Partial<Product>>({
    code: "",
    name: "",
    lotNumber: "",
    description: "",
    status: "활성"
  });

  // 샘플 제품 데이터
  const [products, setProducts] = useState<Product[]>([
    {
      id: "1",
      code: "KS501",
      name: "스크린센터",
      lotNumber: "SS",
      description: "스크린센터",
      status: "활성"
    },
    {
      id: "2",
      code: "KWK503",
      name: "대형 세터",
      lotNumber: "WS",
      description: "11700*8500 이상",
      status: "비활성"
    },
    {
      id: "3",
      code: "KOTS01",
      name: "플랫 세터",
      lotNumber: "TS",
      description: "플랫 세터(+수지형)",
      status: "활성"
    }
  ]);

  // 사용 가능한 품목 목록
  const availableItems: AvailableItem[] = [
    { id: "1", type: "자재", code: "K-BE-C-E-E0R1330", name: "몸판판", specification: "몸판판-KEU-EAT-'919*3000", unit: "SET", defaultQty: 1 },
    { id: "2", type: "부품", code: "H-SC-S-X-KF02*700", name: "신액배션", specification: "", unit: "SET", defaultQty: 1 },
    { id: "3", type: "자재", code: "K-BE-C-E-E0R2045", name: "몸판판", specification: "몸판판-KEU-I-SET-'125*425", unit: "SET", defaultQty: 1 },
    { id: "4", type: "부품", code: "H-SC-S-X-KF02*C80122", name: "신액배션", specification: "신액배션스크린-U220", unit: "SET", defaultQty: 1 },
    { id: "5", type: "자재", code: "P-ET-C-S-KWS01", name: "관산판", specification: "관산판 스크린(콘솔내판)", unit: "SET", defaultQty: 0 },
    { id: "6", type: "부품", code: "K-ET-C-X-YT01", name: "국제판", specification: "국제판-스틸샷", unit: "SET", defaultQty: 0 },
    { id: "7", type: "자재", code: "P-ET-S-X-YM01", name: "국제판", specification: "국제판-스틸샷", unit: "SET", defaultQty: 0 },
    { id: "8", type: "부품", code: "P-ET-S-X-KGT5001", name: "관산판", specification: "관산판 스크린(콘솔내판)", unit: "SET", defaultQty: 0 },
    { id: "9", type: "자재", code: "P-ET-S-X-KGT1902", name: "버튼판", specification: "버튼판 스크린(콘솔)", unit: "SET", defaultQty: 0 },
    { id: "10", type: "부품", code: "P-ET-S-B-S450", name: "국제판", specification: "국제판 스크린(콘솔)", unit: "SET", defaultQty: 0 }
  ];

  // BOM 그룹 샘플 데이터
  const bomGroups = [
    { id: "g1", name: "분류 ID: 3", items: 2 },
    { id: "g2", name: "분류 ID: 4", items: 2 }
  ];

  const filteredProducts = products.filter(product => {
    const matchesSearch = product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         product.code.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = selectedStatus === "all" || product.status === selectedStatus;
    return matchesSearch && matchesStatus;
  });

  const filteredItems = availableItems.filter(item => {
    return item.name.toLowerCase().includes(itemSearchTerm.toLowerCase()) ||
           item.code.toLowerCase().includes(itemSearchTerm.toLowerCase());
  });

  const handleEdit = (product: Product) => {
    setSelectedProduct(product);
    if (product.bomItems) {
      setBomItems(product.bomItems);
    } else {
      setBomItems([]);
    }
    setIsEditDialogOpen(true);
  };

  const handleDelete = (product: Product) => {
    setSelectedProduct(product);
    setIsDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    if (selectedProduct) {
      setProducts(products.filter(p => p.id !== selectedProduct.id));
      setIsDeleteDialogOpen(false);
      setSelectedProduct(null);
    }
  };

  const handleAddProduct = () => {
    const productToAdd: Product = {
      id: `${Date.now()}`,
      code: newProduct.code || "",
      name: newProduct.name || "",
      lotNumber: newProduct.lotNumber || "",
      description: newProduct.description || "",
      status: newProduct.status || "활성",
      bomItems: bomItems
    };
    
    setProducts([...products, productToAdd]);
    setIsAddDialogOpen(false);
    setNewProduct({
      code: "",
      name: "",
      lotNumber: "",
      description: "",
      status: "활성"
    });
    setBomItems([]);
  };

  const handleUpdateProduct = () => {
    if (selectedProduct) {
      setProducts(products.map(p => 
        p.id === selectedProduct.id 
          ? { ...selectedProduct, bomItems } 
          : p
      ));
      setIsEditDialogOpen(false);
      setSelectedProduct(null);
    }
  };

  const handleAddBomItems = (selectedIds: string[]) => {
    const itemsToAdd = availableItems
      .filter(item => selectedIds.includes(item.id))
      .map(item => ({
        id: `bom-${Date.now()}-${item.id}`,
        type: "인정" as const,
        itemType: item.type as "자재" | "부품",
        itemCode: item.code,
        itemName: item.name,
        specification: item.specification,
        quantity: item.defaultQty,
        unit: item.unit
      }));
    
    setBomItems([...bomItems, ...itemsToAdd]);
    setIsItemSelectOpen(false);
    setItemSearchTerm("");
  };

  const stats = {
    total: products.length,
    active: products.filter(p => p.status === "활성").length,
    inactive: products.filter(p => p.status === "비활성").length
  };

  return (
    <div className="p-6 space-y-6">
      {/* 헤더 */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold text-foreground flex items-center gap-3">
            <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
              <Box className="h-6 w-6 text-blue-600" />
            </div>
            제품 관리
          </h1>
          <p className="text-muted-foreground mt-1">제품(BOM) 등록 및 관리</p>
        </div>
        <div className="flex gap-2">
          <Button 
            className="bg-blue-600 hover:bg-blue-700"
            onClick={() => setIsAddDialogOpen(true)}
          >
            <Plus className="h-4 w-4 mr-2" />
            제품 등록
          </Button>
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <Card className="border-l-4 border-l-blue-500">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-muted-foreground">전체 제품</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-blue-600">{stats.total}</div>
            <p className="text-xs text-muted-foreground mt-1">등록된 제품 수</p>
          </CardContent>
        </Card>

        <Card className="border-l-4 border-l-green-500">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-muted-foreground">활성 제품</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-green-600">{stats.active}</div>
            <p className="text-xs text-muted-foreground mt-1">판매/생산 가능</p>
          </CardContent>
        </Card>

        <Card className="border-l-4 border-l-gray-500">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm text-muted-foreground">비활성 제품</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-gray-600">{stats.inactive}</div>
            <p className="text-xs text-muted-foreground mt-1">단종/개발중</p>
          </CardContent>
        </Card>
      </div>

      {/* 검색 및 필터 */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="제품코드/명 검색..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={selectedStatus} onValueChange={setSelectedStatus}>
              <SelectTrigger className="w-full md:w-48">
                <SelectValue placeholder="상태" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">전체 상태</SelectItem>
                <SelectItem value="활성">활성</SelectItem>
                <SelectItem value="비활성">비활성</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* 제품 목록 */}
      <Card>
        <CardContent className="pt-6">
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-32">제품코드</TableHead>
                  <TableHead>제품명</TableHead>
                  <TableHead className="w-24">로트도</TableHead>
                  <TableHead>설명</TableHead>
                  <TableHead className="w-24 text-center">상태</TableHead>
                  <TableHead className="w-32 text-right">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredProducts.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                      등록된 제품이 없습니다.
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredProducts.map((product) => (
                    <TableRow key={product.id}>
                      <TableCell className="font-mono text-sm">{product.code}</TableCell>
                      <TableCell className="font-medium">{product.name}</TableCell>
                      <TableCell className="text-sm">{product.lotNumber}</TableCell>
                      <TableCell className="text-sm text-muted-foreground">{product.description}</TableCell>
                      <TableCell className="text-center">
                        <Badge 
                          className={
                            product.status === "활성" 
                              ? "bg-green-500 text-white hover:bg-green-600" 
                              : "bg-gray-500 text-white hover:bg-gray-600"
                          }
                        >
                          {product.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button 
                            variant="outline" 
                            size="sm"
                            onClick={() => handleEdit(product)}
                          >
                            수정
                          </Button>
                          <Button 
                            variant="outline" 
                            size="sm"
                            className="text-red-600 hover:text-red-700"
                            onClick={() => handleDelete(product)}
                          >
                            삭제
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 신규 제품 등록 다이얼로그 */}
      <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>제품(BOM) 수정</DialogTitle>
            <DialogDescription>
              제품 정보와 BOM(자재 명세서)을 등록합니다.
            </DialogDescription>
          </DialogHeader>

          <div className="grid grid-cols-12 gap-6">
            {/* 왼쪽 사이드바 */}
            <div className="col-span-2 space-y-2">
              <div className="text-sm font-medium mb-2">카테고리</div>
              <Button
                variant={bomCategory === "BOM관리" ? "default" : "ghost"}
                className="w-full justify-start"
                onClick={() => setBomCategory("BOM관리")}
              >
                BOM관리
              </Button>
              <Button
                variant={bomCategory === "품목" ? "default" : "ghost"}
                className="w-full justify-start"
                onClick={() => setBomCategory("품목")}
              >
                품목
              </Button>
              <Button
                variant={bomCategory === "불량" ? "default" : "ghost"}
                className="w-full justify-start"
                onClick={() => setBomCategory("불량")}
              >
                불량
              </Button>
            </div>

            {/* 메인 콘텐츠 */}
            <div className="col-span-10 space-y-6">
              {bomCategory === "BOM관리" && (
                <>
                  {/* 기본 정보 */}
                  <div className="grid grid-cols-4 gap-4">
                    <div className="space-y-2">
                      <Label>코드</Label>
                      <Input 
                        value={newProduct.code}
                        onChange={(e) => setNewProduct({...newProduct, code: e.target.value})}
                        placeholder="PR-A-SS001"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>제품 명</Label>
                      <Input 
                        value={newProduct.name}
                        onChange={(e) => setNewProduct({...newProduct, name: e.target.value})}
                        placeholder="강화판"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>제품분류</Label>
                      <Select>
                        <SelectTrigger>
                          <SelectValue placeholder="제품" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="product">제품</SelectItem>
                          <SelectItem value="part">부품</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label>단위</Label>
                      <Input placeholder="ea" />
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <Label>1차카테고리</Label>
                      <Select>
                        <SelectTrigger>
                          <SelectValue placeholder="1차카테고리" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="metal">금속</SelectItem>
                          <SelectItem value="plastic">플라스틱</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label>2차카테고리</Label>
                      <Select>
                        <SelectTrigger>
                          <SelectValue placeholder="2차카테고리" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="steel">철강</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label>3차카테고리</Label>
                      <Select>
                        <SelectTrigger>
                          <SelectValue placeholder="3차카테고리" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="sheet">판재</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>규격 모델(코기)</Label>
                      <Input 
                        value={newProduct.lotNumber}
                        onChange={(e) => setNewProduct({...newProduct, lotNumber: e.target.value})}
                        placeholder="EGI-1.1ST-1219*3000"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>설명</Label>
                      <Input 
                        value={newProduct.description}
                        onChange={(e) => setNewProduct({...newProduct, description: e.target.value})}
                        placeholder="철 국 판"
                      />
                    </div>
                  </div>

                  <Separator />

                  {/* 상태 플래그 */}
                  <div className="space-y-2">
                    <Label>상태 플래그</Label>
                    <div className="flex gap-6">
                      <div className="flex items-center space-x-2">
                        <Checkbox id="sellable" />
                        <Label htmlFor="sellable" className="cursor-pointer">판매 가능</Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Checkbox id="purchasable" />
                        <Label htmlFor="purchasable" className="cursor-pointer">구매 가능</Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Checkbox id="producible" defaultChecked />
                        <Label htmlFor="producible" className="cursor-pointer">생산 가능</Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Checkbox id="active" defaultChecked />
                        <Label htmlFor="active" className="cursor-pointer">활성</Label>
                      </div>
                    </div>
                  </div>

                  <Separator />

                  {/* 규격 정보 */}
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label>규격 정보</Label>
                      <Button size="sm" variant="outline">
                        <Plus className="h-4 w-4 mr-2" />
                        규격 추가
                      </Button>
                    </div>
                    <div className="rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-12">#</TableHead>
                            <TableHead>속성</TableHead>
                            <TableHead>값</TableHead>
                            <TableHead>단위</TableHead>
                            <TableHead className="w-20 text-center">적용</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          <TableRow>
                            <TableCell className="text-center">1</TableCell>
                            <TableCell>두께</TableCell>
                            <TableCell>1.5</TableCell>
                            <TableCell>T</TableCell>
                            <TableCell className="text-center">
                              <Checkbox defaultChecked />
                            </TableCell>
                          </TableRow>
                        </TableBody>
                      </Table>
                    </div>
                  </div>

                  <Separator />

                  {/* BOM 품목 목록 */}
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label>BOM 품목 구성</Label>
                      <Button 
                        size="sm" 
                        className="bg-blue-600 hover:bg-blue-700"
                        onClick={() => setIsItemSelectOpen(true)}
                      >
                        <Plus className="h-4 w-4 mr-2" />
                        품목 추가 (인정/비인정)
                      </Button>
                    </div>

                    <div className="rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-12">#</TableHead>
                            <TableHead className="w-20">방식</TableHead>
                            <TableHead className="w-20">품목</TableHead>
                            <TableHead>코드</TableHead>
                            <TableHead>명칭</TableHead>
                            <TableHead>규격</TableHead>
                            <TableHead>사이즈 (W×H×L×T)</TableHead>
                            <TableHead className="w-20">단위</TableHead>
                            <TableHead className="w-20">수량</TableHead>
                            <TableHead className="w-20">작업</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {bomItems.length === 0 ? (
                            <TableRow>
                              <TableCell colSpan={10} className="text-center py-8 text-muted-foreground">
                                부품 선택 버튼을 클릭하여 BOM 품목을 추가하세요.
                              </TableCell>
                            </TableRow>
                          ) : (
                            bomItems.map((item, index) => (
                              <TableRow key={item.id}>
                                <TableCell className="text-center">{index + 1}</TableCell>
                                <TableCell>
                                  <Badge 
                                    variant="outline" 
                                    className={
                                      item.type === "인정" 
                                        ? "bg-green-50 text-green-700 border-green-200" 
                                        : "bg-orange-50 text-orange-700 border-orange-200"
                                    }
                                  >
                                    {item.type}
                                  </Badge>
                                </TableCell>
                                <TableCell>
                                  <Badge variant="outline">
                                    {item.itemType}
                                  </Badge>
                                </TableCell>
                                <TableCell className="font-mono text-sm">{item.itemCode}</TableCell>
                                <TableCell>{item.itemName}</TableCell>
                                <TableCell className="text-sm text-muted-foreground">
                                  {item.specification || '-'}
                                </TableCell>
                                <TableCell className="text-sm text-muted-foreground">
                                  {item.type === "비인정" ? (
                                    <span>
                                      {item.width || 0}×{item.height || 0}×{item.length || 0}×{item.thickness || 0}mm
                                    </span>
                                  ) : (
                                    <span>-</span>
                                  )}
                                </TableCell>
                                <TableCell>{item.unit}</TableCell>
                                <TableCell>
                                  <Input 
                                    type="number" 
                                    value={item.quantity}
                                    onChange={(e) => {
                                      const updated = [...bomItems];
                                      updated[index].quantity = parseInt(e.target.value) || 0;
                                      setBomItems(updated);
                                    }}
                                    className="w-16"
                                  />
                                </TableCell>
                                <TableCell>
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    className="text-red-600"
                                    onClick={() => {
                                      setBomItems(bomItems.filter((_, i) => i !== index));
                                    }}
                                  >
                                    삭제
                                  </Button>
                                </TableCell>
                              </TableRow>
                            ))
                          )}
                        </TableBody>
                      </Table>
                    </div>
                  </div>
                </>
              )}

              {bomCategory === "품목" && (
                <div className="text-center py-12 text-muted-foreground">
                  품목 관리 기능
                </div>
              )}

              {bomCategory === "불량" && (
                <div className="text-center py-12 text-muted-foreground">
                  불량 관리 기능
                </div>
              )}
            </div>
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button variant="outline" onClick={() => setIsAddDialogOpen(false)}>
              취소
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleAddProduct}>
              저장
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 수정 다이얼로그 (신규와 동일한 구조) */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>제품(BOM) 수정</DialogTitle>
            <DialogDescription>
              제품 정보와 BOM(자재 명세서)을 수정합니다.
            </DialogDescription>
          </DialogHeader>

          {selectedProduct && (
            <div className="grid grid-cols-12 gap-6">
              {/* 왼쪽 사이드바 */}
              <div className="col-span-2 space-y-2">
                <div className="text-sm font-medium mb-2">카테고리</div>
                <Button
                  variant={bomCategory === "BOM관리" ? "default" : "ghost"}
                  className="w-full justify-start"
                  onClick={() => setBomCategory("BOM관리")}
                >
                  BOM관리
                </Button>
                <Button
                  variant={bomCategory === "품목" ? "default" : "ghost"}
                  className="w-full justify-start"
                  onClick={() => setBomCategory("품목")}
                >
                  품목
                </Button>
                <Button
                  variant={bomCategory === "불량" ? "default" : "ghost"}
                  className="w-full justify-start"
                  onClick={() => setBomCategory("불량")}
                >
                  불량
                </Button>
              </div>

              {/* 메인 콘텐츠 */}
              <div className="col-span-10 space-y-6">
                {bomCategory === "BOM관리" && (
                  <>
                    <div className="grid grid-cols-4 gap-4">
                      <div className="space-y-2">
                        <Label>코드</Label>
                        <Input 
                          value={selectedProduct.code}
                          onChange={(e) => setSelectedProduct({...selectedProduct, code: e.target.value})}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>제품 명</Label>
                        <Input 
                          value={selectedProduct.name}
                          onChange={(e) => setSelectedProduct({...selectedProduct, name: e.target.value})}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>제품분류</Label>
                        <Select defaultValue="product">
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="product">제품</SelectItem>
                            <SelectItem value="part">부품</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="space-y-2">
                        <Label>단위</Label>
                        <Input defaultValue="ea" />
                      </div>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label>규격 모델(코기)</Label>
                        <Input 
                          value={selectedProduct.lotNumber}
                          onChange={(e) => setSelectedProduct({...selectedProduct, lotNumber: e.target.value})}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>설명</Label>
                        <Input 
                          value={selectedProduct.description}
                          onChange={(e) => setSelectedProduct({...selectedProduct, description: e.target.value})}
                        />
                      </div>
                    </div>

                    <Separator />

                    {/* BOM 품목 목록 */}
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <Label>BOM 품목 구성</Label>
                        <Button 
                          size="sm" 
                          className="bg-blue-600 hover:bg-blue-700"
                          onClick={() => setIsItemSelectOpen(true)}
                        >
                          <Plus className="h-4 w-4 mr-2" />
                          품목 추가 (인정/비인정)
                        </Button>
                      </div>

                      <div className="rounded-md border">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead className="w-12">#</TableHead>
                              <TableHead className="w-20">방식</TableHead>
                              <TableHead className="w-20">품목</TableHead>
                              <TableHead>코드</TableHead>
                              <TableHead>명칭</TableHead>
                              <TableHead>규격</TableHead>
                              <TableHead>사이즈 (W×H×L×T)</TableHead>
                              <TableHead className="w-20">단위</TableHead>
                              <TableHead className="w-20">수량</TableHead>
                              <TableHead className="w-20">작업</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {bomItems.length === 0 ? (
                              <TableRow>
                                <TableCell colSpan={10} className="text-center py-8 text-muted-foreground">
                                  부품 선택 버튼을 클릭하여 BOM 품목을 추가하세요.
                                </TableCell>
                              </TableRow>
                            ) : (
                              bomItems.map((item, index) => (
                                <TableRow key={item.id}>
                                  <TableCell className="text-center">{index + 1}</TableCell>
                                  <TableCell>
                                    <Badge 
                                      variant="outline" 
                                      className={
                                        item.type === "인정" 
                                          ? "bg-green-50 text-green-700 border-green-200" 
                                          : "bg-orange-50 text-orange-700 border-orange-200"
                                      }
                                    >
                                      {item.type}
                                    </Badge>
                                  </TableCell>
                                  <TableCell>
                                    <Badge variant="outline">
                                      {item.itemType}
                                    </Badge>
                                  </TableCell>
                                  <TableCell className="font-mono text-sm">{item.itemCode}</TableCell>
                                  <TableCell>{item.itemName}</TableCell>
                                  <TableCell className="text-sm text-muted-foreground">
                                    {item.specification || '-'}
                                  </TableCell>
                                  <TableCell className="text-sm text-muted-foreground">
                                    {item.type === "비인정" ? (
                                      <span>
                                        {item.width || 0}×{item.height || 0}×{item.length || 0}×{item.thickness || 0}mm
                                      </span>
                                    ) : (
                                      <span>-</span>
                                    )}
                                  </TableCell>
                                  <TableCell>{item.unit}</TableCell>
                                  <TableCell>
                                    <Input 
                                      type="number" 
                                      value={item.quantity}
                                      onChange={(e) => {
                                        const updated = [...bomItems];
                                        updated[index].quantity = parseInt(e.target.value) || 0;
                                        setBomItems(updated);
                                      }}
                                      className="w-16"
                                    />
                                  </TableCell>
                                  <TableCell>
                                    <Button
                                      variant="outline"
                                      size="sm"
                                      className="text-red-600"
                                      onClick={() => {
                                        setBomItems(bomItems.filter((_, i) => i !== index));
                                      }}
                                    >
                                      삭제
                                    </Button>
                                  </TableCell>
                                </TableRow>
                              ))
                            )}
                          </TableBody>
                        </Table>
                      </div>
                    </div>
                  </>
                )}
              </div>
            </div>
          )}

          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>
              취소
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700" onClick={handleUpdateProduct}>
              저장
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* BOM 품목 추가 다이얼로그 (인정/비인정) */}
      <Dialog open={isItemSelectOpen} onOpenChange={setIsItemSelectOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>BOM 품목 추가</DialogTitle>
            <DialogDescription>
              인정/비인정 방식을 선택하고 자재/부품을 추가하세요.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* 1단계: 인정/비인정 선택 */}
            <Card className="border-2 border-blue-200 bg-blue-50/30">
              <CardHeader className="pb-3">
                <CardTitle className="text-sm">1단계: 품목 등록 방식 선택</CardTitle>
              </CardHeader>
              <CardContent>
                <RadioGroup 
                  value={recognitionType} 
                  onValueChange={(value: "인정" | "비인정") => setRecognitionType(value)}
                  className="flex gap-6"
                >
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="인정" id="recognized" />
                    <Label htmlFor="recognized" className="cursor-pointer flex items-center gap-2">
                      <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
                        인정
                      </Badge>
                      <span>등록된 자재/부품에서 선택</span>
                    </Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="비인정" id="unrecognized" />
                    <Label htmlFor="unrecognized" className="cursor-pointer flex items-center gap-2">
                      <Badge variant="outline" className="bg-orange-50 text-orange-700 border-orange-200">
                        비인정
                      </Badge>
                      <span>사이즈 직접 입력</span>
                    </Label>
                  </div>
                </RadioGroup>
              </CardContent>
            </Card>

            {/* 2단계: 품목 유형 선택 */}
            <Card className="border-2 border-purple-200 bg-purple-50/30">
              <CardHeader className="pb-3">
                <CardTitle className="text-sm">2단계: 품목 유형 선택</CardTitle>
              </CardHeader>
              <CardContent>
                <RadioGroup 
                  value={selectedItemType} 
                  onValueChange={(value: "자재" | "부품") => setSelectedItemType(value)}
                  className="flex gap-6"
                >
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="자재" id="material" />
                    <Label htmlFor="material" className="cursor-pointer">
                      <Badge variant="outline" className="bg-blue-50 text-blue-700">자재</Badge>
                    </Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="부품" id="part" />
                    <Label htmlFor="part" className="cursor-pointer">
                      <Badge variant="outline" className="bg-purple-50 text-purple-700">부품</Badge>
                    </Label>
                  </div>
                </RadioGroup>
              </CardContent>
            </Card>

            <Separator />

            {/* 3단계: 인정 - 등록된 품목에서 선택 */}
            {recognitionType === "인정" && (
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <Label className="text-base">등록된 {selectedItemType} 목록</Label>
                  <div className="text-sm text-muted-foreground">
                    {filteredItems.filter(i => i.type === selectedItemType).length}개
                  </div>
                </div>

                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder={`${selectedItemType} 검색...`}
                      value={itemSearchTerm}
                      onChange={(e) => setItemSearchTerm(e.target.value)}
                      className="pl-10"
                    />
                  </div>
                </div>

                <div className="rounded-md border max-h-96 overflow-y-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-12">선택</TableHead>
                        <TableHead>코드</TableHead>
                        <TableHead>명칭</TableHead>
                        <TableHead>규격</TableHead>
                        <TableHead>단위</TableHead>
                        <TableHead className="text-right">기본수량</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredItems
                        .filter(item => item.type === selectedItemType)
                        .map((item) => (
                          <TableRow key={item.id}>
                            <TableCell>
                              <Checkbox id={`item-${item.id}`} />
                            </TableCell>
                            <TableCell className="font-mono text-sm">{item.code}</TableCell>
                            <TableCell>{item.name}</TableCell>
                            <TableCell className="text-sm text-muted-foreground">
                              {item.specification || '-'}
                            </TableCell>
                            <TableCell>{item.unit}</TableCell>
                            <TableCell className="text-right">{item.defaultQty}</TableCell>
                          </TableRow>
                        ))}
                    </TableBody>
                  </Table>
                </div>
              </div>
            )}

            {/* 3단계: 비인정 - 직접 입력 */}
            {recognitionType === "비인정" && (
              <div className="space-y-4">
                <Label className="text-base">품목 정보 직접 입력</Label>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>품목 코드 *</Label>
                    <Input
                      placeholder="예: MAT-CUSTOM-001"
                      value={manualBomItem.itemCode}
                      onChange={(e) => setManualBomItem({...manualBomItem, itemCode: e.target.value})}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>품목명 *</Label>
                    <Input
                      placeholder="예: 알루미늄 판재"
                      value={manualBomItem.itemName}
                      onChange={(e) => setManualBomItem({...manualBomItem, itemName: e.target.value})}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label>규격</Label>
                  <Input
                    placeholder="예: SUS304"
                    value={manualBomItem.specification}
                    onChange={(e) => setManualBomItem({...manualBomItem, specification: e.target.value})}
                  />
                </div>

                <Separator />

                <Label className="text-base">사이즈 정보</Label>

                <div className="grid grid-cols-4 gap-4">
                  <div className="space-y-2">
                    <Label>폭 (W)</Label>
                    <div className="flex gap-2">
                      <Input
                        type="number"
                        placeholder="0"
                        value={manualBomItem.width || ""}
                        onChange={(e) => setManualBomItem({...manualBomItem, width: Number(e.target.value)})}
                      />
                      <span className="flex items-center text-sm text-muted-foreground">mm</span>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label>높이 (H)</Label>
                    <div className="flex gap-2">
                      <Input
                        type="number"
                        placeholder="0"
                        value={manualBomItem.height || ""}
                        onChange={(e) => setManualBomItem({...manualBomItem, height: Number(e.target.value)})}
                      />
                      <span className="flex items-center text-sm text-muted-foreground">mm</span>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label>길이 (L)</Label>
                    <div className="flex gap-2">
                      <Input
                        type="number"
                        placeholder="0"
                        value={manualBomItem.length || ""}
                        onChange={(e) => setManualBomItem({...manualBomItem, length: Number(e.target.value)})}
                      />
                      <span className="flex items-center text-sm text-muted-foreground">mm</span>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label>두께 (T)</Label>
                    <div className="flex gap-2">
                      <Input
                        type="number"
                        placeholder="0"
                        value={manualBomItem.thickness || ""}
                        onChange={(e) => setManualBomItem({...manualBomItem, thickness: Number(e.target.value)})}
                      />
                      <span className="flex items-center text-sm text-muted-foreground">mm</span>
                    </div>
                  </div>
                </div>

                <Separator />

                <div className="grid grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label>수량 *</Label>
                    <Input
                      type="number"
                      placeholder="1"
                      value={manualBomItem.quantity}
                      onChange={(e) => setManualBomItem({...manualBomItem, quantity: Number(e.target.value)})}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>단위 *</Label>
                    <Select 
                      value={manualBomItem.unit} 
                      onValueChange={(value) => setManualBomItem({...manualBomItem, unit: value})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="EA">EA</SelectItem>
                        <SelectItem value="M">M</SelectItem>
                        <SelectItem value="SET">SET</SelectItem>
                        <SelectItem value="KG">KG</SelectItem>
                        <SelectItem value="BOX">BOX</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2 col-span-1">
                    <Label>비고</Label>
                    <Input
                      placeholder="비고"
                      value={manualBomItem.note}
                      onChange={(e) => setManualBomItem({...manualBomItem, note: e.target.value})}
                    />
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button variant="outline" onClick={() => {
              setIsItemSelectOpen(false);
              setItemSearchTerm("");
              setRecognitionType("인정");
              setSelectedItemType("자재");
              setManualBomItem({
                itemCode: "",
                itemName: "",
                specification: "",
                quantity: 1,
                unit: "EA",
                width: 0,
                height: 0,
                length: 0,
                thickness: 0,
                note: ""
              });
            }}>
              취소
            </Button>
            <Button 
              className="bg-blue-600 hover:bg-blue-700"
              onClick={() => {
                if (recognitionType === "인정") {
                  // 선택된 항목들의 ID를 수집 (실제로는 체크박스 상태를 추적해야 함)
                  const selectedIds = filteredItems
                    .filter(i => i.type === selectedItemType)
                    .slice(0, 2)
                    .map(i => i.id);
                  handleAddBomItems(selectedIds);
                } else {
                  // 비인정 - 직접 입력한 항목 추가
                  if (!manualBomItem.itemCode || !manualBomItem.itemName) {
                    alert("품목 코드와 품목명을 입력해주세요.");
                    return;
                  }
                  
                  const newItem: BOMItem = {
                    id: `bom-manual-${Date.now()}`,
                    type: "비인정",
                    itemType: selectedItemType,
                    itemCode: manualBomItem.itemCode,
                    itemName: manualBomItem.itemName,
                    specification: manualBomItem.specification,
                    quantity: manualBomItem.quantity,
                    unit: manualBomItem.unit,
                    width: manualBomItem.width,
                    height: manualBomItem.height,
                    length: manualBomItem.length,
                    thickness: manualBomItem.thickness,
                    note: manualBomItem.note
                  };
                  
                  setBomItems([...bomItems, newItem]);
                  setIsItemSelectOpen(false);
                  
                  // 폼 초기화
                  setManualBomItem({
                    itemCode: "",
                    itemName: "",
                    specification: "",
                    quantity: 1,
                    unit: "EA",
                    width: 0,
                    height: 0,
                    length: 0,
                    thickness: 0,
                    note: ""
                  });
                }
              }}
            >
              추가
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>제품 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              정말로 이 제품을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.
              {selectedProduct && (
                <div className="mt-4 p-3 bg-muted rounded-md">
                  <p className="font-medium">{selectedProduct.name}</p>
                  <p className="text-sm text-muted-foreground">코드: {selectedProduct.code}</p>
                </div>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction 
              className="bg-red-600 hover:bg-red-700"
              onClick={confirmDelete}
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
