import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "./ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Badge } from "./ui/badge";
import { 
  Layers, 
  Plus, 
  Search, 
  Edit, 
  Trash2,
  ArrowRight,
  Link2,
  Copy,
  ArrowLeft,
  GitBranch,
  CheckCircle2,
  Circle,
  History,
  ChevronDown,
  ChevronUp
} from "lucide-react";

// BOM 라인
interface BOMLine {
  id: string;
  childItemCode: string;
  childItemName: string;
  quantity: number;
  quantityFormula?: string;
  condition?: string;
  isVariableSize?: boolean;
  dimensions?: string[];
}

// 치수 매핑
interface DimensionMapping {
  id: string;
  childItemCode: string;
  parentDimension: string;
  childDimension: string;
  mappingFormula: string;
}

// BOM 헤더
interface BOM {
  id: string;
  parentItemCode: string;
  parentItemName: string;
  version: string;
  isActive: boolean; // 활성 버전 여부
  isVariableSize?: boolean;
  parentDimensions?: string[];
  lines: BOMLine[];
  dimensionMappings?: DimensionMapping[];
  createdAt: string;
  updatedAt: string;
}

interface BOMManagementEnhancedProps {
  onNavigateToBOMRegister?: () => void;
}

export function BOMManagementEnhanced({ onNavigateToBOMRegister }: BOMManagementEnhancedProps = {}) {
  const [currentView, setCurrentView] = useState<"list" | "form">("list");
  const [searchTerm, setSearchTerm] = useState("");
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false);
  const [selectedBOM, setSelectedBOM] = useState<BOM | null>(null);
  const [selectedItemForVersion, setSelectedItemForVersion] = useState<string | null>(null);
  const [currentTab, setCurrentTab] = useState("lines");
  const [groupByItem, setGroupByItem] = useState(true);
  const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set());

  // 폼 데이터
  const [formData, setFormData] = useState({
    parentItemCode: "",
    version: "1.0",
  });

  const [bomLines, setBomLines] = useState<BOMLine[]>([]);
  const [dimensionMappings, setDimensionMappings] = useState<DimensionMapping[]>([]);

  // 샘플 품목 데이터 (실제로는 ItemManagement에서 가져와야 함)
  const sampleItems = [
    {
      code: "PT-RAIL-001",
      name: "가이드레일",
      isVariableSize: false,
      dimensions: [],
    },
    {
      code: "PT-CURTAIN-001",
      name: "셔터 커튼",
      isVariableSize: false,
      dimensions: [],
    },
    {
      code: "PT-MOTOR-001",
      name: "셔터 모터",
      isVariableSize: false,
      dimensions: [],
    },
    {
      code: "PT-REMOTE-001",
      name: "리모콘",
      isVariableSize: false,
      dimensions: [],
    },
    {
      code: "FG-SHUTTER-SET-001",
      name: "셔터 세트",
      isVariableSize: false,
      dimensions: [],
    },
  ];

  // 샘플 BOM 데이터
  const [boms, setBOMs] = useState<BOM[]>([
    {
      id: "1",
      parentItemCode: "PT-RAIL-VAR",
      parentItemName: "가이드레일 (가변 길이)",
      version: "1.0",
      isActive: true,
      isVariableSize: true,
      parentDimensions: ["G"],
      lines: [
        {
          id: "l1",
          childItemCode: "RM-001",
          childItemName: "알루미늄 압출재",
          quantity: 0,
          quantityFormula: "G/1000*1.02",
          isVariableSize: false,
          dimensions: [],
        },
        {
          id: "l2",
          childItemCode: "RM-003",
          childItemName: "브래킷",
          quantity: 8,
          isVariableSize: false,
          dimensions: [],
        },
      ],
      dimensionMappings: [],
      createdAt: "2025-01-17",
      updatedAt: "2025-01-17",
    },
    {
      id: "2",
      parentItemCode: "FG-SHUTTER-SET-VAR",
      parentItemName: "셔터 세트 (가변 크기)",
      version: "1.0",
      isActive: true,
      isVariableSize: true,
      parentDimensions: ["W", "H"],
      lines: [
        {
          id: "l3",
          childItemCode: "PT-RAIL-VAR",
          childItemName: "가이드레일",
          quantity: 2,
          isVariableSize: true,
          dimensions: ["G"],
        },
        {
          id: "l4",
          childItemCode: "PT-CURTAIN-VAR",
          childItemName: "셔터 커튼",
          quantity: 1,
          isVariableSize: true,
          dimensions: ["W", "H"],
        },
        {
          id: "l5",
          childItemCode: "PT-MOTOR-001",
          childItemName: "셔터 모터",
          quantity: 1,
          condition: "MOTOR='Y'",
          isVariableSize: false,
          dimensions: [],
        },
      ],
      dimensionMappings: [
        {
          id: "m1",
          childItemCode: "PT-RAIL-VAR",
          parentDimension: "W",
          childDimension: "G",
          mappingFormula: "W",
        },
        {
          id: "m2",
          childItemCode: "PT-CURTAIN-VAR",
          parentDimension: "W",
          childDimension: "W",
          mappingFormula: "W",
        },
        {
          id: "m3",
          childItemCode: "PT-CURTAIN-VAR",
          parentDimension: "H",
          childDimension: "H",
          mappingFormula: "H",
        },
      ],
      createdAt: "2025-01-18",
      updatedAt: "2025-01-18",
    },
  ]);

  const filteredBOMs = boms.filter((bom) => {
    const matchesSearch =
      bom.parentItemCode.toLowerCase().includes(searchTerm.toLowerCase()) ||
      bom.parentItemName.toLowerCase().includes(searchTerm.toLowerCase());
    return matchesSearch;
  });

  // 품목별로 그룹화
  const groupedBOMs = filteredBOMs.reduce((acc, bom) => {
    if (!acc[bom.parentItemCode]) {
      acc[bom.parentItemCode] = [];
    }
    acc[bom.parentItemCode].push(bom);
    return acc;
  }, {} as Record<string, BOM[]>);

  // 각 그룹을 버전순으로 정렬
  Object.keys(groupedBOMs).forEach(itemCode => {
    groupedBOMs[itemCode].sort((a, b) => parseFloat(b.version) - parseFloat(a.version));
  });

  const handleAdd = () => {
    // BOMRegistration 페이지로 이동하는 경우
    if (onNavigateToBOMRegister) {
      onNavigateToBOMRegister();
      return;
    }
    
    // 기존 폼 화면 사용
    setFormData({
      parentItemCode: "",
      version: "1.0",
    });
    setBomLines([]);
    setDimensionMappings([]);
    setCurrentTab("lines");
    setSelectedBOM(null);
    setCurrentView("form");
  };

  const handleEdit = (bom: BOM) => {
    setSelectedBOM(bom);
    setFormData({
      parentItemCode: bom.parentItemCode,
      version: bom.version,
    });
    setBomLines(bom.lines);
    setDimensionMappings(bom.dimensionMappings);
    setCurrentTab("lines");
    setCurrentView("form");
  };

  const saveBOM = () => {
    const parentItem = sampleItems.find((i) => i.code === formData.parentItemCode);
    if (!parentItem) return;

    // 동일 품목의 다른 버전들을 비활성화
    const existingVersions = boms.filter(b => b.parentItemCode === formData.parentItemCode);
    const isFirstVersion = existingVersions.length === 0;

    const newBOM: BOM = {
      id: Date.now().toString(),
      parentItemCode: formData.parentItemCode,
      parentItemName: parentItem.name,
      version: formData.version,
      isActive: isFirstVersion, // 첫 버전은 자동 활성화
      isVariableSize: parentItem.isVariableSize,
      parentDimensions: parentItem.dimensions,
      lines: bomLines,
      dimensionMappings: dimensionMappings,
      createdAt: new Date().toISOString().split("T")[0],
      updatedAt: new Date().toISOString().split("T")[0],
    };

    setBOMs([...boms, newBOM]);
    setCurrentView("list");
  };

  const updateBOM = () => {
    if (!selectedBOM) return;

    const parentItem = sampleItems.find((i) => i.code === formData.parentItemCode);
    if (!parentItem) return;

    const updatedBOM: BOM = {
      ...selectedBOM,
      parentItemCode: formData.parentItemCode,
      parentItemName: parentItem.name,
      version: formData.version,
      isVariableSize: parentItem.isVariableSize,
      parentDimensions: parentItem.dimensions,
      lines: bomLines,
      dimensionMappings: dimensionMappings,
      updatedAt: new Date().toISOString().split("T")[0],
    };

    setBOMs(boms.map((bom) => (bom.id === selectedBOM.id ? updatedBOM : bom)));
    setCurrentView("list");
    setSelectedBOM(null);
  };

  const createNewVersion = (baseBOM: BOM) => {
    const existingVersions = boms
      .filter(b => b.parentItemCode === baseBOM.parentItemCode)
      .map(b => parseFloat(b.version));
    const maxVersion = Math.max(...existingVersions);
    const newVersion = (maxVersion + 0.1).toFixed(1);

    setFormData({
      parentItemCode: baseBOM.parentItemCode,
      version: newVersion,
    });
    setBomLines(JSON.parse(JSON.stringify(baseBOM.lines))); // 깊은 복사
    setDimensionMappings(JSON.parse(JSON.stringify(baseBOM.dimensionMappings)));
    setCurrentTab("lines");
    setSelectedBOM(null);
    setCurrentView("form");
  };

  const setActiveVersion = (bomId: string, itemCode: string) => {
    setBOMs(boms.map(bom => ({
      ...bom,
      isActive: bom.id === bomId && bom.parentItemCode === itemCode
    })));
  };

  const getItemVersions = (itemCode: string) => {
    return boms
      .filter(b => b.parentItemCode === itemCode)
      .sort((a, b) => parseFloat(b.version) - parseFloat(a.version));
  };

  const toggleItemExpanded = (itemCode: string) => {
    const newExpanded = new Set(expandedItems);
    if (newExpanded.has(itemCode)) {
      newExpanded.delete(itemCode);
    } else {
      newExpanded.add(itemCode);
    }
    setExpandedItems(newExpanded);
  };

  const addBOMLine = () => {
    const newLine: BOMLine = {
      id: Date.now().toString(),
      childItemCode: "",
      childItemName: "",
      quantity: 1,
      isVariableSize: false,
      dimensions: [],
    };
    setBomLines([...bomLines, newLine]);
  };

  const addDimensionMapping = () => {
    const newMapping: DimensionMapping = {
      id: Date.now().toString(),
      childItemCode: "",
      parentDimension: "",
      childDimension: "",
      mappingFormula: "",
    };
    setDimensionMappings([...dimensionMappings, newMapping]);
  };

  const renderBOMDialog = (isEdit: boolean) => {
    const parentItem = sampleItems.find((i) => i.code === formData.parentItemCode);

    return (
      <Dialog open={isEdit ? isEditDialogOpen : isAddDialogOpen} onOpenChange={isEdit ? setIsEditDialogOpen : setIsAddDialogOpen}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{isEdit ? "BOM 수정" : "BOM 등록"}</DialogTitle>
            <DialogDescription>
              {isEdit ? "BOM 정보를 수정합니다." : "새로운 BOM을 등록합니다. Phase 4-5의 프로세스를 따라 입력해주세요."}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 기본 정보 */}
            <Card>
              <CardHeader>
                <CardTitle>기본 정보</CardTitle>
              </CardHeader>
              <CardContent className="grid grid-cols-2 gap-4">
                <div>
                  <Label>상위 품목 *</Label>
                  <Select value={formData.parentItemCode} onValueChange={(value) => setFormData({ ...formData, parentItemCode: value })}>
                    <SelectTrigger>
                      <SelectValue placeholder="품목 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {sampleItems
                        .filter((i) => i.code !== "RM-001" && i.code !== "RM-003")
                        .map((item) => (
                          <SelectItem key={item.code} value={item.code}>
                            {item.code} - {item.name}
                          </SelectItem>
                        ))}
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label>버전</Label>
                  <Input value={formData.version} onChange={(e) => setFormData({ ...formData, version: e.target.value })} />
                </div>

                {parentItem && parentItem.isVariableSize && (
                  <div className="col-span-2">
                    <Label>상위 품목 치수</Label>
                    <div className="flex gap-2 mt-2">
                      {parentItem.dimensions?.map((dim) => (
                        <Badge key={dim} variant="secondary">
                          {dim}
                        </Badge>
                      ))}
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>

            <Tabs value={currentTab} onValueChange={setCurrentTab}>
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="lines">
                  <Copy className="w-4 h-4 mr-2" />
                  BOM 라인 (구성품)
                </TabsTrigger>
                <TabsTrigger value="mapping" disabled={!parentItem?.isVariableSize}>
                  <Link2 className="w-4 h-4 mr-2" />
                  치수 연결 ⭐
                </TabsTrigger>
              </TabsList>

              {/* BOM 라인 탭 */}
              <TabsContent value="lines" className="space-y-3 mt-4">
                <div className="flex justify-between items-center">
                  <h3 className="font-semibold">구성품 목록 (Phase 5 STEP 3)</h3>
                  <Button onClick={addBOMLine} size="sm">
                    <Plus className="w-4 h-4 mr-2" />
                    구성품 추가
                  </Button>
                </div>

                {bomLines.length === 0 ? (
                  <p className="text-sm text-muted-foreground text-center py-8 border rounded-lg">
                    하위 구성품을 추가하세요
                  </p>
                ) : (
                  <div className="space-y-3">
                    {bomLines.map((line, index) => {
                      const childItem = sampleItems.find((i) => i.code === line.childItemCode);

                      return (
                        <Card key={line.id}>
                          <CardContent className="pt-6">
                            <div className="grid grid-cols-6 gap-3">
                              <div className="col-span-2">
                                <Label className="text-xs">하위 품목 *</Label>
                                <Select
                                  value={line.childItemCode}
                                  onValueChange={(value) => {
                                    const item = sampleItems.find((i) => i.code === value);
                                    const updated = [...bomLines];
                                    updated[index].childItemCode = value;
                                    updated[index].childItemName = item?.name || "";
                                    updated[index].isVariableSize = item?.isVariableSize || false;
                                    updated[index].dimensions = item?.dimensions || [];
                                    setBomLines(updated);
                                  }}
                                >
                                  <SelectTrigger>
                                    <SelectValue placeholder="품목 선택" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {sampleItems.map((item) => (
                                      <SelectItem key={item.code} value={item.code}>
                                        {item.code} - {item.name}
                                      </SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                              </div>

                              <div>
                                <Label className="text-xs">수량 (고정)</Label>
                                <Input
                                  type="number"
                                  value={line.quantity || ""}
                                  onChange={(e) => {
                                    const updated = [...bomLines];
                                    updated[index].quantity = parseFloat(e.target.value) || 0;
                                    setBomLines(updated);
                                  }}
                                />
                              </div>

                              <div>
                                <Label className="text-xs">계산식 (변수)</Label>
                                <Input
                                  placeholder="L/1000"
                                  value={line.quantityFormula || ""}
                                  onChange={(e) => {
                                    const updated = [...bomLines];
                                    updated[index].quantityFormula = e.target.value;
                                    setBomLines(updated);
                                  }}
                                />
                              </div>

                              <div>
                                <Label className="text-xs">조건 (선택)</Label>
                                <Input
                                  placeholder="MOTOR='Y'"
                                  value={line.condition || ""}
                                  onChange={(e) => {
                                    const updated = [...bomLines];
                                    updated[index].condition = e.target.value;
                                    setBomLines(updated);
                                  }}
                                />
                              </div>

                              <div className="flex items-end">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => setBomLines(bomLines.filter((_, i) => i !== index))}
                                >
                                  <Trash2 className="w-4 h-4" />
                                </Button>
                              </div>
                            </div>

                            {childItem?.isVariableSize && (
                              <div className="mt-3 p-3 bg-blue-50 border border-blue-200 rounded">
                                <p className="text-xs font-semibold mb-1">하위 품목 치수:</p>
                                <div className="flex gap-2">
                                  {childItem.dimensions.map((dim) => (
                                    <Badge key={dim} variant="outline">
                                      {dim}
                                    </Badge>
                                  ))}
                                </div>
                                <p className="text-xs text-muted-foreground mt-1">
                                  ※ 치수 연결 탭에서 상위 치수와 매핑해주세요
                                </p>
                              </div>
                            )}
                          </CardContent>
                        </Card>
                      );
                    })}
                  </div>
                )}
              </TabsContent>

              {/* 치수 연결 탭 */}
              <TabsContent value="mapping" className="space-y-3 mt-4">
                <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                  <h3 className="font-semibold mb-2">⭐ 치수 자동 연결 (Phase 3 S11 - 핵심 기능!)</h3>
                  <p className="text-sm text-muted-foreground">
                    상위 품목의 치수를 하위 품목의 치수에 자동으로 전달합니다.
                    <br />
                    예: 세트.W → 레일.G, 세트.W → 커튼.W, 세트.H → 커튼.H
                  </p>
                </div>

                <div className="flex justify-between items-center">
                  <h3 className="font-semibold">치수 매핑 설정</h3>
                  <Button onClick={addDimensionMapping} size="sm">
                    <Plus className="w-4 h-4 mr-2" />
                    매핑 추가
                  </Button>
                </div>

                {dimensionMappings.length === 0 ? (
                  <p className="text-sm text-muted-foreground text-center py-8 border rounded-lg">
                    치수 매핑을 추가하세요. 가변 크기 하위 품목의 치수를 상위 품목 치수와 연결합니다.
                  </p>
                ) : (
                  <div className="space-y-3">
                    {dimensionMappings.map((mapping, index) => {
                      const childLine = bomLines.find((l) => l.childItemCode === mapping.childItemCode);

                      return (
                        <Card key={mapping.id}>
                          <CardContent className="pt-6">
                            <div className="grid grid-cols-5 gap-3">
                              <div>
                                <Label className="text-xs">하위 품목</Label>
                                <Select
                                  value={mapping.childItemCode}
                                  onValueChange={(value) => {
                                    const updated = [...dimensionMappings];
                                    updated[index].childItemCode = value;
                                    setDimensionMappings(updated);
                                  }}
                                >
                                  <SelectTrigger>
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {bomLines
                                      .filter((l) => l.isVariableSize)
                                      .map((line) => (
                                        <SelectItem key={line.childItemCode} value={line.childItemCode}>
                                          {line.childItemName}
                                        </SelectItem>
                                      ))}
                                  </SelectContent>
                                </Select>
                              </div>

                              <div>
                                <Label className="text-xs">하위 치수</Label>
                                <Select
                                  value={mapping.childDimension}
                                  onValueChange={(value) => {
                                    const updated = [...dimensionMappings];
                                    updated[index].childDimension = value;
                                    setDimensionMappings(updated);
                                  }}
                                >
                                  <SelectTrigger>
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {childLine?.dimensions.map((dim) => (
                                      <SelectItem key={dim} value={dim}>
                                        {dim}
                                      </SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                              </div>

                              <div className="flex items-center justify-center">
                                <ArrowRight className="w-5 h-5 text-muted-foreground" />
                              </div>

                              <div>
                                <Label className="text-xs">상위 치수</Label>
                                <Select
                                  value={mapping.parentDimension}
                                  onValueChange={(value) => {
                                    const updated = [...dimensionMappings];
                                    updated[index].parentDimension = value;
                                    updated[index].mappingFormula = value; // 기본 수식은 동일 치수명
                                    setDimensionMappings(updated);
                                  }}
                                >
                                  <SelectTrigger>
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {parentItem?.dimensions?.map((dim) => (
                                      <SelectItem key={dim} value={dim}>
                                        {dim}
                                      </SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                              </div>

                              <div className="flex items-end">
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => setDimensionMappings(dimensionMappings.filter((_, i) => i !== index))}
                                >
                                  <Trash2 className="w-4 h-4" />
                                </Button>
                              </div>
                            </div>

                            <div className="mt-3 p-3 bg-green-50 border border-green-200 rounded">
                              <p className="text-sm">
                                <span className="font-semibold">매핑 결과:</span> {childLine?.childItemName}.{mapping.childDimension} ← {parentItem?.name}.
                                {mapping.parentDimension}
                              </p>
                              <p className="text-xs text-muted-foreground mt-1">
                                견적 작성 시 "{parentItem?.name}"의 {mapping.parentDimension} 값이 "{childLine?.childItemName}"의 {mapping.childDimension}에 자동 전달됩니다.
                              </p>
                            </div>
                          </CardContent>
                        </Card>
                      );
                    })}
                  </div>
                )}

                {/* 매핑 미리보기 */}
                {dimensionMappings.length > 0 && (
                  <Card className="bg-blue-50 border-blue-200">
                    <CardHeader>
                      <CardTitle className="text-base">치수 매핑 미리보기</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>상위 품목</TableHead>
                            <TableHead>상위 치수</TableHead>
                            <TableHead className="text-center">→</TableHead>
                            <TableHead>하위 품목</TableHead>
                            <TableHead>하위 치수</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {dimensionMappings.map((mapping) => {
                            const childLine = bomLines.find((l) => l.childItemCode === mapping.childItemCode);
                            return (
                              <TableRow key={mapping.id}>
                                <TableCell>{parentItem?.name}</TableCell>
                                <TableCell>
                                  <Badge variant="secondary">{mapping.parentDimension}</Badge>
                                </TableCell>
                                <TableCell className="text-center">
                                  <ArrowRight className="w-4 h-4 mx-auto" />
                                </TableCell>
                                <TableCell>{childLine?.childItemName}</TableCell>
                                <TableCell>
                                  <Badge variant="secondary">{mapping.childDimension}</Badge>
                                </TableCell>
                              </TableRow>
                            );
                          })}
                        </TableBody>
                      </Table>
                    </CardContent>
                  </Card>
                )}
              </TabsContent>
            </Tabs>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => (isEdit ? setIsEditDialogOpen(false) : setIsAddDialogOpen(false))}>
              취소
            </Button>
            <Button onClick={isEdit ? updateBOM : saveBOM}>
              저장
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    );
  };

  // 폼 화면 렌더링
  if (currentView === "form") {
    const parentItem = sampleItems.find((i) => i.code === formData.parentItemCode);
    const isEdit = !!selectedBOM;

    return (
      <div className="p-6 space-y-6">
        {/* 헤더 */}
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <Button variant="ghost" size="sm" onClick={() => setCurrentView("list")}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              목록으로
            </Button>
            <div>
              <h1 className="text-2xl">{isEdit ? "BOM 수정" : "BOM 등록"}</h1>
              <p className="text-sm text-muted-foreground mt-1">
                {isEdit ? "BOM 정보를 수정합니다." : "새로운 BOM을 등록합니다. Phase 4-5의 프로세스를 따라 입력해주세요."}
              </p>
            </div>
          </div>
          <Button onClick={isEdit ? updateBOM : saveBOM} size="lg">
            저장
          </Button>
        </div>

        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle>기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="grid grid-cols-2 gap-4">
            <div>
              <Label>상위 품목 *</Label>
              <Select value={formData.parentItemCode} onValueChange={(value) => setFormData({ ...formData, parentItemCode: value })}>
                <SelectTrigger>
                  <SelectValue placeholder="품목 선택" />
                </SelectTrigger>
                <SelectContent>
                  {sampleItems
                    .filter((i) => i.code !== "RM-001" && i.code !== "RM-003")
                    .map((item) => (
                      <SelectItem key={item.code} value={item.code}>
                        {item.code} - {item.name}
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>버전</Label>
              <Input value={formData.version} onChange={(e) => setFormData({ ...formData, version: e.target.value })} />
            </div>

            {parentItem && parentItem.isVariableSize && (
              <div className="col-span-2">
                <Label>상위 품목 치수</Label>
                <div className="flex gap-2 mt-2">
                  {parentItem.dimensions?.map((dim) => (
                    <Badge key={dim} variant="secondary">
                      {dim}
                    </Badge>
                  ))}
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 탭 */}
        <Tabs value={currentTab} onValueChange={setCurrentTab}>
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="lines">
              <Copy className="w-4 h-4 mr-2" />
              BOM 라인 (구성품)
            </TabsTrigger>
            <TabsTrigger value="mapping" disabled={!parentItem?.isVariableSize}>
              <Link2 className="w-4 h-4 mr-2" />
              치수 연결 ⭐
            </TabsTrigger>
          </TabsList>

          {/* BOM 라인 탭 */}
          <TabsContent value="lines" className="space-y-3 mt-4">
            <div className="flex justify-between items-center">
              <h3 className="font-semibold">구성품 목록 (Phase 5 STEP 3)</h3>
              <Button onClick={addBOMLine} size="sm">
                <Plus className="w-4 h-4 mr-2" />
                구성품 추가
              </Button>
            </div>

            {bomLines.length === 0 ? (
              <Card>
                <CardContent className="text-center py-12">
                  <p className="text-muted-foreground">하위 구성품을 추가하세요</p>
                </CardContent>
              </Card>
            ) : (
              <div className="space-y-3">
                {bomLines.map((line, index) => {
                  const childItem = sampleItems.find((i) => i.code === line.childItemCode);

                  return (
                    <Card key={line.id}>
                      <CardContent className="pt-6">
                        <div className="grid grid-cols-6 gap-3">
                          <div className="col-span-2">
                            <Label className="text-xs">하위 품목 *</Label>
                            <Select
                              value={line.childItemCode}
                              onValueChange={(value) => {
                                const item = sampleItems.find((i) => i.code === value);
                                const updated = [...bomLines];
                                updated[index].childItemCode = value;
                                updated[index].childItemName = item?.name || "";
                                updated[index].isVariableSize = item?.isVariableSize || false;
                                updated[index].dimensions = item?.dimensions || [];
                                setBomLines(updated);
                              }}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="품목 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {sampleItems.map((item) => (
                                  <SelectItem key={item.code} value={item.code}>
                                    {item.code} - {item.name}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>

                          <div>
                            <Label className="text-xs">수량 (고정)</Label>
                            <Input
                              type="number"
                              value={line.quantity || ""}
                              onChange={(e) => {
                                const updated = [...bomLines];
                                updated[index].quantity = parseFloat(e.target.value) || 0;
                                setBomLines(updated);
                              }}
                            />
                          </div>

                          <div>
                            <Label className="text-xs">계산식 (변수)</Label>
                            <Input
                              placeholder="G/1000*1.02"
                              value={line.quantityFormula || ""}
                              onChange={(e) => {
                                const updated = [...bomLines];
                                updated[index].quantityFormula = e.target.value;
                                setBomLines(updated);
                              }}
                            />
                          </div>

                          <div>
                            <Label className="text-xs">조건 (선택)</Label>
                            <Input
                              placeholder="MOTOR='Y'"
                              value={line.condition || ""}
                              onChange={(e) => {
                                const updated = [...bomLines];
                                updated[index].condition = e.target.value;
                                setBomLines(updated);
                              }}
                            />
                          </div>

                          <div className="flex items-end">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => setBomLines(bomLines.filter((_, i) => i !== index))}
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>

                          {childItem && childItem.isVariableSize && childItem.dimensions && childItem.dimensions.length > 0 && (
                            <div className="col-span-6 pt-2 border-t">
                              <p className="text-xs text-muted-foreground">
                                이 품목은 가변 크기 제품입니다. 치수: {childItem.dimensions.join(", ")}
                              </p>
                            </div>
                          )}
                        </div>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>
            )}
          </TabsContent>

          {/* 치수 연결 탭 */}
          <TabsContent value="mapping" className="space-y-3 mt-4">
            <div className="flex justify-between items-center">
              <div>
                <h3 className="font-semibold">치수 자동 연결 (상위 → 하위 매핑) ⭐</h3>
                <p className="text-sm text-muted-foreground mt-1">
                  Phase 5 STEP 4: 상위 품목의 치수를 하위 품목의 치수에 자동으로 연결합니다
                </p>
              </div>
              <Button onClick={addDimensionMapping} size="sm" disabled={!parentItem?.isVariableSize}>
                <Plus className="w-4 h-4 mr-2" />
                매핑 추가
              </Button>
            </div>

            {dimensionMappings.length === 0 ? (
              <Card>
                <CardContent className="text-center py-12">
                  <p className="text-muted-foreground">치수 매핑을 추가하세요</p>
                  <p className="text-sm text-muted-foreground mt-2">
                    예: 세트의 W → 레일의 G (세트 폭이 레일 길이로 전달됨)
                  </p>
                </CardContent>
              </Card>
            ) : (
              <div className="space-y-3">
                {dimensionMappings.map((mapping, index) => {
                  const childLine = bomLines.find((l) => l.childItemCode === mapping.childItemCode);

                  return (
                    <Card key={mapping.id}>
                      <CardContent className="pt-6">
                        <div className="grid grid-cols-6 gap-3">
                          <div className="col-span-2">
                            <Label className="text-xs">하위 품목 *</Label>
                            <Select
                              value={mapping.childItemCode}
                              onValueChange={(value) => {
                                const updated = [...dimensionMappings];
                                updated[index].childItemCode = value;
                                setDimensionMappings(updated);
                              }}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="품목 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {bomLines
                                  .filter((l) => l.isVariableSize)
                                  .map((line) => (
                                    <SelectItem key={line.id} value={line.childItemCode}>
                                      {line.childItemCode} - {line.childItemName}
                                    </SelectItem>
                                  ))}
                              </SelectContent>
                            </Select>
                          </div>

                          <div>
                            <Label className="text-xs">상위 치수 *</Label>
                            <Select
                              value={mapping.parentDimension}
                              onValueChange={(value) => {
                                const updated = [...dimensionMappings];
                                updated[index].parentDimension = value;
                                updated[index].mappingFormula = value;
                                setDimensionMappings(updated);
                              }}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {parentItem?.dimensions?.map((dim) => (
                                  <SelectItem key={dim} value={dim}>
                                    {dim}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>

                          <div className="flex items-end justify-center">
                            <ArrowRight className="w-5 h-5 text-primary" />
                          </div>

                          <div>
                            <Label className="text-xs">하위 치수 *</Label>
                            <Select
                              value={mapping.childDimension}
                              onValueChange={(value) => {
                                const updated = [...dimensionMappings];
                                updated[index].childDimension = value;
                                setDimensionMappings(updated);
                              }}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {childLine?.dimensions?.map((dim) => (
                                  <SelectItem key={dim} value={dim}>
                                    {dim}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>

                          <div className="flex items-end">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => setDimensionMappings(dimensionMappings.filter((_, i) => i !== index))}
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>
                        </div>

                        <div className="mt-3 p-3 bg-green-50 border border-green-200 rounded">
                          <p className="text-sm">
                            <span className="font-semibold">매핑 결과:</span> {childLine?.childItemName}.{mapping.childDimension} ← {parentItem?.name}.
                            {mapping.parentDimension}
                          </p>
                          <p className="text-xs text-muted-foreground mt-1">
                            견적 작성 시 "{parentItem?.name}"의 {mapping.parentDimension} 값이 "{childLine?.childItemName}"의 {mapping.childDimension}에 자동 전달됩니다.
                          </p>
                        </div>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>
            )}

            {/* 매핑 미리보기 */}
            {dimensionMappings.length > 0 && (
              <Card className="bg-blue-50 border-blue-200">
                <CardHeader>
                  <CardTitle className="text-base">치수 매핑 미리보기</CardTitle>
                </CardHeader>
                <CardContent>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>상위 품목</TableHead>
                        <TableHead>상위 치수</TableHead>
                        <TableHead className="text-center">→</TableHead>
                        <TableHead>하위 품목</TableHead>
                        <TableHead>하위 치수</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {dimensionMappings.map((mapping) => {
                        const childLine = bomLines.find((l) => l.childItemCode === mapping.childItemCode);
                        return (
                          <TableRow key={mapping.id}>
                            <TableCell>{parentItem?.name}</TableCell>
                            <TableCell>
                              <Badge variant="secondary">{mapping.parentDimension}</Badge>
                            </TableCell>
                            <TableCell className="text-center">
                              <ArrowRight className="w-4 h-4 mx-auto" />
                            </TableCell>
                            <TableCell>{childLine?.childItemName}</TableCell>
                            <TableCell>
                              <Badge variant="secondary">{mapping.childDimension}</Badge>
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </CardContent>
              </Card>
            )}
          </TabsContent>
        </Tabs>
      </div>
    );
  }

  // 목록 화면 렌더링
  return (
    <div className="p-6 space-y-6">
      {/* 헤더 */}
      <div>
        <h1 className="text-2xl mb-2">BOM 관리 (버전 관리 강화)</h1>
        <p className="text-muted-foreground">
          Phase 4-5: BOM 구성품 등록, 치수 자동 연결 및 버전 관리 (상위 → 하위 치수 매핑)
        </p>
        <div className="flex gap-2 mt-2">
          <Badge variant="outline" className="text-xs">
            <GitBranch className="w-3 h-3 mr-1" />
            품목별 다중 버전 관리
          </Badge>
          <Badge variant="outline" className="text-xs">
            <CheckCircle2 className="w-3 h-3 mr-1" />
            활성 버전 지정
          </Badge>
          <Badge variant="outline" className="text-xs">
            <Copy className="w-3 h-3 mr-1" />
            버전 복사 생성
          </Badge>
        </div>
      </div>

      {/* 필터 및 검색 */}
      <div className="flex gap-4">
        <div className="flex-1">
          <Input
            placeholder="품목코드 또는 품목명 검색..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        <Button onClick={handleAdd}>
          <Plus className="w-4 h-4 mr-2" />
          BOM 등록
        </Button>
      </div>

      {/* 보기 모드 토글 */}
      <div className="flex items-center gap-2">
        <Button
          variant={groupByItem ? "default" : "outline"}
          size="sm"
          onClick={() => setGroupByItem(true)}
        >
          <GitBranch className="w-4 h-4 mr-2" />
          품목별 버전 관리
        </Button>
        <Button
          variant={!groupByItem ? "default" : "outline"}
          size="sm"
          onClick={() => setGroupByItem(false)}
        >
          <Layers className="w-4 h-4 mr-2" />
          전체 목록
        </Button>
      </div>

      {/* BOM 테이블 - 품목별 그룹화 */}
      {groupByItem ? (
        <div className="space-y-4">
          {Object.entries(groupedBOMs).map(([itemCode, versions]) => {
            const activeVersion = versions.find(v => v.isActive);
            const isExpanded = expandedItems.has(itemCode);
            
            return (
              <Card key={itemCode}>
                <CardHeader className="pb-3">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3 flex-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => toggleItemExpanded(itemCode)}
                        className="p-0 h-auto"
                      >
                        {isExpanded ? <ChevronUp className="w-5 h-5" /> : <ChevronDown className="w-5 h-5" />}
                      </Button>
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <code className="text-sm bg-muted px-2 py-1 rounded">{itemCode}</code>
                          <h3 className="font-semibold">{versions[0].parentItemName}</h3>
                          {versions[0].isVariableSize && (
                            <Badge variant="default">가변</Badge>
                          )}
                        </div>
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-sm text-muted-foreground">
                            총 {versions.length}개 버전
                          </span>
                          {activeVersion && (
                            <>
                              <span className="text-muted-foreground">•</span>
                              <div className="flex items-center gap-1">
                                <CheckCircle2 className="w-4 h-4 text-green-600" />
                                <span className="text-sm">활성 버전: v{activeVersion.version}</span>
                              </div>
                            </>
                          )}
                        </div>
                      </div>
                    </div>
                    <Button 
                      size="sm"
                      onClick={() => activeVersion && createNewVersion(activeVersion)}
                    >
                      <Plus className="w-4 h-4 mr-2" />
                      신규 버전 생성
                    </Button>
                  </div>
                </CardHeader>
                
                {isExpanded && (
                  <CardContent className="pt-0">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-12">상태</TableHead>
                          <TableHead>버전</TableHead>
                          <TableHead>구성품</TableHead>
                          <TableHead>치수 매핑</TableHead>
                          <TableHead>등록일</TableHead>
                          <TableHead>수정일</TableHead>
                          <TableHead className="text-right">관리</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {versions.map((bom) => (
                          <TableRow key={bom.id} className={bom.isActive ? "bg-green-50" : ""}>
                            <TableCell>
                              {bom.isActive ? (
                                <CheckCircle2 className="w-4 h-4 text-green-600" />
                              ) : (
                                <Circle className="w-4 h-4 text-gray-300" />
                              )}
                            </TableCell>
                            <TableCell>
                              <div className="flex items-center gap-2">
                                <Badge variant={bom.isActive ? "default" : "outline"}>
                                  v{bom.version}
                                </Badge>
                                {bom.isActive && (
                                  <Badge variant="secondary" className="text-xs">사용중</Badge>
                                )}
                              </div>
                            </TableCell>
                            <TableCell>{bom.lines.length}개</TableCell>
                            <TableCell>
                              {bom.dimensionMappings.length > 0 ? (
                                <Badge variant="secondary">{bom.dimensionMappings.length}개</Badge>
                              ) : (
                                <span className="text-muted-foreground">-</span>
                              )}
                            </TableCell>
                            <TableCell className="text-sm">{bom.createdAt}</TableCell>
                            <TableCell className="text-sm">{bom.updatedAt}</TableCell>
                            <TableCell className="text-right">
                              <div className="flex justify-end gap-1">
                                {!bom.isActive && (
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => setActiveVersion(bom.id, bom.parentItemCode)}
                                    title="활성화"
                                  >
                                    <CheckCircle2 className="w-4 h-4 text-green-600" />
                                  </Button>
                                )}
                                <Button 
                                  variant="ghost" 
                                  size="sm" 
                                  onClick={() => handleEdit(bom)}
                                  title="수정"
                                >
                                  <Edit className="w-4 h-4" />
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => createNewVersion(bom)}
                                  title="이 버전 기반으로 새 버전 생성"
                                >
                                  <Copy className="w-4 h-4" />
                                </Button>
                              </div>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </CardContent>
                )}
              </Card>
            );
          })}
          
          {Object.keys(groupedBOMs).length === 0 && (
            <Card>
              <CardContent className="text-center text-muted-foreground py-8">
                등록된 BOM이 없습니다
              </CardContent>
            </Card>
          )}
        </div>
      ) : (
        // 전체 목록 보기
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">상태</TableHead>
                  <TableHead>상위 품목코드</TableHead>
                  <TableHead>상위 품목명</TableHead>
                  <TableHead>버전</TableHead>
                  <TableHead>가변 크기</TableHead>
                  <TableHead>구성품 수</TableHead>
                  <TableHead>치수 매핑</TableHead>
                  <TableHead>등록일</TableHead>
                  <TableHead className="text-right">관리</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredBOMs.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center text-muted-foreground py-8">
                      등록된 BOM이 없습니다
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredBOMs.map((bom) => (
                    <TableRow key={bom.id} className={bom.isActive ? "bg-green-50" : ""}>
                      <TableCell>
                        {bom.isActive ? (
                          <CheckCircle2 className="w-4 h-4 text-green-600" />
                        ) : (
                          <Circle className="w-4 h-4 text-gray-300" />
                        )}
                      </TableCell>
                      <TableCell>
                        <code className="text-sm bg-muted px-2 py-1 rounded">{bom.parentItemCode}</code>
                      </TableCell>
                      <TableCell>{bom.parentItemName}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Badge variant={bom.isActive ? "default" : "outline"}>v{bom.version}</Badge>
                          {bom.isActive && (
                            <Badge variant="secondary" className="text-xs">사용중</Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        {bom.isVariableSize ? (
                          <Badge variant="default">가변</Badge>
                        ) : (
                          <Badge variant="outline">고정</Badge>
                        )}
                      </TableCell>
                      <TableCell>{bom.lines.length}개</TableCell>
                      <TableCell>
                        {bom.dimensionMappings.length > 0 ? (
                          <Badge variant="secondary">{bom.dimensionMappings.length}개 연결</Badge>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell>{bom.createdAt}</TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-1">
                          {!bom.isActive && (
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => setActiveVersion(bom.id, bom.parentItemCode)}
                              title="활성화"
                            >
                              <CheckCircle2 className="w-4 h-4 text-green-600" />
                            </Button>
                          )}
                          <Button variant="ghost" size="sm" onClick={() => handleEdit(bom)}>
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => createNewVersion(bom)}
                            title="새 버전 생성"
                          >
                            <Copy className="w-4 h-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* 등록/수정 다이얼로그 */}
      {renderBOMDialog(false)}
      {renderBOMDialog(true)}
    </div>
  );
}
