import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Textarea } from "./ui/textarea";
import { Badge } from "./ui/badge";
import { ArrowLeft, Save, Play, Calculator } from "lucide-react";
import { toast } from "sonner@2.0.3";
import { useData } from "./contexts/DataContext";

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

export function QuoteCreation({ onBack, onClose }: QuoteCreationProps = {}) {
  const { formulaRules, resetAllData } = useData();
  
  // 고객 정보
  const [customerName, setCustomerName] = useState("");
  const [customerType, setCustomerType] = useState("");
  const [contactPerson, setContactPerson] = useState("");
  const [contactNumber, setContactNumber] = useState("");

  // 입력 상태 (자동 계산용)
  const [inputs, setInputs] = useState({
    floors: 1,
    sign: '+',
    w0: 0,
    h0: 0,
    guideRailItem: '알루미늄',
    power: '220V 단상',
    controller: '기본형',
    quantity: 1,
    category: '스크린' as '스크린' | '철재',
    shaft: '4"'
  });
  
  // 계산 결과
  const [calculationResults, setCalculationResults] = useState<any>(null);

  // 자동 계산 실행
  const handleAutoCalculation = () => {
    if (!inputs.w0 || !inputs.h0) {
      toast.error("오픈사이즈를 입력해주세요.");
      return;
    }

    const { floors, w0, h0, category, shaft } = inputs;

    // 기본 계산
    const w1 = w0; // 제작사이즈 폭 = 오픈사이즈 폭
    const h1 = h0; // 제작사이즈 높이 = 오픈사이즈 높이
    const area = (w1 * h1) / 1000000; // 면적 (m²)
    
    // 중량 계산 (면적 기반, 간단한 예시)
    let weight = area * 25; // kg (스크린 기준)
    if (category === '철재') {
      weight = area * 35; // kg (철재는 더 무거움)
    }

    const results: any = {
      basic: {
        quantity: floors,
        w1,
        h1,
        area,
        weight,
        category,
        shaft
      },
      items: {}
    };

    // 모터 선택 (중량 기준)
    const motorRules = formulaRules.filter(r => 
      r.ruleCode.startsWith(`MOTOR-${category === '스크린' ? 'SCREEN' : 'STEEL'}`) && 
      r.status === 'active'
    );

    for (const rule of motorRules) {
      if (rule.ranges) {
        const matchedRange = rule.ranges.find(r => weight >= r.minValue && weight <= r.maxValue);
        if (matchedRange) {
          results.items.motor = matchedRange.result;
          break;
        }
      }
    }

    // 가이드레일 제작길이(G) 계산
    const grLengthRule = formulaRules.find(r => r.ruleCode === 'GR-LENGTH' && r.status === 'active');
    let guideRailLength = 0;
    if (grLengthRule && grLengthRule.formula) {
      try {
        guideRailLength = evaluateFormula(grLengthRule.formula, { W1: w1, H1: h1, H0: h0, area, weight });
        results.items.guideRailLength = guideRailLength;
      } catch (e) {
        results.items.guideRailLength = '계산오류';
      }
    }

    // 가이드레일 자재 선택 (제작길이 G 기준)
    if (guideRailLength > 0) {
      const grMaterialRules = formulaRules.filter(r => r.ruleCode.startsWith('GR-MATERIAL') && r.status === 'active');
      for (const rule of grMaterialRules) {
        if (rule.ranges) {
          const matchedRange = rule.ranges.find(r => guideRailLength > r.minValue && guideRailLength <= r.maxValue);
          if (matchedRange) {
            results.items.guideRailMaterial = matchedRange.result;
            break;
          }
        }
      }
    }

    // 가이드레일 품목 (중량 기준)
    const grTypeRule = formulaRules.find(r => r.ruleCode === 'GUIDE-RAIL-TYPE' && r.status === 'active');
    if (grTypeRule && grTypeRule.ranges) {
      const matchedRange = grTypeRule.ranges.find(r => weight >= r.minValue && weight <= r.maxValue);
      results.items.guideRailType = matchedRange ? matchedRange.result : '범위 초과';
    }
    
    // 연기차단재 수량 (제품 카테고리별)
    const smokeBarrierQtyCode = `SMOKE-BARRIER-QTY-${category === '스크린' ? 'SCREEN' : 'STEEL'}`;
    const smokeBarrierQtyRule = formulaRules.find(r => r.ruleCode === smokeBarrierQtyCode && r.status === 'active');
    if (smokeBarrierQtyRule && smokeBarrierQtyRule.fixedValue !== undefined) {
      const qtyPer1Ryang = smokeBarrierQtyRule.fixedValue;
      const totalQty = qtyPer1Ryang * 2; // 1SET = 2량
      results.items.smokeBarrierQty = `${totalQty}개 (1량당 ${qtyPer1Ryang}개)`;
    }
    
    // 연기차단재 재단 길이 (가이드레일과 동일)
    if (guideRailLength > 0) {
      results.items.smokeBarrierLength = guideRailLength;
    }
    
    // 케이스(셔터박스) 제작사이즈 S 계산 (W1 사용)
    const caseSize = w1;
    
    // 케이스판재 자재 선택 (제작사이즈 S 기준)
    if (caseSize > 0) {
      const caseMaterialRules = formulaRules.filter(r => r.ruleCode.startsWith('CASE-MATERIAL') && r.status === 'active');
      for (const rule of caseMaterialRules) {
        if (rule.ranges) {
          const matchedRange = rule.ranges.find(r => caseSize > r.minValue && caseSize <= r.maxValue);
          if (matchedRange) {
            results.items.caseMaterial = `${matchedRange.result} (${matchedRange.quantity}개)`;
            break;
          }
        }
      }
    }
    
    // 마구리 수량
    const marguriRule = formulaRules.find(r => r.ruleCode === 'MARGURI-QTY' && r.status === 'active');
    if (marguriRule && marguriRule.fixedValue !== undefined) {
      results.items.marguri = `${marguriRule.fixedValue}EA (1SET)`;
    }
    
    // 케이스용 연기차단재 수량
    const caseSmokeBarrierRule = formulaRules.find(r => r.ruleCode === 'CASE-SMOKE-BARRIER-QTY' && r.status === 'active');
    if (caseSmokeBarrierRule && caseSmokeBarrierRule.formula) {
      try {
        const qty = evaluateFormula(caseSmokeBarrierRule.formula, { S: caseSize });
        results.items.caseSmokeBarrier = `${qty}개 (2줄 삽입)`;
      } catch (e) {
        results.items.caseSmokeBarrier = '계산오류';
      }
    }
    
    // 상부덮개 수량
    const topCoverRule = formulaRules.find(r => r.ruleCode === 'TOP-COVER-QTY' && r.status === 'active');
    if (topCoverRule && topCoverRule.formula) {
      try {
        const qty = evaluateFormula(topCoverRule.formula, { S: caseSize });
        results.items.topCover = `${qty}개`;
      } catch (e) {
        results.items.topCover = '계산오류';
      }
    }

    // 감기샤프트 길이
    const shaftRule = formulaRules.find(r => r.ruleCode === 'WINDING-SHAFT' && r.status === 'active');
    if (shaftRule && shaftRule.formula) {
      try {
        const shaftLength = evaluateFormula(shaftRule.formula, { W1: w1, H1: h1, area, weight });
        results.items.windingShaft = parseFloat(shaftLength.toFixed(2));
      } catch (e) {
        results.items.windingShaft = '계산오류';
      }
    }

    // 하단바 길이
    const bottomBarRule = formulaRules.find(r => r.ruleCode === 'BOTTOM-BAR' && r.status === 'active');
    if (bottomBarRule && bottomBarRule.formula) {
      try {
        const bottomBarLength = evaluateFormula(bottomBarRule.formula, { W1: w1, H1: h1, area, weight });
        results.items.bottomBar = parseFloat(bottomBarLength.toFixed(2));
      } catch (e) {
        results.items.bottomBar = '계산오류';
      }
    }

    setCalculationResults(results);
    toast.success("부품구성표(BOM)가 자동 계산되었습니다.");
  };

  // 간단한 수식 평가 함수
  const evaluateFormula = (formula: string, vars: Record<string, number>): number => {
    let expr = formula;
    
    // 변수 치환
    Object.keys(vars).forEach(key => {
      const regex = new RegExp(`\\b${key}\\b`, 'g');
      expr = expr.replace(regex, vars[key].toString());
    });

    // 함수 치환
    expr = expr.replace(/CEIL\(([^)]+)\)/g, (_, p1) => {
      const val = eval(p1);
      return Math.ceil(val).toString();
    });
    expr = expr.replace(/FLOOR\(([^)]+)\)/g, (_, p1) => {
      const val = eval(p1);
      return Math.floor(val).toString();
    });
    expr = expr.replace(/ROUND\(([^)]+)\)/g, (_, p1) => {
      const val = eval(p1);
      return Math.round(val).toString();
    });

    // 수식 평가
    try {
      return eval(expr);
    } catch (error) {
      console.error('Formula evaluation error:', error);
      throw error;
    }
  };

  // 저장
  const handleSave = () => {
    if (!customerName) {
      toast.error("고객사명을 입력해주세요.");
      return;
    }

    if (!calculationResults) {
      toast.error("부품구성표(BOM)를 먼저 계산해주세요.");
      return;
    }

    const quoteData = {
      customerInfo: {
        customerName,
        customerType,
        contactPerson,
        contactNumber
      },
      inputs,
      calculationResults
    };

    console.log("견적 데이터:", quoteData);
    toast.success("견적이 저장되었습니다.");
    
    if (onClose) {
      onClose();
    } else if (onBack) {
      onBack();
    }
  };

  return (
    <div className="p-6 space-y-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          {onBack && (
            <Button variant="outline" size="sm" onClick={onBack}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              목록으로
            </Button>
          )}
          <div>
            <h1 className="text-2xl">견적서 작성</h1>
            <p className="text-sm text-muted-foreground mt-1">
              오픈사이즈 입력 시 부품구성표(BOM)가 자동 계산됩니다.
            </p>
          </div>
        </div>
        <Button onClick={handleSave} size="lg">
          <Save className="w-4 h-4 mr-2" />
          저장
        </Button>
      </div>

      {/* 고객 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>고객 정보</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 htmlFor="customerName">고객사명 *</Label>
              <Input
                id="customerName"
                placeholder="고객사명을 입력하세요"
                value={customerName}
                onChange={(e) => setCustomerName(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="customerType">고객 구분</Label>
              <Select value={customerType} onValueChange={setCustomerType}>
                <SelectTrigger>
                  <SelectValue placeholder="신규 고객" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="new">신규 고객</SelectItem>
                  <SelectItem value="existing">기존 고객</SelectItem>
                  <SelectItem value="vip">VIP 고객</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="contactPerson">담당자</Label>
              <Input
                id="contactPerson"
                placeholder="담당자명"
                value={contactPerson}
                onChange={(e) => setContactPerson(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="contactNumber">연락처</Label>
              <Input
                id="contactNumber"
                placeholder="연락처"
                value={contactNumber}
                onChange={(e) => setContactNumber(e.target.value)}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 부품구성표(BOM) 자동 산출 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Calculator className="h-5 w-5 text-blue-600" />
            부품구성표(BOM) 자동 산출
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <h3 className="font-medium mb-2">💡 사용 방법</h3>
            <p className="text-sm">
              층수, 부호, 오픈사이즈, 제품 카테고리, 샤프트를 입력하면 등록된 모든 산정 기준과 수식이 자동 적용되어
              모터, 케이스판재, 가이드레일, 연기차단재 등 모든 부자재가 자동 계산됩니다.
            </p>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div>
              <Label>층수</Label>
              <Input
                type="number"
                value={inputs.floors}
                onChange={(e) => setInputs({...inputs, floors: parseInt(e.target.value) || 1})}
                placeholder="1"
              />
            </div>
            
            <div>
              <Label>부호</Label>
              <Select value={inputs.sign} onValueChange={(v) => setInputs({...inputs, sign: v})}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="+">+</SelectItem>
                  <SelectItem value="-">-</SelectItem>
                  <SelectItem value="A">A</SelectItem>
                  <SelectItem value="B">B</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>오픈사이즈 W0 (mm)</Label>
              <Input
                type="number"
                value={inputs.w0}
                onChange={(e) => setInputs({...inputs, w0: parseFloat(e.target.value) || 0})}
                placeholder="예: 4000"
              />
            </div>
            
            <div>
              <Label>오픈사이즈 H0 (mm)</Label>
              <Input
                type="number"
                value={inputs.h0}
                onChange={(e) => setInputs({...inputs, h0: parseFloat(e.target.value) || 0})}
                placeholder="예: 2500"
              />
            </div>

            <div>
              <Label>제품 카테고리</Label>
              <Select value={inputs.category} onValueChange={(v: '스크린' | '철재') => setInputs({...inputs, category: v})}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="스크린">스크린</SelectItem>
                  <SelectItem value="철재">철재</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>샤프트 규격</Label>
              <Select value={inputs.shaft} onValueChange={(v) => setInputs({...inputs, shaft: v})}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value='4"'>4"</SelectItem>
                  <SelectItem value='5"'>5"</SelectItem>
                  <SelectItem value='6"'>6"</SelectItem>
                  <SelectItem value='8"'>8"</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>전원</Label>
              <Select value={inputs.power} onValueChange={(v) => setInputs({...inputs, power: v})}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="220V 단상">220V 단상</SelectItem>
                  <SelectItem value="220V 3상">220V 3상</SelectItem>
                  <SelectItem value="380V 3상">380V 3상</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>수량</Label>
              <Input
                type="number"
                value={inputs.quantity}
                onChange={(e) => setInputs({...inputs, quantity: parseInt(e.target.value) || 1})}
                placeholder="1"
              />
            </div>
          </div>

          <Button onClick={handleAutoCalculation} className="w-full" size="lg">
            <Play className="h-4 w-4 mr-2" />
            부품구성표(BOM) 자동 산출 실행
          </Button>

          {/* 결과 표시 */}
          {calculationResults && (
            <div className="mt-6 space-y-4">
              <div className="bg-blue-50 border-2 border-blue-300 rounded-lg p-4">
                <h3 className="font-medium mb-3">🎯 입력 정보 요약</h3>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  <div className="bg-white rounded-lg p-3">
                    <p className="text-xs text-gray-600 mb-1">층수 / 부호</p>
                    <p className="text-sm font-bold">{calculationResults.basic.quantity}층 / {inputs.sign}</p>
                  </div>
                  <div className="bg-white rounded-lg p-3">
                    <p className="text-xs text-gray-600 mb-1">제품 카테고리</p>
                    <p className="text-sm font-bold">{calculationResults.basic.category}</p>
                  </div>
                  <div className="bg-white rounded-lg p-3">
                    <p className="text-xs text-gray-600 mb-1">샤프트 규격</p>
                    <p className="text-sm font-bold">{calculationResults.basic.shaft}</p>
                  </div>
                  <div className="bg-white rounded-lg p-3">
                    <p className="text-xs text-gray-600 mb-1">전원 / 수량</p>
                    <p className="text-sm font-bold">{inputs.power} / {inputs.quantity}EA</p>
                  </div>
                </div>
              </div>

              <div className="bg-green-50 border-2 border-green-300 rounded-lg p-4">
                <h3 className="font-medium mb-3">📐 기본 산출 결과</h3>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  <div className="bg-white rounded-lg p-3">
                    <p className="text-xs text-gray-600 mb-1">제작사이즈 W1</p>
                    <p className="text-sm font-medium">{calculationResults.basic.w1.toFixed(0)} mm</p>
                  </div>
                  <div className="bg-white rounded-lg p-3">
                    <p className="text-xs text-gray-600 mb-1">제작사이즈 H1</p>
                    <p className="text-sm font-medium">{calculationResults.basic.h1.toFixed(0)} mm</p>
                  </div>
                  <div className="bg-white rounded-lg p-3">
                    <p className="text-xs text-gray-600 mb-1">면적</p>
                    <p className="text-sm font-medium">{calculationResults.basic.area.toFixed(3)} m²</p>
                  </div>
                  <div className="bg-orange-100 rounded-lg p-3 border-2 border-orange-400">
                    <p className="text-xs text-orange-700 mb-1 font-semibold">중량 (산출 기준)</p>
                    <p className="font-bold text-orange-900">{calculationResults.basic.weight.toFixed(2)} kg</p>
                  </div>
                </div>
              </div>

              <div className="bg-purple-50 border-2 border-purple-300 rounded-lg p-4">
                <h3 className="font-medium mb-3">🔧 부품구성표(BOM) - 자동 산출 결과</h3>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                  {calculationResults.items.motor && (
                    <div className="bg-gradient-to-r from-purple-100 to-pink-100 rounded-lg p-4 border-2 border-purple-400">
                      <p className="text-xs text-purple-700 mb-1 font-semibold">모터</p>
                      <p className="font-bold text-purple-900">{calculationResults.items.motor}</p>
                    </div>
                  )}
                  {calculationResults.items.guideRailLength !== undefined && (
                    <div className="bg-gradient-to-r from-blue-100 to-cyan-100 rounded-lg p-4 border-2 border-blue-400">
                      <p className="text-xs text-blue-700 mb-1 font-semibold">가이드레일 제작길이(G)</p>
                      <p className="font-bold text-blue-900">{calculationResults.items.guideRailLength} mm</p>
                    </div>
                  )}
                  {calculationResults.items.guideRailMaterial && (
                    <div className="bg-gradient-to-r from-green-100 to-emerald-100 rounded-lg p-4 border-2 border-green-400">
                      <p className="text-xs text-green-700 mb-1 font-semibold">가이드레일 자재</p>
                      <p className="font-bold text-green-900">{calculationResults.items.guideRailMaterial}</p>
                    </div>
                  )}
                  {calculationResults.items.guideRailType && (
                    <div className="bg-white rounded-lg p-3 border">
                      <p className="text-xs text-gray-600 mb-1">가이드레일 품목</p>
                      <p className="font-medium">{calculationResults.items.guideRailType}</p>
                    </div>
                  )}
                  {calculationResults.items.smokeBarrierQty && (
                    <div className="bg-gradient-to-r from-amber-100 to-yellow-100 rounded-lg p-4 border-2 border-amber-400">
                      <p className="text-xs text-amber-700 mb-1 font-semibold">연기차단재 수량</p>
                      <p className="font-bold text-amber-900">{calculationResults.items.smokeBarrierQty}</p>
                    </div>
                  )}
                  {calculationResults.items.smokeBarrierLength !== undefined && (
                    <div className="bg-white rounded-lg p-3 border">
                      <p className="text-xs text-gray-600 mb-1">연기차단재 재단 길이</p>
                      <p className="font-medium">{calculationResults.items.smokeBarrierLength} mm</p>
                    </div>
                  )}
                  {calculationResults.items.caseMaterial && (
                    <div className="bg-gradient-to-r from-indigo-100 to-purple-100 rounded-lg p-4 border-2 border-indigo-400">
                      <p className="text-xs text-indigo-700 mb-1 font-semibold">케이스판재 자재</p>
                      <p className="font-bold text-indigo-900">{calculationResults.items.caseMaterial}</p>
                    </div>
                  )}
                  {calculationResults.items.marguri && (
                    <div className="bg-white rounded-lg p-3 border">
                      <p className="text-xs text-gray-600 mb-1">마구리</p>
                      <p className="font-medium">{calculationResults.items.marguri}</p>
                    </div>
                  )}
                  {calculationResults.items.caseSmokeBarrier && (
                    <div className="bg-gradient-to-r from-rose-100 to-pink-100 rounded-lg p-4 border-2 border-rose-400">
                      <p className="text-xs text-rose-700 mb-1 font-semibold">케이스용 연기차단재</p>
                      <p className="font-bold text-rose-900">{calculationResults.items.caseSmokeBarrier}</p>
                    </div>
                  )}
                  {calculationResults.items.topCover && (
                    <div className="bg-gradient-to-r from-teal-100 to-cyan-100 rounded-lg p-4 border-2 border-teal-400">
                      <p className="text-xs text-teal-700 mb-1 font-semibold">상부덮개</p>
                      <p className="font-bold text-teal-900">{calculationResults.items.topCover}</p>
                    </div>
                  )}
                  {calculationResults.items.windingShaft !== undefined && (
                    <div className="bg-white rounded-lg p-3 border">
                      <p className="text-xs text-gray-600 mb-1">감기샤프트</p>
                      <p className="font-medium">{calculationResults.items.windingShaft} m</p>
                    </div>
                  )}
                  {calculationResults.items.bottomBar !== undefined && (
                    <div className="bg-white rounded-lg p-3 border">
                      <p className="text-xs text-gray-600 mb-1">하단바</p>
                      <p className="font-medium">{calculationResults.items.bottomBar} m</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
