import React, { 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 { Play, Plus, Trash2, Copy } from "lucide-react";
import { useData } from "./contexts/DataContext";
import { AutoCalculationSimulator } from "./AutoCalculationSimulator";

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

interface QuoteItemResult {
  id: string;
  floors: string;
  signNumber: string;
  results: any;
}

export function MultiQuoteCalculator() {
  const { itemMasters } = useData();
  
  const [quoteItems, setQuoteItems] = useState<QuoteItem[]>([
    {
      id: crypto.randomUUID(),
      floors: "",
      signNumber: "",
      productId: "",
      category: "",
      w0: 0,
      h0: 0,
      guideRailInstallType: "",
      power: "",
      controller: "",
      quantity: 1,
      edgeWingSize: 50,
      inspectionFee: 50000,
    }
  ]);

  const [calculatedResults, setCalculatedResults] = useState<QuoteItemResult[]>([]);
  const [isCalculating, setIsCalculating] = useState(false);

  // 항목 추가
  const handleAddItem = () => {
    const newItem: QuoteItem = {
      id: crypto.randomUUID(),
      floors: "",
      signNumber: "",
      productId: "",
      category: "",
      w0: 0,
      h0: 0,
      guideRailInstallType: "",
      power: "",
      controller: "",
      quantity: 1,
      edgeWingSize: 50,
      inspectionFee: 50000,
    };
    setQuoteItems([...quoteItems, newItem]);
  };

  // 항목 복사
  const handleCopyItem = (index: number) => {
    const itemToCopy = quoteItems[index];
    const newItem: QuoteItem = {
      ...itemToCopy,
      id: crypto.randomUUID(),
      floors: "",
      signNumber: "",
    };
    const newItems = [...quoteItems];
    newItems.splice(index + 1, 0, newItem);
    setQuoteItems(newItems);
  };

  // 항목 삭제
  const handleRemoveItem = (index: number) => {
    if (quoteItems.length === 1) {
      alert("최소 1개의 항목이 필요합니다.");
      return;
    }
    const newItems = quoteItems.filter((_, i) => i !== index);
    setQuoteItems(newItems);
  };

  // 항목 업데이트
  const handleUpdateItem = (index: number, field: keyof QuoteItem, value: any) => {
    const newItems = [...quoteItems];
    newItems[index] = { ...newItems[index], [field]: value };
    setQuoteItems(newItems);
  };

  // 전체 계산 실행
  const handleCalculateAll = async () => {
    // Validation
    const invalidItems = quoteItems.filter(item => 
      !item.productId || !item.category || !item.w0 || !item.h0 || 
      !item.guideRailInstallType || !item.power || !item.controller
    );

    if (invalidItems.length > 0) {
      alert("모든 항목의 필수 항목(*)을 입력해주세요.");
      return;
    }

    setIsCalculating(true);
    
    // 계산 완료 후 결과 표시를 위해 상태 업데이트
    // 실제 계산은 AutoCalculationSimulator가 개별적으로 수행
    const results = quoteItems.map(item => ({
      id: item.id,
      floors: item.floors,
      signNumber: item.signNumber,
      results: null, // AutoCalculationSimulator가 개별적으로 계산
    }));

    setCalculatedResults(results);
    setIsCalculating(false);
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>다중 견적 산출</CardTitle>
          <Button onClick={handleAddItem} size="sm" variant="outline">
            <Plus className="h-4 w-4 mr-2" />
            항목 추가
          </Button>
        </CardHeader>
        <CardContent className="space-y-6">
          {quoteItems.map((item, index) => (
            <Card key={item.id} className="border-2">
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className="px-2 py-1 bg-primary/10 rounded text-sm">
                      항목 {index + 1}
                    </span>
                    {item.floors && (
                      <span className="text-sm text-muted-foreground">
                        {item.floors}
                      </span>
                    )}
                    {item.signNumber && (
                      <span className="text-sm text-muted-foreground">
                        / {item.signNumber}
                      </span>
                    )}
                  </div>
                  <div className="flex gap-2">
                    <Button
                      onClick={() => handleCopyItem(index)}
                      size="sm"
                      variant="ghost"
                    >
                      <Copy className="h-4 w-4" />
                    </Button>
                    <Button
                      onClick={() => handleRemoveItem(index)}
                      size="sm"
                      variant="ghost"
                      disabled={quoteItems.length === 1}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* 층수 / 부호 */}
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 p-3 bg-muted/30 rounded-lg">
                  <div>
                    <Label className="flex items-center gap-1">
                      층수
                      <span className="text-xs text-muted-foreground">(선택)</span>
                    </Label>
                    <Input
                      type="text"
                      value={item.floors}
                      onChange={(e) => handleUpdateItem(index, "floors", e.target.value)}
                      placeholder="예: 지하1층~지상5층"
                    />
                  </div>
                  <div>
                    <Label className="flex items-center gap-1">
                      부호
                      <span className="text-xs text-muted-foreground">(선택)</span>
                    </Label>
                    <Input
                      type="text"
                      value={item.signNumber}
                      onChange={(e) => handleUpdateItem(index, "signNumber", e.target.value)}
                      placeholder="예: A-101"
                    />
                  </div>
                </div>

                {/* 제품 정보 */}
                <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
                  <div>
                    <Label className="flex items-center gap-1">
                      제품명
                      <span className="text-red-500">*</span>
                    </Label>
                    <Select
                      value={item.productId}
                      onValueChange={(v) => handleUpdateItem(index, "productId", v)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="선택하세요" />
                      </SelectTrigger>
                      <SelectContent>
                        {itemMasters
                          .filter((im) => im.itemType === "FG")
                          .map((im) => (
                            <SelectItem key={im.id} value={im.id}>
                              {im.itemName} ({im.itemCode})
                            </SelectItem>
                          ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label className="flex items-center gap-1">
                      제품 카테고리
                      <span className="text-red-500">*</span>
                    </Label>
                    <Select
                      value={item.category}
                      onValueChange={(v) => handleUpdateItem(index, "category", v)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="선택하세요" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="스크린">스크린</SelectItem>
                        <SelectItem value="철재">철재</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label className="flex items-center gap-1">
                      오픈사이즈 W0 (mm)
                      <span className="text-red-500">*</span>
                    </Label>
                    <Input
                      type="number"
                      value={item.w0 || ''}
                      onChange={(e) => handleUpdateItem(index, "w0", parseFloat(e.target.value) || 0)}
                      placeholder="입력하세요"
                    />
                  </div>

                  <div>
                    <Label className="flex items-center gap-1">
                      오픈사이즈 H0 (mm)
                      <span className="text-red-500">*</span>
                    </Label>
                    <Input
                      type="number"
                      value={item.h0 || ''}
                      onChange={(e) => handleUpdateItem(index, "h0", parseFloat(e.target.value) || 0)}
                      placeholder="입력하세요"
                    />
                  </div>
                </div>

                {/* 상세 옵션 */}
                <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
                  <div>
                    <Label className="flex items-center gap-1">
                      가이드레일 설치 유형
                      <span className="text-red-500">*</span>
                    </Label>
                    <Select
                      value={item.guideRailInstallType}
                      onValueChange={(v) => handleUpdateItem(index, "guideRailInstallType", v)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="선택하세요" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="벽면형">벽면형</SelectItem>
                        <SelectItem value="측면형">측면형</SelectItem>
                        <SelectItem value="혼합형">혼합형</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label className="flex items-center gap-1">
                      모터 전원
                      <span className="text-red-500">*</span>
                    </Label>
                    <Select
                      value={item.power}
                      onValueChange={(v) => handleUpdateItem(index, "power", v)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="선택하세요" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="220V">220V</SelectItem>
                        <SelectItem value="380V">380V</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label className="flex items-center gap-1">
                      연동제어기
                      <span className="text-red-500">*</span>
                    </Label>
                    <Select
                      value={item.controller}
                      onValueChange={(v) => handleUpdateItem(index, "controller", v)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="선택하세요" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="매립">매립</SelectItem>
                        <SelectItem value="노출">노출</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label>수량</Label>
                    <Input
                      type="number"
                      value={item.quantity || ''}
                      onChange={(e) => handleUpdateItem(index, "quantity", parseInt(e.target.value) || 1)}
                      placeholder="입력하세요"
                    />
                  </div>
                </div>

                {/* 추가 옵션 */}
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                  <div>
                    <Label>마구리 날개치수 (mm)</Label>
                    <Input
                      type="number"
                      value={item.edgeWingSize || ''}
                      onChange={(e) => handleUpdateItem(index, "edgeWingSize", parseFloat(e.target.value) || 0)}
                      placeholder="입력하세요"
                    />
                  </div>

                  <div>
                    <Label>검사비 설정 (원)</Label>
                    <Input
                      type="number"
                      value={item.inspectionFee || ''}
                      onChange={(e) => handleUpdateItem(index, "inspectionFee", parseFloat(e.target.value) || 0)}
                      placeholder="입력하세요"
                    />
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}

          <Button
            onClick={handleCalculateAll}
            className="w-full"
            size="lg"
            disabled={isCalculating}
          >
            <Play className="h-4 w-4 mr-2" />
            {isCalculating ? "계산 중..." : `전체 견적 산출 (${quoteItems.length}개 항목)`}
          </Button>
        </CardContent>
      </Card>

      {/* 결과 표시 영역 */}
      {calculatedResults.length > 0 && (
        <div className="space-y-6">
          <h2 className="text-xl font-bold">견적 결과</h2>
          {quoteItems.map((item, index) => (
            <Card key={item.id}>
              <CardHeader>
                <CardTitle className="text-lg">
                  항목 {index + 1}
                  {item.floors && ` - ${item.floors}`}
                  {item.signNumber && ` / ${item.signNumber}`}
                </CardTitle>
              </CardHeader>
              <CardContent>
                <AutoCalculationSimulator
                  showSampleButton={false}
                  showResults={true}
                  initialSettings={{
                    productId: item.productId,
                    productCategory: item.category,
                    openSizeWidth: item.w0,
                    openSizeHeight: item.h0,
                    guideRailInstallType: item.guideRailInstallType,
                    motorPower: item.power,
                    controller: item.controller,
                    quantity: item.quantity,
                    edgeWingSize: item.edgeWingSize,
                    inspectionFee: item.inspectionFee,
                  }}
                />
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}