import React, { useState, useEffect } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Plus, Check, ChevronsUpDown, Copy, Trash2 } from "lucide-react";
import { Badge } from "./ui/badge";
import { useData } from "./contexts/DataContext";
import type { FormulaRule } from "./contexts/DataContext";
import { BomCalculationResults } from "./BomCalculationResults";
import { generateGuideRailRules } from "./GuideRailRulesGenerator";
import { generateCaseRules } from "./CaseRulesGenerator";
import { calculateItemPrice } from "./utils/priceCalculator";
import { consolidateAndPriceAutoBomResults } from "./utils/autoBomPriceCalculator";
import { calculateBomWithDebug } from "./utils/bomCalculatorWithDebug";
import { toast } from "sonner@2.0.3";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "./ui/command";
import { cn } from "./ui/utils";

interface QuoteItem {
  id: string;
  name: string;
  productId: string;
  category: string;
  floors: string;
  sign: string;
  w0: number;
  h0: number;
  guideRailInstallType: string;
  power: string;
  controller: string;
  quantity: number;
  edgeWingSize: number;
  inspectionFee: number;
}

interface AutoCalculationSimulatorProps {
  onCalculationComplete?: (results: any) => void;
  showSampleButton?: boolean;
  showResults?: boolean;
  initialSettings?: {
    productId?: string;
    productName?: string;
    productCategory?: string;
    openSizeWidth?: number;
    openSizeHeight?: number;
    guideRailInstallType?: string;
    motorPower?: string;
    controller?: string;
    quantity?: number;
    edgeWingSize?: number;
    inspectionFee?: number;
  };
}

export function AutoCalculationSimulator({ 
  onCalculationComplete,
  showSampleButton = true,
  showResults = true,
  initialSettings
}: AutoCalculationSimulatorProps) {
  const { 
    itemMasters, 
    pricing, 
    formulaRules, 
    formulas,
    categoryGroups,
    addItemMaster, 
    setItemMasters, 
    setFormulaRules 
  } = useData();
  
  // 단가 맵핑 데이터 로드
  const [priceMappings, setPriceMappings] = useState<any[]>([]);
  
  // 디버깅 표시 여부 상태 추가
  const [showDebug, setShowDebug] = useState<boolean>(() => {
    try {
      const saved = localStorage.getItem('autoCalculation_showDebug');
      return saved ? JSON.parse(saved) : false;
    } catch {
      return false;
    }
  });
  
  // showDebug를 localStorage에 저장
  useEffect(() => {
    try {
      localStorage.setItem('autoCalculation_showDebug', JSON.stringify(showDebug));
    } catch (error) {
      console.error('Failed to save showDebug to localStorage:', error);
    }
  }, [showDebug]);
  
  useEffect(() => {
    const savedMappings = localStorage.getItem("priceMappingItems");
    if (savedMappings) {
      const mappings = JSON.parse(savedMappings);
      console.log(`📋 단가 맵핑 데이터 로드: ${mappings.length}개`);
      setPriceMappings(mappings);
    }
  }, []);
  
  // pricing 데이터 사용
  const pricings = pricing || [];
  
  // formulaRules에서 카테고리별 규칙 필터링
  const categoryRules = formulaRules || [];
  const itemCategoryRules = formulaRules || [];

  // 다중 견적 데이터
  const [quotes, setQuotes] = useState<QuoteItem[]>([
    {
      id: `quote-${Date.now()}`,
      name: "견적 1",
      productId: initialSettings?.productId || "",
      category: initialSettings?.productCategory || "",
      floors: "",
      sign: "",
      w0: initialSettings?.openSizeWidth || 0,
      h0: initialSettings?.openSizeHeight || 0,
      guideRailInstallType: initialSettings?.guideRailInstallType || "",
      power: initialSettings?.motorPower || "",
      controller: initialSettings?.controller || "",
      quantity: initialSettings?.quantity || 1,
      edgeWingSize: initialSettings?.edgeWingSize || 50,
      inspectionFee: initialSettings?.inspectionFee || 50000,
    }
  ]);

  // 견적 산출 결과
  const [calculationResults, setCalculationResults] = useState<any>(() => {
    try {
      const saved = localStorage.getItem('autoCalculation_results');
      return saved ? JSON.parse(saved) : null;
    } catch {
      return null;
    }
  });
  
  // calculationResults를 localStorage에 저장
  useEffect(() => {
    try {
      if (calculationResults) {
        localStorage.setItem('autoCalculation_results', JSON.stringify(calculationResults));
      }
    } catch (error) {
      console.error('Failed to save calculationResults to localStorage:', error);
    }
  }, [calculationResults]);
  
  // bomItems 수정을 위한 함수들
  const handleUpdateBomItem = (quoteIndex: number, itemCode: string, field: 'calculatedQuantity' | 'unitPrice', value: number) => {
    setCalculationResults((prev: any) => {
      if (!prev?.quotes) return prev;
      
      const newQuotes = [...prev.quotes];
      const quote = newQuotes[quoteIndex];
      
      // BOM 아이템 찾아서 업데이트 (재귀적으로)
      const updateItem = (items: any[]): any[] => {
        return items.map(item => {
          if (item.itemCode === itemCode) {
            const updated = { ...item, [field]: value };
            // 금액 재계산
            updated.totalPrice = updated.calculatedQuantity * updated.unitPrice;
            return updated;
          }
          if (item.children && item.children.length > 0) {
            return { ...item, children: updateItem(item.children) };
          }
          return item;
        });
      };
      
      quote.bomItems = updateItem(quote.bomItems || []);
      
      // 총 금액 재계산
      const calculateTotal = (items: any[]): number => {
        return items.reduce((sum, item) => {
          let total = item.totalPrice;
          if (item.children && item.children.length > 0) {
            total += calculateTotal(item.children);
          }
          return sum + total;
        }, 0);
      };
      
      if (quote.summary) {
        quote.summary.totalPrice = calculateTotal(quote.bomItems || []);
      }
      
      return { ...prev, quotes: newQuotes };
    });
  };
  
  const handleDeleteBomItem = (quoteIndex: number, itemCode: string) => {
    setCalculationResults((prev: any) => {
      if (!prev?.quotes) return prev;
      
      const newQuotes = [...prev.quotes];
      const quote = newQuotes[quoteIndex];
      
      // BOM 아이템 삭제 (재귀적으로)
      const deleteItem = (items: any[]): any[] => {
        return items.filter(item => {
          if (item.itemCode === itemCode) return false;
          if (item.children && item.children.length > 0) {
            item.children = deleteItem(item.children);
          }
          return true;
        });
      };
      
      quote.bomItems = deleteItem(quote.bomItems || []);
      
      // 총 금액 재계산
      const calculateTotal = (items: any[]): number => {
        return items.reduce((sum, item) => {
          let total = item.totalPrice;
          if (item.children && item.children.length > 0) {
            total += calculateTotal(item.children);
          }
          return sum + total;
        }, 0);
      };
      
      if (quote.summary) {
        quote.summary.totalPrice = calculateTotal(quote.bomItems || []);
      }
      
      return { ...prev, quotes: newQuotes };
    });
    
    toast.success('품목이 삭제되었습니다.');
  };
  
  const handleAddBomItem = (quoteIndex: number, newItem: any) => {
    setCalculationResults((prev: any) => {
      if (!prev?.quotes) return prev;
      
      const newQuotes = [...prev.quotes];
      const quote = newQuotes[quoteIndex];
      
      if (!quote.bomItems) {
        quote.bomItems = [];
      }
      
      quote.bomItems.push(newItem);
      
      // 총 금액 재계산
      const calculateTotal = (items: any[]): number => {
        return items.reduce((sum, item) => {
          let total = item.totalPrice;
          if (item.children && item.children.length > 0) {
            total += calculateTotal(item.children);
          }
          return sum + total;
        }, 0);
      };
      
      if (quote.summary) {
        quote.summary.totalPrice = calculateTotal(quote.bomItems || []);
      }
      
      return { ...prev, quotes: newQuotes };
    });
    
    toast.success('품목이 추가되었습니다.');
  };
  
  const [fieldErrors, setFieldErrors] = useState<{[key: string]: {[field: string]: string}}>({});
  const [productSearchOpen, setProductSearchOpen] = useState<{[key: string]: boolean}>({});

  // 견적 추가
  const handleAddQuote = () => {
    const newQuote: QuoteItem = {
      id: `quote-${Date.now()}`,
      name: `견적 ${quotes.length + 1}`,
      productId: "",
      category: "",
      floors: "",
      sign: "",
      w0: 0,
      h0: 0,
      guideRailInstallType: "",
      power: "",
      controller: "",
      quantity: 1,
      edgeWingSize: 50,
      inspectionFee: 50000,
    };
    setQuotes([...quotes, newQuote]);
  };

  // 견적 복사
  const handleCopyQuote = (quoteId: string) => {
    const quoteToCopy = quotes.find(q => q.id === quoteId);
    if (quoteToCopy) {
      const newQuote: QuoteItem = {
        ...quoteToCopy,
        id: `quote-${Date.now()}`,
        name: `${quoteToCopy.name} (복사)`,
      };
      setQuotes([...quotes, newQuote]);
      toast.success("견적이 복사되었습니다");
    }
  };

  // 견적 삭제
  const handleDeleteQuote = (quoteId: string) => {
    if (quotes.length === 1) {
      toast.error("최소 1개의 견적은 유지되어야 합니다");
      return;
    }
    setQuotes(quotes.filter(q => q.id !== quoteId));
    toast.success("견적이 삭제되었습니다");
  };

  // 견적 업데이트
  const handleQuoteChange = (quoteId: string, field: string, value: any) => {
    setQuotes(quotes.map(q => q.id === quoteId ? { ...q, [field]: value } : q));
    // 해당 필드의 에러 클리어
    setFieldErrors(prev => ({
      ...prev,
      [quoteId]: {
        ...prev[quoteId],
        [field]: ''
      }
    }));
  };

  // 개별 필드 validation 함수
  const validateField = (fieldName: string, value: any): string => {
    switch(fieldName) {
      case 'productId':
        return !value ? '제품명을 선택해주세요.' : '';
      case 'category':
        return !value ? '제품 카테고리를 선택해주세요.' : '';
      case 'w0':
        return (!value || value <= 0) ? '오픈사이즈 W0를 입력해주세요.' : '';
      case 'h0':
        return (!value || value <= 0) ? '오픈사이즈 H0를 입력해주세요.' : '';
      case 'guideRailInstallType':
        return !value ? '가이드레일 설치 유형을 선택해주세요.' : '';
      case 'power':
        return !value ? '모터 전원을 선택해주세요.' : '';
      case 'controller':
        return !value ? '연동제어기를 선택해주세요.' : '';
      case 'quantity':
        // quantity는 기본값 1을 고려
        const qty = value || 1;
        return (qty <= 0) ? '수량을 입력해주세요.' : '';
      default:
        return '';
    }
  };

  // 모든 견적 validation
  const validateAllQuotes = (): boolean => {
    const errors: {[key: string]: {[field: string]: string}} = {};
    let hasError = false;
    
    quotes.forEach(quote => {
      const quoteErrors: {[field: string]: string} = {};
      
      quoteErrors.productId = validateField('productId', quote.productId);
      quoteErrors.category = validateField('category', quote.category);
      quoteErrors.w0 = validateField('w0', quote.w0);
      quoteErrors.h0 = validateField('h0', quote.h0);
      quoteErrors.guideRailInstallType = validateField('guideRailInstallType', quote.guideRailInstallType);
      quoteErrors.power = validateField('power', quote.power);
      quoteErrors.controller = validateField('controller', quote.controller);
      quoteErrors.quantity = validateField('quantity', quote.quantity);

      errors[quote.id] = quoteErrors;
      
      if (Object.values(quoteErrors).some(error => error !== '')) {
        hasError = true;
      }
    });

    setFieldErrors(errors);
    return !hasError;
  };

  // 자동 산출 실행
  const handleAutoCalculation = async () => {
    console.log('🎯 자동 산출 시작');
    
    if (!validateAllQuotes()) {
      toast.error("필수 입력값을 확인해주세요");
      return;
    }

    toast.success(`${quotes.length}개 견적 산출을 시작합니다`);
    
    try {
      // 각 견적에 대해 BOM 계산 수행
      const allResults: any[] = [];
      
      for (const quote of quotes) {
        // 제품 정보 가져오기
        const selectedProduct = itemMasters.find(p => p.id === quote.productId);
        if (!selectedProduct) {
          console.error(`제품을 찾을 수 없음: ${quote.productId}`);
          continue;
        }

        console.log(`\n${'='.repeat(80)}`);
        console.log(`📊 [${quote.name}] BOM 계산 시작`);
        console.log(`제품: ${selectedProduct.itemName} (${selectedProduct.itemCode})`);
        console.log(`카테고리: ${quote.category}`);
        console.log(`오픈사이즈: W${quote.w0} × H${quote.h0}`);
        console.log(`${'='.repeat(80)}\n`);

        // 제품의 BOM 구조 읽기
        const productBom = selectedProduct.bom || [];
        console.log(`📦 제품 BOM 항목 수: ${productBom.length}개`);
        
        if (productBom.length === 0) {
          console.warn(`⚠️ [${quote.name}] 제품에 BOM이 없습니다.`);
          continue;
        }
        
        // 계산 변수 설정
        const calculationVariables = {
          W0: quote.w0,
          H0: quote.h0,
          W1: quote.category === '스크린' ? quote.w0 + 140 : quote.w0 + 110,
          H1: quote.h0 + 350,
          W: 0, // W는 W1으로 매핑
          H: 0, // H는 H1으로 매핑
          M: 0, // 면적은 나중에 계산
          K: 0  // 중량은 나중에 계산
        };
        
        // W와 H를 W1, H1으로 매핑
        calculationVariables.W = calculationVariables.W1;
        calculationVariables.H = calculationVariables.H1;
        calculationVariables.M = (calculationVariables.W1 * calculationVariables.H1) / 1000000;
        
        console.log(`📐 계산 변수:`, calculationVariables);

        // BOM 항목들을 처리
        const bomItems: any[] = [];
        
        for (const bomEntry of productBom) {
          const childItem = itemMasters.find(item => item.itemCode === bomEntry.childItemCode);
          if (!childItem) {
            console.warn(`⚠️ BOM 항목을 찾을 수 없음: ${bomEntry.childItemCode}`);
            continue;
          }
          
          // 수량 계산
          let calculatedQuantity = bomEntry.quantity || 1;
          let debugFormula = `기준수량: ${bomEntry.quantity}`;
          
          // 수식이 있으면 계산
          if (bomEntry.quantityFormula && bomEntry.quantityFormula.trim() !== '') {
            try {
              // 수식의 변수를 실제 값으로 치환
              let formula = bomEntry.quantityFormula;
              let originalFormula = formula;
              
              // 변수를 값으로 치환 (긴 변수명부터 처리)
              const sortedVariables = Object.keys(calculationVariables).sort((a, b) => b.length - a.length);
              for (const varName of sortedVariables) {
                const value = (calculationVariables as any)[varName];
                // 변수명을 정확히 매칭 (단어 경계 사용)
                const regex = new RegExp(`\\b${varName}\\b`, 'g');
                formula = formula.replace(regex, String(value));
              }
              
              console.log(`  🔢 수식 계산: ${originalFormula} → ${formula}`);
              
              // 수식 계산
              calculatedQuantity = eval(formula);
              debugFormula = `${originalFormula} = ${formula} = ${calculatedQuantity.toFixed(2)}`;
              console.log(`  ✓ ${childItem.itemName}: ${debugFormula}`);
            } catch (error) {
              console.error(`  ✗ 수식 계산 실패 (${childItem.itemName}):`, error);
              debugFormula = `수식 오류: ${bomEntry.quantityFormula}`;
            }
          }
          
          // 단가 조회 (1순위: pricing, 2순위: itemMaster)
          let unitPrice = 0;
          let priceSource = '단가 없음';
          
          const itemPricing = pricings.find(p => p.itemCode === bomEntry.childItemCode);
          if (itemPricing && itemPricing.salesPrice) {
            unitPrice = itemPricing.salesPrice;
            priceSource = `단가관리 (${unitPrice.toLocaleString()}원)`;
          } else if (childItem.salesPrice) {
            unitPrice = childItem.salesPrice;
            priceSource = `품목마스터 (${unitPrice.toLocaleString()}원)`;
          }
          
          // 카테고리별 단가 계산 방식 결정
          const itemCategory = childItem.itemCategory || childItem.category1 || '기타';
          let finalUnitPrice = unitPrice;
          let priceCalculationNote = '';
          
          // 면적 기반 단가 품목 판단 (원단, 패널, 도장 등)
          const areaBasedCategories = ['원단', '패널', '도장', '표면처리'];
          const isAreaBased = areaBasedCategories.some(cat => 
            itemCategory.includes(cat) || childItem.itemName.includes(cat)
          );
          
          if (isAreaBased && calculationVariables.M > 0) {
            // 면적 단가: 단가 = 기본단가 × 면적
            finalUnitPrice = unitPrice * calculationVariables.M;
            priceCalculationNote = `면적단가 (${unitPrice.toLocaleString()}원/㎡ × ${calculationVariables.M.toFixed(2)}㎡)`;
          } else {
            // 수량 단가: 단가 그대로 사용
            priceCalculationNote = `수량단가`;
          }
          
          console.log(`  💰 ${childItem.itemName}: ${priceSource} → ${priceCalculationNote}`);
          
          // 금액 계산
          const totalPrice = calculatedQuantity * finalUnitPrice;
          
          bomItems.push({
            itemCode: childItem.itemCode,
            itemName: childItem.itemName,
            itemCategory: itemCategory,
            quantityFormula: bomEntry.quantityFormula || '',
            calculatedQuantity: calculatedQuantity,
            unit: childItem.unit,
            unitPrice: finalUnitPrice,
            totalPrice: totalPrice,
            children: [], // 하위 BOM은 나중에 구현
            debugInfo: {
              step1_formula: bomEntry.quantityFormula || '수식 없음',
              step2_variables: calculationVariables,
              step3_quantityCalc: debugFormula,
              step4_quantity: calculatedQuantity,
              step5_priceSource: priceSource,
              step6_basePrice: unitPrice,
              step7_categoryMultiplier: priceCalculationNote,
              step8_finalPrice: finalUnitPrice,
              step9_totalCalc: `${calculatedQuantity.toFixed(2)} × ${finalUnitPrice.toLocaleString()} = ${totalPrice.toLocaleString()}`,
              step10_total: totalPrice
            }
          });
        }
        
        console.log(`✅ BOM 항목 생성 완료: ${bomItems.length}개`);
        
        // 총 금액 계산
        const totalAmount = bomItems.reduce((sum, item) => sum + item.totalPrice, 0);
        console.log(`💵 총 금액: ${totalAmount.toLocaleString()}원`);

        const bomResult = {
          productName: selectedProduct.itemName,
          productCategory: quote.category,
          windingShaftResults: [],
          guideRailResults: [],
          baseResults: [],
          smokeBarrierResults: [],
          caseItemResults: [],
          motorResults: [],
          controllerResults: [],
          edgeWingResults: [],
          inspectionResults: [],
          basic: {
            w0: quote.w0,
            h0: quote.h0,
            w1: calculationVariables.W1,
            h1: calculationVariables.H1,
            area: calculationVariables.M,
            weight: calculationVariables.K,
            productName: selectedProduct.itemName,
            category: quote.category,
            quantity: quote.quantity
          },
          summary: {
            totalPrice: totalAmount
          }
        };

        console.log(`\n✅ [${quote.name}] BOM 계산 완료`);
        console.log(`생성된 BOM 항목 수: ${bomItems.length}개`);

        // 단가 계산 (이미 계산했으므로 그대로 사용)
        const pricedItems = bomItems;

        // 견적 정보 추가
        const quoteResult = {
          ...bomResult,
          bomItems: pricedItems,
          quoteName: quote.name,
          floors: quote.floors,
          sign: quote.sign,
          quoteId: quote.id,
          productName: selectedProduct.itemName,
          productCategory: quote.category,
          selectedProductId: selectedProduct.id,
          openSize: {
            width: quote.w0,
            height: quote.h0
          },
          guideRailInstallType: quote.guideRailInstallType,
          motorPower: quote.power,
          controller: quote.controller,
          quantity: quote.quantity,
          edgeWingSize: quote.edgeWingSize,
          inspectionFee: quote.inspectionFee,
          totalAmount: totalAmount
        };

        allResults.push(quoteResult);
      }

      console.log(`\n${'='.repeat(80)}`);
      console.log(`🎉 전체 견적 산출 완료: ${allResults.length}개`);
      console.log(`${'='.repeat(80)}\n`);

      // 결과 저장 (다중 견적 결과를 배열로 저장)
      setCalculationResults({
        quotes: allResults,
        totalCount: allResults.length
      });

      // 콜백 호출
      if (onCalculationComplete) {
        const resultData = {
          quotes: allResults,
          totalCount: allResults.length
        };
        console.log("🚀 AutoCalculationSimulator - 콜백 호출 데이터:", resultData);
        console.log("🚀 첫 번째 견적 상세:", allResults[0]);
        onCalculationComplete(resultData);
      }

      toast.success(`${allResults.length}개 견적 산출이 완료되었습니다`);
    } catch (error) {
      console.error('❌ 견적 산출 중 오류 발생:', error);
      toast.error('견적 산출 중 오류가 발생했습니다');
    }
  };

  return (
    <div className="space-y-6">
      {/* 견적 입력 카드들 */}
      <div className="space-y-4">
        {quotes.map((quote, index) => (
          <Card key={quote.id}>
            <CardHeader className="pb-[0px] pt-[24px] pr-[24px] pl-[24px] px-[24px] py-[0px]">
              <div className="flex items-center justify-between mt-[16px] mr-[0px] mb-[0px] ml-[0px] pb-4 border-b border-gray-200">
                <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200 px-3 py-1.5 text-sm">
                  {quote.name}
                </Badge>
                <div className="flex gap-2">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleCopyQuote(quote.id)}
                    className="p-0 h-8 w-8"
                  >
                    <Copy className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleDeleteQuote(quote.id)}
                    disabled={quotes.length === 1}
                    className="p-0 h-8 w-8 text-red-600 hover:text-red-700 hover:bg-red-50"
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 통합 그리드 - 모든 필드 */}
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                {/* 층수 */}
                <div className="space-y-2">
                  <Label>층수</Label>
                  <Input
                    type="text"
                    value={quote.floors || ''}
                    onChange={(e) => handleQuoteChange(quote.id, 'floors', e.target.value)}
                    placeholder="예: 1층, B1, 지하1층"
                  />
                </div>

                {/* 부호 */}
                <div className="space-y-2">
                  <Label>부호</Label>
                  <Input
                    type="text"
                    value={quote.sign || ''}
                    onChange={(e) => handleQuoteChange(quote.id, 'sign', e.target.value)}
                    placeholder="예: A, B, C"
                  />
                </div>

                {/* 제품 카테고리 */}
                <div className="space-y-2">
                  <Label>제품 카테고리 (PC) <span className="text-red-500">*</span></Label>
                  <Select
                    value={quote.category || undefined}
                    onValueChange={(value) => {
                      console.log('✅ 카테고리 선택:', value);
                      // 한 번에 상태 업데이트
                      setQuotes(quotes.map(q => 
                        q.id === quote.id 
                          ? { ...q, category: value, productId: '' } 
                          : q
                      ));
                      // 에러 클리어
                      setFieldErrors(prev => ({
                        ...prev,
                        [quote.id]: {
                          ...prev[quote.id],
                          category: '',
                          productId: ''
                        }
                      }));
                    }}
                  >
                    <SelectTrigger className={fieldErrors?.[quote.id]?.category ? 'border-red-500' : ''}>
                      <SelectValue placeholder="카테고리 선택" />
                    </SelectTrigger>
                    <SelectContent position="item-aligned">
                      <SelectItem value="스크린">스크린</SelectItem>
                      <SelectItem value="철재">철재</SelectItem>
                    </SelectContent>
                  </Select>
                  {fieldErrors[quote.id]?.category && (
                    <p className="text-sm text-red-500">{fieldErrors[quote.id].category}</p>
                  )}
                </div>

                {/* 제품명 */}
                <div className="space-y-2">
                  <Label>제품명 <span className="text-red-500">*</span></Label>
                  <Popover open={productSearchOpen[quote.id]} onOpenChange={(open) => setProductSearchOpen({...productSearchOpen, [quote.id]: open})}>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        aria-expanded={productSearchOpen[quote.id]}
                        className={cn(
                          "w-full justify-between h-9",
                          fieldErrors[quote.id]?.productId && "border-red-500",
                          !quote.productId && "text-muted-foreground"
                        )}
                      >
                        {quote.productId
                          ? (() => {
                              const selectedProduct = itemMasters.find((p) => p.id === quote.productId);
                              return selectedProduct ? `${selectedProduct.itemName} (${selectedProduct.itemCode})` : "제품을 선택하세요";
                            })()
                          : "제품을 선택하세요"}
                        <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
                      <Command>
                        <CommandInput placeholder="제품 검색..." />
                        <CommandList>
                          <CommandEmpty>검색 결과가 없습니다.</CommandEmpty>
                          <CommandGroup>
                            {itemMasters
                              .filter((item) => item.itemType === 'FG')
                              .filter((item) => {
                                if (!quote.category) return true;
                                // 카테고리 매핑: "스크린" → "SCREEN", "철재" → "STEEL"
                                const categoryMap: Record<string, string> = {
                                  '스크린': 'SCREEN',
                                  '철재': 'STEEL'
                                };
                                const mappedCategory = categoryMap[quote.category];
                                return item.productCategory === mappedCategory;
                              })
                              .map((product) => (
                                <CommandItem
                                  key={product.id}
                                  value={`${product.itemName} ${product.itemCode}`}
                                  onSelect={() => {
                                    handleQuoteChange(quote.id, 'productId', product.id);
                                    setProductSearchOpen({...productSearchOpen, [quote.id]: false});
                                  }}
                                >
                                  <Check
                                    className={cn(
                                      "mr-2 h-4 w-4",
                                      quote.productId === product.id ? "opacity-100" : "opacity-0"
                                    )}
                                  />
                                  {product.itemName} ({product.itemCode})
                                </CommandItem>
                              ))}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                  {fieldErrors[quote.id]?.productId && (
                    <p className="text-sm text-red-500">{fieldErrors[quote.id].productId}</p>
                  )}
                </div>

                {/* 오픈사이즈 (W0) */}
                <div className="space-y-2">
                  <Label>오픈사이즈 (W0) <span className="text-red-500">*</span></Label>
                  <Input
                    type="number"
                    value={quote.w0 || ''}
                    onChange={(e) => handleQuoteChange(quote.id, 'w0', Number(e.target.value))}
                    placeholder="예: 2000"
                    className={fieldErrors[quote.id]?.w0 ? 'border-red-500' : ''}
                  />
                  {fieldErrors[quote.id]?.w0 && (
                    <p className="text-sm text-red-500">{fieldErrors[quote.id].w0}</p>
                  )}
                </div>

                {/* 오픈사이즈 (H0) */}
                <div className="space-y-2">
                  <Label>오픈사이즈 (H0) <span className="text-red-500">*</span></Label>
                  <Input
                    type="number"
                    value={quote.h0 || ''}
                    onChange={(e) => handleQuoteChange(quote.id, 'h0', Number(e.target.value))}
                    placeholder="예: 2500"
                    className={fieldErrors[quote.id]?.h0 ? 'border-red-500' : ''}
                  />
                  {fieldErrors[quote.id]?.h0 && (
                    <p className="text-sm text-red-500">{fieldErrors[quote.id].h0}</p>
                  )}
                </div>

                {/* 가이드레일 설치 유형 */}
                <div className="space-y-2">
                  <Label>가이드레일 설치 유형 (GT) <span className="text-red-500">*</span></Label>
                  <Select
                    value={quote.guideRailInstallType}
                    onValueChange={(value) => handleQuoteChange(quote.id, 'guideRailInstallType', value)}
                  >
                    <SelectTrigger className={fieldErrors[quote.id]?.guideRailInstallType ? 'border-red-500' : ''}>
                      <SelectValue placeholder="설치 유형 선택" />
                    </SelectTrigger>
                    <SelectContent position="item-aligned">
                      <SelectItem value="벽면형">벽면형</SelectItem>
                      <SelectItem value="측면형">측면형</SelectItem>
                    </SelectContent>
                  </Select>
                  {fieldErrors[quote.id]?.guideRailInstallType && (
                    <p className="text-sm text-red-500">{fieldErrors[quote.id].guideRailInstallType}</p>
                  )}
                </div>

                {/* 모터 전원 */}
                <div className="space-y-2">
                  <Label>모터 전원 (MP) <span className="text-red-500">*</span></Label>
                  <Select
                    value={quote.power}
                    onValueChange={(value) => handleQuoteChange(quote.id, 'power', value)}
                  >
                    <SelectTrigger className={fieldErrors[quote.id]?.power ? 'border-red-500' : ''}>
                      <SelectValue placeholder="전원 선택" />
                    </SelectTrigger>
                    <SelectContent position="item-aligned">
                      <SelectItem value="220V">220V</SelectItem>
                      <SelectItem value="380V">380V</SelectItem>
                    </SelectContent>
                  </Select>
                  {fieldErrors[quote.id]?.power && (
                    <p className="text-sm text-red-500">{fieldErrors[quote.id].power}</p>
                  )}
                </div>

                {/* 연동제어기 */}
                <div className="space-y-2">
                  <Label>연동제어기 (CT) <span className="text-red-500">*</span></Label>
                  <Select
                    value={quote.controller}
                    onValueChange={(value) => handleQuoteChange(quote.id, 'controller', value)}
                  >
                    <SelectTrigger className={fieldErrors[quote.id]?.controller ? 'border-red-500' : ''}>
                      <SelectValue placeholder="제어기 선택" />
                    </SelectTrigger>
                    <SelectContent position="item-aligned">
                      <SelectItem value="단독">단독</SelectItem>
                      <SelectItem value="연동">연동</SelectItem>
                    </SelectContent>
                  </Select>
                  {fieldErrors[quote.id]?.controller && (
                    <p className="text-sm text-red-500">{fieldErrors[quote.id].controller}</p>
                  )}
                </div>

                {/* 수량 */}
                <div className="space-y-2">
                  <Label>수량 (QTY) <span className="text-red-500">*</span></Label>
                  <Input
                    type="number"
                    value={quote.quantity || 1}
                    onChange={(e) => handleQuoteChange(quote.id, 'quantity', Number(e.target.value))}
                    placeholder="예: 1"
                    className={fieldErrors[quote.id]?.quantity ? 'border-red-500' : ''}
                  />
                  {fieldErrors[quote.id]?.quantity && (
                    <p className="text-sm text-red-500">{fieldErrors[quote.id].quantity}</p>
                  )}
                </div>

                {/* 마구리 날개치수 */}
                <div className="space-y-2">
                  <Label>마구리 날개치수 (WS)</Label>
                  <Input
                    type="number"
                    value={quote.edgeWingSize || 50}
                    onChange={(e) => handleQuoteChange(quote.id, 'edgeWingSize', Number(e.target.value))}
                    placeholder="예: 50"
                  />
                </div>

                {/* 검사비 */}
                <div className="space-y-2">
                  <Label>검사비 (INSP)</Label>
                  <Input
                    type="number"
                    value={quote.inspectionFee || 50000}
                    onChange={(e) => handleQuoteChange(quote.id, 'inspectionFee', Number(e.target.value))}
                    placeholder="예: 50000"
                  />
                </div>
              </div>
            </CardContent>
          </Card>
        ))}

        {/* 견적 추가 버튼 */}
        <Button
          variant="outline"
          className="w-full h-12 border-dashed"
          onClick={handleAddQuote}
        >
          <Plus className="mr-2 h-4 w-4" />
          견적 추가
        </Button>
      </div>

      {/* 산출 버튼 */}
      <Button onClick={handleAutoCalculation} className="w-full h-12">
        견적 견적 산출 ({quotes.length}개 항목)
      </Button>

      {/* 결과 표시 */}
      {showResults && calculationResults?.quotes && calculationResults.quotes.length > 0 && (
        <div className="space-y-4">
          {/* 다중 견적 통합 금액 (2개 이상일 때만 표시) */}
          {calculationResults.quotes.length > 1 && (
            <Card className="bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200">
              <CardHeader>
                <CardTitle className="flex items-center justify-between">
                  <span className="text-blue-900">전체 통합 금액</span>
                  <Badge variant="outline" className="bg-white text-blue-700 border-blue-300">
                    {calculationResults.quotes.length}개 견적
                  </Badge>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {/* 각 견적별 금액 */}
                <div className="space-y-2">
                  {calculationResults.quotes.map((result: any, index: number) => (
                    <div key={index} className="flex items-center justify-between text-sm">
                      <span className="text-gray-700">
                        {result.quoteName}
                        {(result.floors || result.sign) && (
                          <span className="text-xs text-gray-500 ml-2">
                            ({result.floors}{result.floors && result.sign && ' / '}{result.sign})
                          </span>
                        )}
                      </span>
                      <span className="font-[Pretendard] font-medium">
                        {result.summary?.totalPrice?.toLocaleString() || 0}원
                      </span>
                    </div>
                  ))}
                </div>
                
                {/* 총합계 */}
                <div className="border-t border-blue-200 pt-3 mt-3">
                  <div className="flex items-center justify-between">
                    <span className="font-semibold text-blue-900">총 합계</span>
                    <span className="font-[Pretendard] text-xl font-bold text-blue-700">
                      {calculationResults.quotes
                        .reduce((sum: number, result: any) => sum + (result.summary?.totalPrice || 0), 0)
                        .toLocaleString()}원
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
          
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold">견적 산출 결과 ({calculationResults.totalCount}개)</h3>
            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                id="showDebugCheckbox"
                checked={showDebug}
                onChange={(e) => setShowDebug(e.target.checked)}
                className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <label htmlFor="showDebugCheckbox" className="text-sm cursor-pointer">
                디버깅
              </label>
            </div>
          </div>
          {calculationResults.quotes.map((result: any, index: number) => (
            <Card key={result.quoteId || index}>
              <CardHeader>
                <CardTitle className="text-base flex items-center justify-between">
                  <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200 text-sm rounded-md px-3 py-1.5">
                    {result.quoteName}
                  </Badge>
                  <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200 text-sm rounded-md px-3 py-1.5">
                    총 {result.summary?.totalPrice?.toLocaleString() || 0}원
                  </Badge>
                </CardTitle>
                {(result.floors || result.sign) && (
                  <div className="text-sm text-gray-600 mt-2">
                    {result.floors && <span>층수: {result.floors}</span>}
                    {result.floors && result.sign && <span className="mx-2">|</span>}
                    {result.sign && <span>부호: {result.sign}</span>}
                  </div>
                )}
              </CardHeader>
              <CardContent>
                <BomCalculationResults
                  productName={result.productName || result.basic?.productName || ''}
                  productCategory={result.basic?.category || result.productCategory || ''}
                  w0={result.basic?.w0 || result.openSize?.width || 0}
                  h0={result.basic?.h0 || result.openSize?.height || 0}
                  guideRailInstallType={result.guideRailInstallType || ''}
                  motorPower={result.motorPower || ''}
                  controller={result.controller || ''}
                  quantity={result.quantity || result.basic?.quantity || 1}
                  w1={result.basic?.w1 || 0}
                  h1={result.basic?.h1 || 0}
                  area={result.basic?.area || 0}
                  weight={result.basic?.weight || 0}
                  bomItems={result.bomItems || []}
                  showDebug={showDebug}
                  onUpdateItem={(itemCode, field, value) => handleUpdateBomItem(index, itemCode, field, value)}
                  onDeleteItem={(itemCode) => handleDeleteBomItem(index, itemCode)}
                  onAddItem={(newItem) => handleAddBomItem(index, newItem)}
                />
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}