import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Badge } from "./ui/badge";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { useData } from "./contexts/DataContext";
import { AutoCalculationWithTabs } from "./AutoCalculationWithTabs";
import { toast } from "sonner@2.0.3";
import { 
  FileText, 
  Plus, 
  Trash2,
  Calculator,
  Download,
  Send,
  TrendingUp,
  Package,
  DollarSign,
  Percent,
  Save,
  ArrowLeft,
  Filter,
  AlertCircle
} from "lucide-react";

interface QuoteItem {
  id: string;
  productCode: string;
  productName: string;
  quantity: number;
  unitPrice: number;
  discount: number;
  total: number;
}

interface QuoteSimulationProps {
  onBack?: () => void;
}

export function QuoteSimulation({ onBack }: QuoteSimulationProps = {}) {
  const { itemMasters, addQuote, quotes } = useData();
  
  const [customerName, setCustomerName] = useState("");
  const [projectName, setProjectName] = useState("");
  const [customerType, setCustomerType] = useState("new");
  const [quoteItems, setQuoteItems] = useState<QuoteItem[]>([]);
  const [selectedProduct, setSelectedProduct] = useState("");
  const [quantity, setQuantity] = useState(1);
  const [discount, setDiscount] = useState(0);
  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});
  const [calculationResults, setCalculationResults] = useState<any>(null);
  const [editableBOMItems, setEditableBOMItems] = useState<any[]>([]);

  // 제품 유형 필터 (기본값: FG - 제품)
  const [selectedProductType, setSelectedProductType] = useState<string>("FG");
  const [selectedCategory, setSelectedCategory] = useState<string>("ALL");

  // 제품구성 설정 상태
  const [selectedModel, setSelectedModel] = useState("");
  const [floors, setFloors] = useState(1);
  const [symbol, setSymbol] = useState("");
  const [bodyType, setBodyType] = useState("");
  const [installType, setInstallType] = useState("");
  const [openWidth, setOpenWidth] = useState(0);
  const [openHeight, setOpenHeight] = useState(0);
  const [productWidth, setProductWidth] = useState(0);
  const [productHeight, setProductHeight] = useState(0);
  const [selectedBody, setSelectedBody] = useState("");
  const [selectedBending, setSelectedBending] = useState("");
  const [calculatedPrice, setCalculatedPrice] = useState(0);

  // 제품 유형 옵션
  const productTypeOptions = [
    { value: "ALL", label: "전체 품목" },
    { value: "FG", label: "제품 (FG)" },
    { value: "PT", label: "부품 (PT)" },
    { value: "SM", label: "부자재 (SM)" },
    { value: "RM", label: "원자재 (RM)" },
    { value: "CS", label: "소모품 (CS)" },
  ];

  // 제품 카테고리 옵션 (제품인 경우에만)
  const categoryOptions = [
    { value: "ALL", label: "전체 카테고리" },
    { value: "SCREEN", label: "스크린" },
    { value: "STEEL", label: "철재" },
  ];

  // 제품 유형 및 카테고리에 따라 필터링된 품목 목록
  const filteredProducts = itemMasters.filter(item => {
    // 선택된 제품 유형 필터
    if (selectedProductType !== "ALL" && item.itemType !== selectedProductType) {
      return false;
    }
    
    // 선택된 카테고리 필터 (제품인 경우에만 적용)
    if (selectedCategory !== "ALL" && item.itemType === "FG") {
      if (item.productCategory !== selectedCategory) {
        return false;
      }
    }
    
    return true;
  });

  const products = [
    { code: "PRO-2024-001", name: "스마트 센서 모듈 A", price: 150000 },
    { code: "PRO-2024-002", name: "프리미엄 컨트롤러", price: 350000 },
    { code: "PRO-2024-008", name: "산업용 모터 드라이버", price: 280000 }
  ];

  // 모델 목록
  const models = [
    { code: "KWE01", name: "KWE01 - 표준형" },
    { code: "KQTS01", name: "KQTS01 - 프리미엄" },
    { code: "KQSO1", name: "KQSO1 - 특수형" },
    { code: "KWE02", name: "KWE02 - 고급형" }
  ];

  // 본체 종류
  const bodyTypes = [
    { code: "BODY-STD", name: "표준 본체", basePrice: 50000 },
    { code: "BODY-PRE", name: "프리미엄 본체", basePrice: 80000 },
    { code: "BODY-SPC", name: "특수 본체", basePrice: 120000 }
  ];

  // 절곡물 종류
  const bendingTypes = [
    { code: "BEND-A", name: "절곡물 A형", pricePerM2: 15000 },
    { code: "BEND-B", name: "절곡물 B형", pricePerM2: 20000 },
    { code: "BEND-C", name: "절곡물 C형", pricePerM2: 25000 }
  ];

  // 설치 유형
  const installTypes = [
    { code: "WALL", name: "벽 설치형" },
    { code: "CEILING", name: "천장 설치형" },
    { code: "FLOOR", name: "바닥 설치형" },
    { code: "EMBEDDED", name: "매립형" }
  ];

  const addQuoteItem = () => {
    if (!selectedProduct) return;
    
    // DataContext의 품목 데이터에서 찾기
    const product = itemMasters.find(p => p.itemCode === selectedProduct);
    if (!product) return;

    // 판매가 또는 기본 가격 사용
    const unitPrice = product.salesPrice || 0;
    const discountAmount = unitPrice * (discount / 100);
    const finalUnitPrice = unitPrice - discountAmount;
    const total = finalUnitPrice * quantity;

    const newItem: QuoteItem = {
      id: Date.now().toString(),
      productCode: product.itemCode,
      productName: product.itemName,
      quantity: quantity,
      unitPrice: unitPrice,
      discount: discount,
      total: total
    };

    setQuoteItems([...quoteItems, newItem]);
    setSelectedProduct("");
    setQuantity(1);
    setDiscount(0);
  };

  // 제품 유형 변경 시 선택된 제품 초기화
  const handleProductTypeChange = (value: string) => {
    setSelectedProductType(value);
    setSelectedProduct(""); // 선택 초기화
  };

  // 카테고리 변경 시 선택된 제품 초기화
  const handleCategoryChange = (value: string) => {
    setSelectedCategory(value);
    setSelectedProduct(""); // 선택 초기화
  };

  const removeQuoteItem = (id: string) => {
    setQuoteItems(quoteItems.filter(item => item.id !== id));
  };

  const subtotal = quoteItems.reduce((sum, item) => sum + item.total, 0);
  const vat = subtotal * 0.1;
  const total = subtotal + vat;

  const avgDiscountRate = quoteItems.length > 0
    ? quoteItems.reduce((sum, item) => sum + item.discount, 0) / quoteItems.length
    : 0;

  // 제작 사이즈 계산 (mm 단위)
  const productSize = productWidth && productHeight 
    ? `${productWidth} x ${productHeight}` 
    : "";

  // 단가 자동 계산 함수
  const calculatePrice = () => {
    if (!selectedBody || !selectedBending || !productWidth || !productHeight) {
      setCalculatedPrice(0);
      return;
    }

    // 본체 가격
    const bodyPrice = bodyTypes.find(b => b.code === selectedBody)?.basePrice || 0;

    // 절곡물 가격 (면적 기준: m² 단위로 변환)
    const areaM2 = (productWidth / 1000) * (productHeight / 1000);
    const bendingPrice = (bendingTypes.find(b => b.code === selectedBending)?.pricePerM2 || 0) * areaM2;

    // 층수에 따른 추가 비용 (2층부터 층당 10% 추가)
    const floorMultiplier = 1 + ((floors - 1) * 0.1);

    // 총 단가 계산
    const totalPrice = (bodyPrice + bendingPrice) * floorMultiplier;
    setCalculatedPrice(Math.round(totalPrice));
  };

  // 제품 구성 변경 시 단가 재계산
  const handleConfigChange = () => {
    calculatePrice();
  };

  const validateForm = () => {
    const errors: Record<string, string> = {};
    
    // 필수 항목 체크
    if (!customerName.trim()) {
      errors.customerName = "고객사명을 입력하세요.";
    }
    if (!projectName.trim()) {
      errors.projectName = "프로젝트명을 입력하세요.";
    }
    
    // BOM 항목이 있으면 품목 체크 생략, 없으면 품목 필수
    if (editableBOMItems.length === 0 && quoteItems.length === 0) {
      errors.quoteItems = "품목을 추가하거나 자동 산출을 실행하세요.";
    }
    
    setValidationErrors(errors);
    
    // 에러가 있으면 첫 번째 에러 메시지를 toast로 표시
    if (Object.keys(errors).length > 0) {
      const firstError = Object.values(errors)[0];
      toast.error(firstError);
    }
    
    return Object.keys(errors).length === 0;
  };

  const handleSaveQuote = () => {
    console.log("💾 저장 버튼 클릭됨");
    console.log("📋 현재 상태:", { customerName, projectName, quoteItemsCount: quoteItems.length });
    
    if (!validateForm()) {
      toast.error("필수 항목을 모두 입력해주세요.");
      console.log("❌ 유효성 검사 실패:", validationErrors);
      return;
    }
    
    // 견적 번호 생성
    const today = new Date();
    const year = today.getFullYear();
    const quoteNumber = `Q-${year}-${String(quotes.length + 1).padStart(3, '0')}`;
    
    const newQuote = {
      id: `quote-${Date.now()}`,
      quoteNumber,
      customerName,
      projectName,
      quoteDate: today.toISOString().split('T')[0],
      validUntil: new Date(today.setMonth(today.getMonth() + 1)).toISOString().split('T')[0],
      totalAmount: total,
      status: 'draft' as const,
      currentRevision: 0,
      isFinal: false,
      createdAt: new Date().toISOString(),
      revisions: [],
      sendHistory: []
    };
    
    console.log("✅ 저장할 견적:", newQuote);
    console.log("📊 현재 견적 수:", quotes.length);
    
    addQuote(newQuote);
    
    console.log("✅ addQuote 호출 완료");
    toast.success("견적이 성공적으로 저장되었습니다.");
    
    // 폼 초기화
    setCustomerName("");
    setProjectName("");
    setQuoteItems([]);
    setValidationErrors({});
    setCalculationResults(null);
    
    // 저장 후 목록으로 이동
    setTimeout(() => {
      if (onBack) {
        console.log("🔙 목록으로 이동");
        onBack();
      }
    }, 500); // 토스트 메시지를 보여준 후 이동
  };

  // 자동 산출 완료 핸들러
  const handleCalculationComplete = (results: any) => {
    console.log("🎯 자동 산출 완료 - BOM 항목:", results.bomItems?.length, "개");
    
    setCalculationResults(results);
    
    // BOM 항목이 있으면 편집 가능한 상태로 설정
    if (results.bomItems && Array.isArray(results.bomItems)) {
      setEditableBOMItems(results.bomItems);
      toast.success(`자동 산출 완료: ${results.bomItems.length}개 BOM 항목이 생성되었습니다.`);
    } else {
      console.log("❌ BOM 항목이 없습니다");
      toast.warning("BOM 항목이 없습니다.");
    }
  };

  // BOM 항목 변경 핸들러
  const handleBOMItemsChange = (items: any[]) => {
    setEditableBOMItems(items);
    console.log("📝 BOM 항목 변경됨:", items);
  };

  // BOM 임시저장 핸들러
  const handleTempSave = () => {
    if (editableBOMItems.length === 0) {
      toast.error("저장할 BOM 항목이 없습니다.");
      return;
    }
    
    // localStorage에 임시 저장
    const tempData = {
      customerName,
      projectName,
      bomItems: editableBOMItems,
      timestamp: new Date().toISOString()
    };
    
    localStorage.setItem('quote-temp-save', JSON.stringify(tempData));
    toast.success("BOM 항목이 임시저장되었습니다.");
    console.log("💾 임시저장 완료:", tempData);
  };

  // BOM을 견적으로 저장 핸들러
  const handleSaveBOMAsQuote = () => {
    console.log("💾 BOM을 견적으로 저장 버튼 클릭됨");
    
    if (!customerName || !projectName) {
      toast.error("고객사명과 프로젝트명을 입력해주세요.");
      return;
    }
    
    if (editableBOMItems.length === 0) {
      toast.error("저장할 BOM 항목이 없습니다.");
      return;
    }
    
    // BOM 항목을 견적 품목으로 변환
    const bomQuoteItems: QuoteItem[] = editableBOMItems.map((item: any) => ({
      id: item.id || `bom-${Date.now()}-${Math.random()}`,
      productCode: item.itemCode,
      productName: item.itemName,
      quantity: item.calculatedQuantity,
      unitPrice: item.unitPrice,
      discount: 0,
      total: item.totalPrice
    }));
    
    // 기존 품목에 추가
    setQuoteItems(prev => [...prev, ...bomQuoteItems]);
    
    // 견적 번호 생성
    const today = new Date();
    const year = today.getFullYear();
    const quoteNumber = `Q-${year}-${String(quotes.length + 1).padStart(3, '0')}`;
    
    // 총 금액 계산
    const bomTotal = editableBOMItems.reduce((sum: number, item: any) => sum + item.totalPrice, 0);
    
    const newQuote = {
      id: `quote-${Date.now()}`,
      quoteNumber,
      customerName,
      projectName,
      quoteDate: today.toISOString().split('T')[0],
      validUntil: new Date(today.setMonth(today.getMonth() + 1)).toISOString().split('T')[0],
      totalAmount: bomTotal,
      status: 'draft' as const,
      currentRevision: 0,
      isFinal: false,
      createdAt: new Date().toISOString(),
      revisions: [],
      sendHistory: [],
      // BOM 정보도 저장
      bomCalculations: editableBOMItems
    };
    
    console.log("✅ BOM 기반 견적 저장:", newQuote);
    
    addQuote(newQuote);
    toast.success(`견적이 성공적으로 저장되었습니다 (${editableBOMItems.length}개 품목)`);
    
    // localStorage 임시저장 데이터 삭제
    localStorage.removeItem('quote-temp-save');
    
    // 저장 후 목록으로 이동
    setTimeout(() => {
      if (onBack) {
        console.log("🔙 목록으로 이동");
        onBack();
      }
    }, 800);
  };

  return (
    <div className="p-6 space-y-6">
      {/* 헤더 */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold text-foreground flex items-center gap-3">
            <div className="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center">
              <FileText className="h-6 w-6 text-indigo-600" />
            </div>
            견적 시뮬레이션
          </h1>
          <p className="text-muted-foreground mt-1">실시간 견적서 작성 및 시뮬레이션</p>
        </div>
        <div className="flex gap-2">
          {onBack && (
            <Button variant="outline" onClick={onBack}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              목록으로
            </Button>
          )}
          {/* BOM 항목이 있을 때만 임시저장/견적저장 버튼 표시 */}
          {editableBOMItems.length > 0 ? (
            <>
              <Button variant="outline" onClick={handleTempSave}>
                <Save className="h-4 w-4 mr-2" />
                임시저장
              </Button>
              <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveBOMAsQuote}>
                <Save className="h-4 w-4 mr-2" />
                견적으로 저장
              </Button>
            </>
          ) : (
            <Button variant="outline" onClick={handleSaveQuote}>
              <Save className="h-4 w-4 mr-2" />
              견적 저장
            </Button>
          )}
          <Button variant="outline">
            <Download className="h-4 w-4 mr-2" />
            PDF 다운로드
          </Button>
          <Button className="bg-indigo-600 hover:bg-indigo-700">
            <Send className="h-4 w-4 mr-2" />
            견적서 발송
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 왼쪽: 견적 작성 폼 */}
        <div className="lg:col-span-2 space-y-6">
          {/* 고객 정보 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">고객 정보</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>고객사명 *</Label>
                  <Input
                    placeholder="고객사명을 입력하세요"
                    value={customerName}
                    onChange={(e) => setCustomerName(e.target.value)}
                  />
                  {validationErrors.customerName && (
                    <p className="text-red-500 text-sm mt-1">
                      {validationErrors.customerName}
                    </p>
                  )}
                </div>
                <div className="space-y-2">
                  <Label>프로젝트명 *</Label>
                  <Input
                    placeholder="프로젝트명을 입력하세요"
                    value={projectName}
                    onChange={(e) => setProjectName(e.target.value)}
                  />
                  {validationErrors.projectName && (
                    <p className="text-red-500 text-sm mt-1">
                      {validationErrors.projectName}
                    </p>
                  )}
                </div>
                <div className="space-y-2">
                  <Label>고객 구분</Label>
                  <Select value={customerType} onValueChange={setCustomerType}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="new">신규 고객</SelectItem>
                      <SelectItem value="regular">기존 고객 (일반)</SelectItem>
                      <SelectItem value="vip">기존 고객 (VIP)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>담당자</Label>
                  <Input placeholder="담당자명" />
                </div>
                <div className="space-y-2">
                  <Label>연락처</Label>
                  <Input placeholder="연락처" />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 제품구성 설정 */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-lg">제품구성 설정</CardTitle>
                {calculatedPrice > 0 && (
                  <Badge className="bg-green-600">
                    <Calculator className="h-3 w-3 mr-1" />
                    계산된 단가: ₩{calculatedPrice.toLocaleString()}
                  </Badge>
                )}
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 1행: 모델, 층수, 부호 */}
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label>모델 선택 *</Label>
                  <Select value={selectedModel} onValueChange={setSelectedModel}>
                    <SelectTrigger>
                      <SelectValue placeholder="모델 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {models.map((model) => (
                        <SelectItem key={model.code} value={model.code}>
                          {model.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>층수 *</Label>
                  <Input
                    type="number"
                    min="1"
                    value={floors}
                    onChange={(e) => {
                      setFloors(parseInt(e.target.value) || 1);
                      handleConfigChange();
                    }}
                    placeholder="층수 입력"
                  />
                </div>
                <div className="space-y-2">
                  <Label>부호</Label>
                  <Input
                    value={symbol}
                    onChange={(e) => setSymbol(e.target.value)}
                    placeholder="부호 입력"
                  />
                </div>
              </div>

              {/* 2행: 본체종류, 설치유형 */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>본체종류 선택 *</Label>
                  <Select 
                    value={selectedBody} 
                    onValueChange={(value) => {
                      setSelectedBody(value);
                      setTimeout(handleConfigChange, 0);
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="본체종류 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {bodyTypes.map((body) => (
                        <SelectItem key={body.code} value={body.code}>
                          {body.name} (기본가: ₩{body.basePrice.toLocaleString()})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>설치유형 선택 *</Label>
                  <Select value={installType} onValueChange={setInstallType}>
                    <SelectTrigger>
                      <SelectValue placeholder="설치유형 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {installTypes.map((install) => (
                        <SelectItem key={install.code} value={install.code}>
                          {install.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 3행: 오픈사이즈 */}
              <div className="space-y-2">
                <Label>오픈사이즈 (mm)</Label>
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-muted-foreground w-12">가로</span>
                    <Input
                      type="number"
                      min="0"
                      value={openWidth || ""}
                      onChange={(e) => setOpenWidth(parseInt(e.target.value) || 0)}
                      placeholder="가로"
                    />
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-muted-foreground w-12">세로</span>
                    <Input
                      type="number"
                      min="0"
                      value={openHeight || ""}
                      onChange={(e) => setOpenHeight(parseInt(e.target.value) || 0)}
                      placeholder="세로"
                    />
                  </div>
                </div>
                {openWidth > 0 && openHeight > 0 && (
                  <p className="text-sm text-muted-foreground mt-1">
                    오픈사이즈: {openWidth} x {openHeight} mm
                  </p>
                )}
              </div>

              {/* 4행: 제작 치수 */}
              <div className="space-y-2">
                <Label>제작 치수 (mm) *</Label>
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-muted-foreground w-12">가로</span>
                    <Input
                      type="number"
                      min="0"
                      value={productWidth || ""}
                      onChange={(e) => {
                        setProductWidth(parseInt(e.target.value) || 0);
                        setTimeout(handleConfigChange, 0);
                      }}
                      placeholder="가로"
                    />
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-muted-foreground w-12">높이</span>
                    <Input
                      type="number"
                      min="0"
                      value={productHeight || ""}
                      onChange={(e) => {
                        setProductHeight(parseInt(e.target.value) || 0);
                        setTimeout(handleConfigChange, 0);
                      }}
                      placeholder="높이"
                    />
                  </div>
                </div>
              </div>

              {/* 5행: 절곡물 선택 */}
              <div className="space-y-2">
                <Label>절곡물 선택 *</Label>
                <Select 
                  value={selectedBending} 
                  onValueChange={(value) => {
                    setSelectedBending(value);
                    setTimeout(handleConfigChange, 0);
                  }}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="절곡물 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {bendingTypes.map((bending) => (
                      <SelectItem key={bending.code} value={bending.code}>
                        {bending.name} (₩{bending.pricePerM2.toLocaleString()}/m²)
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 제작 사이즈 및 계산 결과 */}
              {productSize && (
                <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <span className="text-sm">제작 사이즈:</span>
                      <span className="font-semibold text-blue-900">{productSize} mm</span>
                    </div>
                    {calculatedPrice > 0 && (
                      <>
                        <div className="flex items-center justify-between">
                          <span className="text-sm">제작 면적:</span>
                          <span className="text-sm">{((productWidth / 1000) * (productHeight / 1000)).toFixed(2)} m²</span>
                        </div>
                        <div className="flex items-center justify-between pt-2 border-t border-blue-300">
                          <span className="font-semibold">계산된 단가:</span>
                          <span className="text-lg font-bold text-blue-900">₩{calculatedPrice.toLocaleString()}</span>
                        </div>
                        <p className="text-xs text-muted-foreground mt-2">
                          * 본체 + 절곡물(면적 기준) + 층수 추가비용이 적용되었습니다.
                        </p>
                      </>
                    )}
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 편집 가능한 BOM 결과 */}
          {editableBOMItems.length > 0 && (
            <div className="border rounded-lg p-4 bg-gray-50 mb-4">
              <h3 className="font-medium mb-2 text-gray-700">BOM 기반 자재 산출 결과</h3>
              <p className="text-sm text-gray-600">
                {editableBOMItems.length}개의 BOM 항목이 자동 산출되었습니다.
                <br />
                AutoCalculationSimulator에서 확인하고 편집할 수 있습니다.
              </p>
            </div>
          )}

          {/* 견적 품목 목록 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">견적 품목 ({quoteItems.length}개)</CardTitle>
            </CardHeader>
            <CardContent>
              {/* 품목 추가 폼 */}
              <div className="p-4 bg-gray-50 rounded-lg border border-gray-200 mb-4">
                <div className="grid grid-cols-1 lg:grid-cols-4 gap-3">
                  <div className="lg:col-span-2">
                    <Label className="text-xs mb-1 block">품목 선택</Label>
                    <Select value={selectedProduct} onValueChange={setSelectedProduct}>
                      <SelectTrigger className="h-9">
                        <SelectValue placeholder="품목을 선택하세요" />
                      </SelectTrigger>
                      <SelectContent>
                        {filteredProducts.map((product) => (
                          <SelectItem key={product.id} value={product.itemCode}>
                            [{product.itemCode}] {product.itemName}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label className="text-xs mb-1 block">수량</Label>
                    <Input
                      type="number"
                      min="1"
                      value={quantity}
                      onChange={(e) => setQuantity(parseInt(e.target.value) || 1)}
                      placeholder="수량"
                      className="h-9"
                    />
                  </div>
                  <div>
                    <Label className="text-xs mb-1 block">할인(%)</Label>
                    <div className="flex gap-2">
                      <Input
                        type="number"
                        min="0"
                        max="100"
                        value={discount}
                        onChange={(e) => setDiscount(parseInt(e.target.value) || 0)}
                        placeholder="0"
                        className="h-9 flex-1"
                      />
                      <Button 
                        onClick={addQuoteItem} 
                        disabled={!selectedProduct}
                        className="h-9"
                        size="sm"
                      >
                        <Plus className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              </div>

              {validationErrors.quoteItems && (
                <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2">
                  <AlertCircle className="h-4 w-4 text-red-600" />
                  <p className="text-red-600 text-sm">
                    {validationErrors.quoteItems}
                  </p>
                </div>
              )}

              {quoteItems.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  <Package className="h-12 w-12 mx-auto mb-3 opacity-50" />
                  <p>품목을 추가해주세요</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {quoteItems.map((item) => (
                    <div key={item.id} className="p-4 bg-muted/30 rounded-lg border">
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="font-medium">{item.productName}</span>
                            <Badge variant="outline" className="text-xs">
                              {item.productCode}
                            </Badge>
                          </div>
                          <div className="text-sm text-muted-foreground">
                            단가: ₩{item.unitPrice.toLocaleString()} | 
                            수량: {item.quantity}개 |
                            할인: {item.discount}%
                          </div>
                        </div>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => removeQuoteItem(item.id)}
                        >
                          <Trash2 className="h-4 w-4 text-red-500" />
                        </Button>
                      </div>
                      <div className="flex justify-between items-center pt-3 border-t">
                        <span className="text-sm text-muted-foreground">합계</span>
                        <span className="text-lg font-bold text-indigo-600">
                          ₩{item.total.toLocaleString()}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* 오른쪽: 견적 요약 */}
        <div className="space-y-6">
          {/* 금액 요약 */}
          <Card className="border-2 border-indigo-200">
            <CardHeader className="bg-gradient-to-r from-indigo-50 to-purple-50">
              <CardTitle className="text-lg flex items-center gap-2">
                <Calculator className="h-5 w-5 text-indigo-600" />
                견적 금액
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4 pt-6">
              <div className="space-y-3">
                <div className="flex justify-between items-center pb-3 border-b">
                  <span className="text-muted-foreground">품목 수</span>
                  <span className="font-medium">{quoteItems.length}개</span>
                </div>
                <div className="flex justify-between items-center pb-3 border-b">
                  <span className="text-muted-foreground">총 수량</span>
                  <span className="font-medium">
                    {quoteItems.reduce((sum, item) => sum + item.quantity, 0)}개
                  </span>
                </div>
                <div className="flex justify-between items-center pb-3 border-b">
                  <span className="text-muted-foreground">평균 할인율</span>
                  <span className="font-medium text-orange-600">
                    {avgDiscountRate.toFixed(1)}%
                  </span>
                </div>
                <div className="flex justify-between items-center pb-3 border-b">
                  <span className="text-muted-foreground">소계</span>
                  <span className="font-medium">₩{subtotal.toLocaleString()}</span>
                </div>
                <div className="flex justify-between items-center pb-3 border-b">
                  <span className="text-muted-foreground">부가세 (10%)</span>
                  <span className="font-medium">₩{vat.toLocaleString()}</span>
                </div>
                <div className="flex justify-between items-center pt-2">
                  <span className="text-lg font-bold">총 견적 금액</span>
                  <span className="text-2xl font-bold text-indigo-600">
                    ₩{total.toLocaleString()}
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 통계 카드 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-sm">견적 통계</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
                <div className="flex items-center gap-2">
                  <DollarSign className="h-4 w-4 text-blue-600" />
                  <span className="text-sm">평균 단가</span>
                </div>
                <span className="font-bold text-blue-600">
                  ₩{quoteItems.length > 0 ? Math.round(subtotal / quoteItems.reduce((sum, item) => sum + item.quantity, 0) || 0).toLocaleString() : 0}
                </span>
              </div>
              <div className="flex items-center justify-between p-3 bg-purple-50 rounded-lg">
                <div className="flex items-center gap-2">
                  <Percent className="h-4 w-4 text-purple-600" />
                  <span className="text-sm">총 할인액</span>
                </div>
                <span className="font-bold text-purple-600">
                  ₩{Math.round(quoteItems.reduce((sum, item) => sum + (item.unitPrice * item.quantity * item.discount / 100), 0)).toLocaleString()}
                </span>
              </div>
              <div className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                <div className="flex items-center gap-2">
                  <TrendingUp className="h-4 w-4 text-green-600" />
                  <span className="text-sm">예상 마진율</span>
                </div>
                <span className="font-bold text-green-600">
                  35.2%
                </span>
              </div>
            </CardContent>
          </Card>

          {/* 빠른 템플릿 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-sm">빠른 템플릿</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <Button variant="outline" className="w-full justify-start" size="sm">
                <FileText className="h-4 w-4 mr-2" />
                표준 견적서 (A)
              </Button>
              <Button variant="outline" className="w-full justify-start" size="sm">
                <FileText className="h-4 w-4 mr-2" />
                대량 구매 견적서 (B)
              </Button>
              <Button variant="outline" className="w-full justify-start" size="sm">
                <FileText className="h-4 w-4 mr-2" />
                VIP 고객 견적서 (C)
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* 자동 견적 산출 섹션 */}
      <div className="mt-8">
        <AutoCalculationWithTabs 
          showSampleButton={false} 
          showResults={true}
          onCalculationComplete={handleCalculationComplete} 
        />
      </div>
    </div>
  );
}