import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { ChevronDown, ChevronRight, Bug, Trash2, Plus, Check, X, Search } from "lucide-react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { useData } from "./contexts/DataContext";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "./ui/command";
import { cn } from "./ui/utils";
import { ConfirmDialog } from "./molecules/StandardDialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Checkbox } from "./ui/checkbox";
import { CommonBottomSheet } from "./templates/CommonBottomSheet";

// 품목별 디버깅 정보
export interface ItemDebugInfo {
  step1_formula: string; // 1단계: 사용된 수식
  step2_variables: Record<string, number>; // 2단계: 대입된 변수 값
  step3_quantityCalc: string; // 3단계: 수량 계산 과정
  step4_quantity: number; // 4단계: 계산된 수량
  step5_priceSource: string; // 5단계: 단가 출처 (품목마스터 / 단가관리)
  step6_basePrice: number; // 6단계: 기본 단가
  step7_categoryMultiplier?: string; // 7단계: 분류별 변수 곱셈 (옵션)
  step8_finalPrice: number; // 8단계: 최종 단가
  step9_totalCalc: string; // 9단계: 금액 계산 과정
  step10_total: number; // 10단계: 최종 금액
}

interface BomItem {
  itemCode: string;
  itemName: string;
  itemCategory: string;
  quantityFormula: string;
  calculatedQuantity: number;
  unit: string;
  unitPrice: number;
  totalPrice: number;
  children?: BomItem[];
  debugInfo?: ItemDebugInfo; // 디버깅 정보 추가
}

interface BomCalculationResultsProps {
  // 입력 정보
  productName: string;
  productCategory: string;
  w0: number; // 오픈사이즈 폭
  h0: number; // 오픈사이즈 높이
  guideRailInstallType: string;
  motorPower: string;
  controller: string;
  quantity: number;
  
  // 계산된 기본 정보
  w1: number; // 제작폭
  h1: number; // 제작높이
  area: number; // 면적 (m²)
  weight: number; // 중량 (kg)
  
  // BOM 기반 자재 산출 결과
  bomItems: BomItem[];
  
  // 디버그 표시 여부
  showDebug?: boolean;
  
  // 콜백 함수들
  onUpdateItem?: (itemCode: string, field: 'calculatedQuantity' | 'unitPrice', value: number) => void;
  onDeleteItem?: (itemCode: string) => void;
  onAddItem?: (newItem: BomItem) => void;
}

export function BomCalculationResults({
  productName,
  productCategory,
  w0,
  h0,
  guideRailInstallType,
  motorPower,
  controller,
  quantity,
  w1,
  h1,
  area,
  weight,
  bomItems,
  showDebug = false, // 기본값 false
  onUpdateItem,
  onDeleteItem,
  onAddItem,
}: BomCalculationResultsProps) {
  const { itemMasters, pricing } = useData();
  
  // localStorage에서 초기값 로드
  const [expandedItems, setExpandedItems] = useState<Set<string>>(() => {
    try {
      const saved = localStorage.getItem('bomCalculation_expandedItems');
      return saved ? new Set(JSON.parse(saved)) : new Set();
    } catch {
      return new Set();
    }
  });
  
  const [discountRate, setDiscountRate] = useState<number>(() => {
    try {
      const saved = localStorage.getItem('bomCalculation_discountRate');
      return saved ? Number(saved) : 0;
    } catch {
      return 0;
    }
  });
  
  // 디버그 정보 표시 여부 상태 추가
  const [showDebugInfo, setShowDebugInfo] = useState<boolean>(() => {
    try {
      const saved = localStorage.getItem('bomCalculation_showDebugInfo');
      return saved ? JSON.parse(saved) : false;
    } catch {
      return false;
    }
  });
  
  // expandedItems를 localStorage에 저장
  useEffect(() => {
    try {
      localStorage.setItem('bomCalculation_expandedItems', JSON.stringify(Array.from(expandedItems)));
    } catch (error) {
      console.error('Failed to save expandedItems to localStorage:', error);
    }
  }, [expandedItems]);
  
  // discountRate를 localStorage에 저장
  useEffect(() => {
    try {
      localStorage.setItem('bomCalculation_discountRate', String(discountRate));
    } catch (error) {
      console.error('Failed to save discountRate to localStorage:', error);
    }
  }, [discountRate]);
  
  // showDebugInfo를 localStorage에 저장
  useEffect(() => {
    try {
      localStorage.setItem('bomCalculation_showDebugInfo', JSON.stringify(showDebugInfo));
    } catch (error) {
      console.error('Failed to save showDebugInfo to localStorage:', error);
    }
  }, [showDebugInfo]);
  
  // 품목코드로 품목마스터 찾기
  const getItemMaster = (itemCode: string) => {
    return itemMasters.find(item => item.itemCode === itemCode);
  };
  
  // 품목유형 표시명 변환
  const getItemTypeLabel = (itemType?: string) => {
    const typeMap: Record<string, string> = {
      'FG': '완제품',
      'PT': '부품',
      'SM': '부자재',
      'RM': '원자재',
      'CS': '소모품'
    };
    return itemType ? typeMap[itemType] || itemType : '-';
  };
  
  // 아코디언 토글
  const toggleExpand = (itemCode: string) => {
    const newExpanded = new Set(expandedItems);
    if (newExpanded.has(itemCode)) {
      newExpanded.delete(itemCode);
    } else {
      newExpanded.add(itemCode);
    }
    setExpandedItems(newExpanded);
  };
  
  // 품목 추가 상태
  const [showAddItem, setShowAddItem] = useState(false);
  const [itemTypeFilter, setItemTypeFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedItems, setSelectedItems] = useState<Map<string, number>>(new Map()); // itemCode -> quantity
  
  // 삭제 확인 다이얼로그 상태
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [itemToDelete, setItemToDelete] = useState<{ code: string; name: string } | null>(null);
  
  // 삭제 확인 핸들러
  const handleDeleteClick = (itemCode: string, itemName: string) => {
    setItemToDelete({ code: itemCode, name: itemName });
    setDeleteConfirmOpen(true);
  };
  
  // 삭제 실행
  const handleDeleteConfirm = () => {
    if (itemToDelete && onDeleteItem) {
      onDeleteItem(itemToDelete.code);
      setItemToDelete(null);
    }
  };
  
  // 품목 추가 함수
  const handleAddNewItem = () => {
    if (!selectedItems.size || !onAddItem) return;
    
    selectedItems.forEach((quantity, itemCode) => {
      const selectedItem = itemMasters.find(item => item.itemCode === itemCode);
      if (!selectedItem) {
        alert('선택한 품목을 찾을 수 없습니다.');
        return;
      }
      
      // 단가 조회
      let unitPrice = 0;
      const itemPricing = pricing.find(p => p.itemCode === itemCode);
      if (itemPricing && itemPricing.salesPrice) {
        unitPrice = itemPricing.salesPrice;
      } else if (selectedItem.salesPrice) {
        unitPrice = selectedItem.salesPrice;
      }
      
      const newItem: BomItem = {
        itemCode: selectedItem.itemCode,
        itemName: selectedItem.itemName,
        itemCategory: selectedItem.itemCategory || selectedItem.category1 || '기타',
        quantityFormula: '',
        calculatedQuantity: quantity,
        unit: selectedItem.unit,
        unitPrice: unitPrice,
        totalPrice: quantity * unitPrice,
        children: []
      };
      
      onAddItem(newItem);
    });
    
    // 초기화
    setSelectedItems(new Map());
    setShowAddItem(false);
    setItemTypeFilter('all');
    setSearchQuery('');
  };
  
  // 필터링된 품목 목록
  const filteredItems = itemMasters.filter(item => {
    // 품목유형 필터
    if (itemTypeFilter !== 'all' && item.itemType !== itemTypeFilter) {
      return false;
    }
    
    // 검색 필터
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return (
        item.itemCode.toLowerCase().includes(query) ||
        item.itemName.toLowerCase().includes(query) ||
        item.spec?.toLowerCase().includes(query)
      );
    }
    
    return true;
  });
  
  // 품목 수량 변경
  const handleItemQuantityChange = (itemCode: string, quantity: number) => {
    const newSelected = new Map(selectedItems);
    if (quantity > 0) {
      newSelected.set(itemCode, quantity);
    } else {
      newSelected.delete(itemCode);
    }
    setSelectedItems(newSelected);
  };
  
  // 재귀적으로 BOM 아이템 렌더링 - 테이블 행 (데스크톱용)
  const renderBomItemRow = (item: BomItem, depth: number = 0, index: number = 0) => {
    const hasChildren = item.children && item.children.length > 0;
    const isExpanded = expandedItems.has(item.itemCode);
    const indentClass = depth > 0 ? `pl-${depth * 8}` : "";
    
    // 품목마스터에서 정보 가져오기
    const itemMaster = getItemMaster(item.itemCode);
    const itemType = getItemTypeLabel(itemMaster?.itemType);
    const baseQuantity = itemMaster?.bom?.[0]?.quantity || 1; // BOM의 기준수량, 없으면 1
    const specification = itemMaster?.spec || '-'; // 규격 정보
    
    return (
      <React.Fragment key={item.itemCode}>
        <TableRow className="hover:bg-gray-50">
          {/* 순번 */}
          <TableCell className="text-center w-[60px]">
            {depth === 0 ? index + 1 : ''}
          </TableCell>
          
          {/* 품목코드 */}
          <TableCell className={`w-[120px] ${indentClass}`}>
            <div className="flex items-center gap-2">
              {hasChildren && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-6 w-6 p-0"
                  onClick={() => toggleExpand(item.itemCode)}
                >
                  {isExpanded ? (
                    <ChevronDown className="h-4 w-4" />
                  ) : (
                    <ChevronRight className="h-4 w-4" />
                  )}
                </Button>
              )}
              {!hasChildren && <div className="w-6" />}
              <span>{item.itemCode}</span>
            </div>
          </TableCell>
          
          {/* 품목명 */}
          <TableCell className="w-[150px]">{item.itemName}</TableCell>
          
          {/* 품목유형 */}
          <TableCell className="text-center w-[100px]">
            <Badge variant="outline">{itemType}</Badge>
          </TableCell>
          
          {/* 규격 */}
          <TableCell className="text-center w-[120px]">{specification}</TableCell>
          
          {/* 기준수량 */}
          <TableCell className="text-center w-[80px] font-[Pretendard]">
            {baseQuantity.toFixed(2)}
          </TableCell>
          
          {/* 산출수량 */}
          <TableCell className="text-center w-[80px] font-[Pretendard]">{onUpdateItem ? (
              <Input
                type="number"
                value={item.calculatedQuantity}
                onChange={(e) => {
                  const newValue = Number(e.target.value);
                  if (newValue >= 0) {
                    onUpdateItem(item.itemCode, 'calculatedQuantity', newValue);
                  }
                }}
                className="w-20 h-7 text-right"
                step="0.01"
              />
            ) : (
              item.calculatedQuantity.toFixed(2)
            )}
          </TableCell>
          
          {/* 단위 */}
          <TableCell className="text-center w-[60px]">{item.unit}</TableCell>
          
          {/* 단가 */}
          <TableCell className="text-right w-[100px] font-[Pretendard]">
            {onUpdateItem ? (
              <Input
                type="number"
                value={item.unitPrice}
                onChange={(e) => {
                  const newValue = Number(e.target.value);
                  if (newValue >= 0) {
                    onUpdateItem(item.itemCode, 'unitPrice', newValue);
                  }
                }}
                className="w-24 h-7 text-right"
                step="1"
              />
            ) : (
              `${item.unitPrice.toLocaleString()}원`
            )}
          </TableCell>
          
          {/* 금액 */}
          <TableCell className="text-right w-[100px] font-[Pretendard]">
            {item.totalPrice.toLocaleString()}원
          </TableCell>
          
          {/* 삭제 */}
          {onDeleteItem && (
            <TableCell className="text-center w-[60px]">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleDeleteClick(item.itemCode, item.itemName)}
                className="h-7 w-7 p-0 text-red-600 hover:text-red-700 hover:bg-red-50"
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </TableCell>
          )}
        </TableRow>
        
        {/* 하위 품목 표시 (펼쳐진 경우) */}
        {hasChildren && isExpanded && item.children!.map((child, childIndex) => renderBomItemRow(child, depth + 1, childIndex))}
      </React.Fragment>
    );
  };
  
  // 재귀적으로 BOM 아이템 렌더링 - 카드 (모바일용)
  const renderBomItemCard = (item: BomItem, depth: number = 0, index: number = 0) => {
    const hasChildren = item.children && item.children.length > 0;
    const isExpanded = expandedItems.has(item.itemCode);
    
    // 품목마스터에서 정보 가져오기
    const itemMaster = getItemMaster(item.itemCode);
    const itemType = getItemTypeLabel(itemMaster?.itemType);
    const baseQuantity = itemMaster?.bom?.[0]?.quantity || 1;
    const specification = itemMaster?.spec || '-';
    
    return (
      <React.Fragment key={item.itemCode}>
        <div className={cn(
          "border rounded-lg p-4 space-y-3",
          depth > 0 && "ml-4 border-l-4 border-l-blue-200"
        )}>
          {/* 헤더: 순번, 품목명, 펼치기 버튼 */}
          <div className="flex items-start justify-between gap-3">
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1">
                {depth === 0 && (
                  <Badge variant="secondary" className="text-xs shrink-0">
                    {index + 1}
                  </Badge>
                )}
                <span className="font-medium truncate">{item.itemName}</span>
              </div>
              <div className="flex items-center gap-2 flex-wrap">
                <span className="font-mono text-xs text-muted-foreground">{item.itemCode}</span>
                <Badge variant="outline" className="text-xs">{itemType}</Badge>
              </div>
            </div>
            <div className="flex items-center gap-1 shrink-0">
              {hasChildren && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-8 w-8 p-0"
                  onClick={() => toggleExpand(item.itemCode)}
                >
                  {isExpanded ? (
                    <ChevronDown className="h-4 w-4" />
                  ) : (
                    <ChevronRight className="h-4 w-4" />
                  )}
                </Button>
              )}
              {onDeleteItem && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleDeleteClick(item.itemCode, item.itemName)}
                  className="h-8 w-8 p-0 text-red-600 hover:text-red-700 hover:bg-red-50"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              )}
            </div>
          </div>
          
          {/* 규격 & 기준수량 */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
            <div className="space-y-1">
              <Label className="text-xs text-muted-foreground">규격</Label>
              <div>{specification}</div>
            </div>
            <div className="space-y-1">
              <Label className="text-xs text-muted-foreground">기준수량</Label>
              <div className="font-[Pretendard]">{baseQuantity.toFixed(2)} {item.unit}</div>
            </div>
          </div>
          
          {/* 산출수량 & 단가 */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
            <div className="space-y-1">
              <Label className="text-xs text-muted-foreground">산출수량</Label>
              {onUpdateItem ? (
                <Input
                  type="number"
                  value={item.calculatedQuantity}
                  onChange={(e) => {
                    const newValue = Number(e.target.value);
                    if (newValue >= 0) {
                      onUpdateItem(item.itemCode, 'calculatedQuantity', newValue);
                    }
                  }}
                  className="h-8 text-right font-[Pretendard]"
                  step="0.01"
                />
              ) : (
                <div className="font-[Pretendard]">{item.calculatedQuantity.toFixed(2)} {item.unit}</div>
              )}
            </div>
            <div className="space-y-1">
              <Label className="text-xs text-muted-foreground">단가</Label>
              {onUpdateItem ? (
                <Input
                  type="number"
                  value={item.unitPrice}
                  onChange={(e) => {
                    const newValue = Number(e.target.value);
                    if (newValue >= 0) {
                      onUpdateItem(item.itemCode, 'unitPrice', newValue);
                    }
                  }}
                  className="h-8 text-right font-[Pretendard]"
                  step="1"
                />
              ) : (
                <div className="font-[Pretendard]">{item.unitPrice.toLocaleString()}원</div>
              )}
            </div>
          </div>
          
          {/* 금액 */}
          <div className="grid grid-cols-1 gap-3 text-sm">
            <div className="space-y-1">
              <Label className="text-xs text-muted-foreground">금액</Label>
              <div className="font-[Pretendard] text-blue-600 font-semibold">
                {item.totalPrice.toLocaleString()}원
              </div>
            </div>
          </div>
        </div>
        
        {/* 하위 품목 표시 (펼쳐진 경우) */}
        {hasChildren && isExpanded && (
          <div className="space-y-2">
            {item.children!.map((child, childIndex) => renderBomItemCard(child, depth + 1, childIndex))}
          </div>
        )}
      </React.Fragment>
    );
  };
  
  // 총 금액 계산 (재귀적으로 모든 하위 품목 포함)
  const calculateTotalAmount = (items: BomItem[]): number => {
    return items.reduce((sum, item) => {
      let total = item.totalPrice;
      if (item.children && item.children.length > 0) {
        total += calculateTotalAmount(item.children);
      }
      return sum + total;
    }, 0);
  };
  
  const subtotal = calculateTotalAmount(bomItems);
  const discountAmount = subtotal * (discountRate / 100);
  const supplyPrice = subtotal - discountAmount;
  const finalAmount = supplyPrice; // 부가세 제거, 공급가가 최종금액
  
  // 🔍 디버깅 로그
  console.group('📊 BOM 계산 결과 디버깅');
  console.log('=== 입력 데이터 ===');
  console.log('제품명:', productName);
  console.log('제품 카테고리:', productCategory);
  console.log('오픈사이즈 W0:', w0, 'H0:', h0);
  console.log('가이드레일 설치:', guideRailInstallType);
  console.log('모터 전원:', motorPower);
  console.log('연동제어기:', controller);
  console.log('수량:', quantity);
  
  console.log('\n=== 계산된 기본 정보 ===');
  console.log('제작폭 (W1):', w1, `(공식: ${productCategory === "스크린" ? "W0 + 140" : "W0 + 110"} = ${w0} + ${productCategory === "스크린" ? 140 : 110})`);
  console.log('제작높이 (H1):', h1, `(공식: H0 + 350 = ${h0} + 350)`);
  console.log('면적 (M):', area.toFixed(2), 'm² (공식: W1 × H1 / 1,000,000)');
  console.log('중량 (K):', weight.toFixed(2), 'kg');
  
  console.log('\n=== BOM 자재 산출 ===');
  console.log('BOM 품목 개수:', bomItems.length);
  bomItems.forEach((item, index) => {
    console.log(`\n품목 ${index + 1}:`, {
      품목코드: item.itemCode,
      품목명: item.itemName,
      품목그룹: item.itemCategory,
      수량공식: item.quantityFormula || '없음',
      산출수량: item.calculatedQuantity,
      단위: item.unit,
      단가: item.unitPrice.toLocaleString() + '원',
      금액: item.totalPrice.toLocaleString() + '원',
      하위품목: item.children ? `${item.children.length}개` : '없음'
    });
    
    if (item.children && item.children.length > 0) {
      item.children.forEach((child, childIndex) => {
        console.log(`  └ 하위품목 ${childIndex + 1}:`, {
          품목코드: child.itemCode,
          품목명: child.itemName,
          산출수량: child.calculatedQuantity,
          금액: child.totalPrice.toLocaleString() + '원'
        });
      });
    }
  });
  
  console.log('\n=== 금액 계산 ===');
  console.log('합계:', subtotal.toLocaleString() + '원', '(모든 BOM 품목의 금액 합계)');
  console.log('할인율:', discountRate + '%');
  console.log('할인금액:', discountAmount.toLocaleString() + '원', `(공식: 합계 × ${discountRate}% = ${subtotal.toLocaleString()} × ${discountRate / 100})`);
  console.log('공급가:', supplyPrice.toLocaleString() + '원', `(공식: 합계 - 할인 = ${subtotal.toLocaleString()} - ${discountAmount.toLocaleString()})`);
  console.log('최종금액:', finalAmount.toLocaleString() + '원', `(공식: 공급가 = ${supplyPrice.toLocaleString()})`);
  console.groupEnd();
  
  return (
    <div className="space-y-6">
      {/* 입력 정보 요약 */}
      <Card>
        <CardHeader>
          <CardTitle>입력 정보 요약</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <Label className="text-muted-foreground text-sm">제품명</Label>
              <p>{productName}</p>
            </div>
            <div>
              <Label className="text-muted-foreground text-sm">제품 카테고리</Label>
              <p>{productCategory}</p>
            </div>
            <div>
              <Label className="text-muted-foreground text-sm">오픈사이즈</Label>
              <p>W{w0} × H{h0}</p>
            </div>
            <div>
              <Label className="text-muted-foreground text-sm">가이드레일 설치</Label>
              <p>{guideRailInstallType}</p>
            </div>
            <div>
              <Label className="text-muted-foreground text-sm">모터 전원</Label>
              <p>{motorPower}</p>
            </div>
            <div>
              <Label className="text-muted-foreground text-sm">연동제어기</Label>
              <p>{controller}</p>
            </div>
            <div>
              <Label className="text-muted-foreground text-sm">수량</Label>
              <p>{quantity}개</p>
            </div>
          </div>
        </CardContent>
      </Card>
      
      {/* 기본 산출 공식 */}
      <Card>
        <CardHeader>
          <CardTitle>기본 산출 공식</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <div className="space-y-1">
              <Label className="text-muted-foreground text-sm">제작폭 (W1)</Label>
              <p className="font-[Pretendard]">{w1.toFixed(0)}</p>
              <p className="text-xs text-muted-foreground">
                {productCategory === "스크린" ? "W0 + 140" : "W0 + 110"}
              </p>
            </div>
            <div className="space-y-1">
              <Label className="text-muted-foreground text-sm">제작높이 (H1)</Label>
              <p className="font-[Pretendard]">{h1.toFixed(0)}</p>
              <p className="text-xs text-muted-foreground">H0 + 350</p>
            </div>
            <div className="space-y-1">
              <Label className="text-muted-foreground text-sm">면적 (M)</Label>
              <p className="font-[Pretendard]">{area.toFixed(2)}</p>
              <p className="text-xs text-muted-foreground">m²</p>
            </div>
            <div className="space-y-1">
              <Label className="text-muted-foreground text-sm">중량 (K)</Label>
              <p className="font-[Pretendard]">{weight.toFixed(2)}</p>
              <p className="text-xs text-muted-foreground">kg</p>
            </div>
          </div>
        </CardContent>
      </Card>
      
      {/* BOM 자재 산출 결과 */}
      <Card>
        <CardHeader className="pb-[0px] pt-[24px] pr-[24px] pl-[24px]">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 pb-4 border-b border-gray-200">
            <div className="flex-1">
              <CardTitle className="mb-2">부품구성표(BOM) 목 목록</CardTitle>
              <p className="text-sm text-muted-foreground">
                품목별 소재명이 내역으로 BOM 구성을 조회할 수 있습니다. 수량과 단가를 수정하여 자동으로 견적이 재산출됩니다.
              </p>
            </div>
            {onAddItem && (
              <>
                <Button className="shrink-0" onClick={() => setShowAddItem(true)}>
                  <Plus className="h-4 w-4 mr-2" />
                  품목 추가
                </Button>
                
                <CommonBottomSheet
                  isOpen={showAddItem}
                  onClose={() => setShowAddItem(false)}
                  title="품목 추가"
                  description="품목마스터에서 선택하여 BOM 목록에 추가합니다"
                  maxWidth="6xl"
                  maxHeight="90vh"
                  showFooter={true}
                  saveButtonText={`일괄 추가 (${selectedItems.size})`}
                  cancelButtonText="취소"
                  saveDisabled={selectedItems.size === 0}
                  onSave={handleAddNewItem}
                  onCancel={() => {
                    setShowAddItem(false);
                    setSelectedItems(new Map());
                    setItemTypeFilter('all');
                    setSearchQuery('');
                  }}
                  contentClassName="space-y-4"
                >
                  <div className="space-y-4">
                    {/* 필터 및 검색 */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label>품목 분류</Label>
                        <Select value={itemTypeFilter} onValueChange={setItemTypeFilter}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="all">전체</SelectItem>
                            <SelectItem value="FG">완제품</SelectItem>
                            <SelectItem value="PT">부품</SelectItem>
                            <SelectItem value="SM">부자재</SelectItem>
                            <SelectItem value="RM">원자재</SelectItem>
                            <SelectItem value="CS">소모품</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      
                      <div className="space-y-2">
                        <Label>검색</Label>
                        <div className="relative">
                          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                          <Input
                            placeholder="품목코드 또는 품목명으로 검색"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            className="pl-9"
                          />
                        </div>
                      </div>
                    </div>
                    
                    {/* 품목 목록 - 데스크톱: 테이블 / 모바일: 카드 */}
                    <div className="border rounded-lg overflow-hidden">
                      <div className="max-h-[400px] overflow-y-auto">
                        {/* 카드 뷰 (모든 해상도) */}
                        <div className="space-y-2 p-2">{filteredItems.length > 0 ? (
                          filteredItems.map((item) => {
                            const itemPricing = pricing.find(p => p.itemCode === item.itemCode);
                            const unitPrice = itemPricing?.salesPrice || item.salesPrice || 0;
                            const isSelected = selectedItems.has(item.itemCode);
                            const quantity = selectedItems.get(item.itemCode) || 1;
                            
                            return (
                              <div
                                key={item.itemCode}
                                className={cn(
                                  "border rounded-lg p-3 space-y-2",
                                  isSelected ? 'bg-blue-50 border-blue-300' : 'bg-white'
                                )}
                              >
                                {/* 체크박스 & 품목명 */}
                                <div className="flex items-start gap-3">
                                  <Checkbox
                                    checked={isSelected}
                                    onCheckedChange={(checked) => {
                                      if (checked) {
                                        handleItemQuantityChange(item.itemCode, 1);
                                      } else {
                                        handleItemQuantityChange(item.itemCode, 0);
                                      }
                                    }}
                                    className="mt-0.5"
                                  />
                                  <div className="flex-1 min-w-0">
                                    <div className="font-medium truncate">{item.itemName}</div>
                                    <div className="flex items-center gap-2 mt-1">
                                      <span className="font-mono text-xs text-muted-foreground">{item.itemCode}</span>
                                      <Badge variant="outline" className="text-xs">{getItemTypeLabel(item.itemType)}</Badge>
                                    </div>
                                  </div>
                                </div>
                                
                                {/* 단가 & 단위 */}
                                <div className="flex items-center justify-between text-sm">
                                  <span className="text-muted-foreground">단가</span>
                                  <span className="font-[Pretendard]">
                                    {unitPrice > 0 ? `${unitPrice.toLocaleString()}원` : '-'} / {item.unit}
                                  </span>
                                </div>
                                
                                {/* 수량 입력 */}
                                {isSelected && (
                                  <div className="flex items-center gap-2">
                                    <Label className="text-sm text-muted-foreground w-12">수량</Label>
                                    <Input
                                      type="number"
                                      value={quantity}
                                      onChange={(e) => handleItemQuantityChange(item.itemCode, Number(e.target.value))}
                                      className="flex-1 h-9 text-center font-[Pretendard]"
                                      step="0.01"
                                      min="0"
                                    />
                                    <span className="text-sm text-muted-foreground w-12">{item.unit}</span>
                                  </div>
                                )}
                              </div>
                            );
                          })
                        ) : (
                          <div className="text-center text-muted-foreground py-8">
                            검색 결과가 없습니다
                          </div>
                        )}
                        </div>
                      </div>
                    </div>
                    
                    {/* 선택된 품목 요약 */}
                    {selectedItems.size > 0 && (
                      <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 md:p-4">
                        <div className="space-y-3">
                          {/* 첫 번째 줄: 선택된 품목 개수 */}
                          <div className="flex-shrink-0">
                            <p className="text-sm whitespace-normal break-words">
                              <span className="font-semibold text-blue-700">{selectedItems.size}개 품목</span>이 선택되었습니다
                            </p>
                          </div>
                          
                          {/* 두 번째 줄: 선택된 품목 Badge 목록 */}
                          <div className="flex flex-wrap gap-1.5 min-h-[24px]">
                            {Array.from(selectedItems.entries()).slice(0, 3).map(([code, qty]) => {
                              const item = itemMasters.find(i => i.itemCode === code);
                              return (
                                <Badge key={code} variant="secondary" className="text-xs flex-shrink-0">
                                  {item?.itemName} × {qty}
                                </Badge>
                              );
                            })}
                            {selectedItems.size > 3 && (
                              <Badge variant="secondary" className="text-xs flex-shrink-0">
                                +{selectedItems.size - 3}
                              </Badge>
                            )}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </CommonBottomSheet>
              </>
            )}
          </div>
        </CardHeader>
        <CardContent className="pt-6">
          {bomItems && bomItems.length > 0 ? (
            <>
              {/* 데스크톱 테이블 뷰 */}
              <div className="hidden xl:block overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-center min-w-[60px]">순번</TableHead>
                      <TableHead className="min-w-[120px]">품목코드</TableHead>
                      <TableHead className="min-w-[150px]">품목명</TableHead>
                      <TableHead className="text-center min-w-[100px]">품목유형</TableHead>
                      <TableHead className="text-center min-w-[120px]">규격</TableHead>
                      <TableHead className="text-center min-w-[80px]">기준수량</TableHead>
                      <TableHead className="text-center min-w-[80px]">산출수량</TableHead>
                      <TableHead className="text-center min-w-[60px]">단위</TableHead>
                      <TableHead className="text-right min-w-[100px]">단가</TableHead>
                      <TableHead className="text-right min-w-[100px]">금액</TableHead>
                      {onDeleteItem && <TableHead className="text-center min-w-[60px]">작업</TableHead>}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {bomItems.map((item, index) => renderBomItemRow(item, 0, index))}
                  </TableBody>
                </Table>
              </div>
              
              {/* 모바일 카드 뷰 */}
              <div className="xl:hidden space-y-3">
                {bomItems.map((item, index) => renderBomItemCard(item, 0, index))}
              </div>
            </>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              <p>BOM 항목이 없습니다.</p>
              <p className="text-sm mt-2">자동 산출을 실행하거나 품목 추가 버튼을 클릭하세요.</p>
            </div>
          )}
        </CardContent>
      </Card>
      
      {/* 품목별 디버깅 정보 */}
      {showDebug && bomItems.some(item => item.debugInfo) && (
        <Card>
          <CardHeader>
            <div className="flex items-center gap-2">
              <Bug className="h-5 w-5 text-orange-500" />
              <CardTitle>품목별 계산 과정 디버깅</CardTitle>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">{bomItems.map((item, idx) => {
            if (!item.debugInfo) return null;
            
            const debug = item.debugInfo;
            
            return (
              <Collapsible key={item.itemCode} defaultOpen={idx === 0}>
                <div className="border rounded-lg">
                  <CollapsibleTrigger className="w-full p-4 hover:bg-muted/50 transition-colors">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <Badge variant="outline">{item.itemCode}</Badge>
                        <span className="font-medium">{item.itemName}</span>
                        <Badge className="bg-blue-100 text-blue-800 border-blue-200">
                          {item.itemCategory}
                        </Badge>
                      </div>
                      <ChevronDown className="h-4 w-4 transition-transform ui-expanded:rotate-180" />
                    </div>
                  </CollapsibleTrigger>
                  
                  <CollapsibleContent>
                    <div className="border-t p-4 space-y-4 bg-muted/20">
                      {/* Step 1: 수식 */}
                      <div className="space-y-1">
                        <Label className="text-xs text-muted-foreground">Step 1 - 사용된 수식</Label>
                        <div className="bg-white p-3 rounded border font-mono text-sm">
                          {debug.step1_formula}
                        </div>
                      </div>
                      
                      {/* Step 2: 변수 값 */}
                      <div className="space-y-1">
                        <Label className="text-xs text-muted-foreground">Step 2 - 대입된 변수 값</Label>
                        <div className="bg-white p-3 rounded border">
                          <div className="flex flex-wrap gap-2">
                            {Object.entries(debug.step2_variables).map(([key, value]) => (
                              <Badge key={key} variant="secondary" className="font-mono">
                                {key} = {value}
                              </Badge>
                            ))}
                          </div>
                        </div>
                      </div>
                      
                      {/* Step 3-4: 수량 계산 */}
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">Step 3 - 수량 계산 과정</Label>
                          <div className="bg-white p-3 rounded border font-mono text-sm">
                            {debug.step3_quantityCalc}
                          </div>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">Step 4 - 계산된 수량</Label>
                          <div className="bg-green-50 p-3 rounded border border-green-200 font-mono text-green-800">
                            {debug.step4_quantity.toFixed(2)} {item.unit}
                          </div>
                        </div>
                      </div>
                      
                      {/* Step 5-6: 단가 정보 */}
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">Step 5 - 단가 출처</Label>
                          <div className="bg-white p-3 rounded border">
                            {debug.step5_priceSource}
                          </div>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">Step 6 - 기본 단가</Label>
                          <div className="bg-white p-3 rounded border font-mono">
                            {debug.step6_basePrice.toLocaleString()}원
                          </div>
                        </div>
                      </div>
                      
                      {/* Step 7-8: 분류별 변수 곱셈 & 최종 단가 */}
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {debug.step7_categoryMultiplier && (
                          <div className="space-y-1">
                            <Label className="text-xs text-muted-foreground">Step 7 - 분류별 변수 곱셈</Label>
                            <div className="bg-white p-3 rounded border font-mono text-sm">
                              {debug.step7_categoryMultiplier}
                            </div>
                          </div>
                        )}
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">Step 8 - 최종 단가</Label>
                          <div className="bg-blue-50 p-3 rounded border border-blue-200 font-mono text-blue-800">
                            {debug.step8_finalPrice.toLocaleString()}원
                          </div>
                        </div>
                      </div>
                      
                      {/* Step 9-10: 금액 계산 */}
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">Step 9 - 금액 계산 과정</Label>
                          <div className="bg-white p-3 rounded border font-mono text-sm">
                            {debug.step9_totalCalc}
                          </div>
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">Step 10 - 최종 금액</Label>
                          <div className="bg-orange-50 p-3 rounded border border-orange-200 font-mono text-orange-800 font-bold">
                            {debug.step10_total.toLocaleString()}원
                          </div>
                        </div>
                      </div>
                    </div>
                  </CollapsibleContent>
                </div>
              </Collapsible>
            );
          })}</CardContent>
        </Card>
      )}
      
      {/* 할인 및 최종 금액 */}
      <Card>
        <CardContent className="pt-6">
          <div className="space-y-4">
            {/* 할인율 입력 */}
            <div className="flex items-center justify-end gap-4">
              <Label htmlFor="discountRate" className="text-sm">할인율 (%)</Label>
              <Input
                id="discountRate"
                type="number"
                value={discountRate}
                onChange={(e) => setDiscountRate(Number(e.target.value))}
                className="w-24 text-right"
                min="0"
                max="100"
              />
            </div>
            
            {/* 금액 요약 */}
            <div className="border-t pt-4 space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">합계</span>
                <span className="font-[Pretendard]">{subtotal.toLocaleString()}원</span>
              </div>
              
              {discountRate > 0 && (
                <div className="flex justify-between text-sm text-red-600">
                  <span>할인 ({discountRate}%)</span>
                  <span className="font-[Pretendard]">-{discountAmount.toLocaleString()}원</span>
                </div>
              )}
              
              <div className="flex justify-between text-sm">
                <span className="text-muted-foreground">공급가</span>
                <span className="font-[Pretendard]">{supplyPrice.toLocaleString()}원</span>
              </div>
              
              <div className="flex justify-between border-t pt-2">
                <span className="font-semibold">최종 금액</span>
                <span className="font-[Pretendard] text-blue-600 font-bold">
                  {finalAmount.toLocaleString()}원
                </span>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
      
      {/* 삭제 확인 다이얼로그 */}
      <ConfirmDialog
        open={deleteConfirmOpen}
        onOpenChange={setDeleteConfirmOpen}
        title="품목 삭제 확인"
        description={`"${itemToDelete?.name}" 품목을 삭제하시겠습니까?`}
        onConfirm={handleDeleteConfirm}
      />
    </div>
  );
}