import React, { useState } from "react";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Button } from "./ui/button";
import { ChevronDown, ChevronUp, Bug, BugOff } from "lucide-react";
import { toast } from "sonner@2.0.3";

interface CalculationResultsProps {
  calculationResults: any;
  inputs: any;
  itemMasters?: any[];
  pricings?: any[];
  debugMode?: boolean;
}

export function FormulaCalculationResults({ 
  calculationResults, 
  inputs, 
  itemMasters = [], 
  pricings = [],
  debugMode = true 
}: CalculationResultsProps) {
  // 안전성 검사
  if (!calculationResults) {
    return (
      <div className="mt-6 p-4 border rounded-lg bg-yellow-50">
        <p className="text-yellow-800">계산 결과가 없습니다.</p>
      </div>
    );
  }

  const [discountRate, setDiscountRate] = useState(0);
  const [showDebugInfo, setShowDebugInfo] = useState(debugMode);
  const [expandedCategories, setExpandedCategories] = useState<Record<string, boolean>>({
    "BOM": true,
    "감기샤프트": true,
    "가이드레일": true,
    "하부BASE": true,
    "연기차단재": true,
    "케이스": true,
    "모터": true,
    "제어기": true,
    "마구리날개": true,
    "검사비": true
  });

  const toggleCategory = (category: string) => {
    setExpandedCategories(prev => ({
      ...prev,
      [category]: !prev[category]
    }));
  };

  // 모든 자동 산출 항목을 카테고리별로 그룹화
  const groupedItems: Record<string, any[]> = {
    "BOM": calculationResults.bomItems || [],
    "감기샤프트": calculationResults.windingShaftResults || [],
    "가이드레일": calculationResults.guideRailResults || [],
    "하부BASE": calculationResults.baseResults || [],
    "연기차단재": calculationResults.smokeBarrierResults || [],
    "케이스": calculationResults.caseItemResults || [],
    "모터": calculationResults.motorResults || [],
    "제어기": calculationResults.controllerResults || [],
    "마구리날개": calculationResults.edgeWingResults || [],
    "검사비": calculationResults.inspectionResults || []
  };

  // 카테고리별 색상
  const categoryConfig: Record<string, { color: string; bgColor: string }> = {
    "BOM": { color: "text-blue-700", bgColor: "bg-blue-50" },
    "감기샤프트": { color: "text-purple-700", bgColor: "bg-purple-50" },
    "가이드레일": { color: "text-green-700", bgColor: "bg-green-50" },
    "하부BASE": { color: "text-amber-700", bgColor: "bg-amber-50" },
    "연기차단재": { color: "text-red-700", bgColor: "bg-red-50" },
    "케이스": { color: "text-pink-700", bgColor: "bg-pink-50" },
    "모터": { color: "text-indigo-700", bgColor: "bg-indigo-50" },
    "제어기": { color: "text-cyan-700", bgColor: "bg-cyan-50" },
    "마구리날개": { color: "text-orange-700", bgColor: "bg-orange-50" },
    "검사비": { color: "text-emerald-700", bgColor: "bg-emerald-50" }
  };

  // 총 금액 계산
  const calculateTotals = () => {
    let totalAmount = 0;
    
    Object.values(groupedItems).forEach(items => {
      items.forEach((item: any) => {
        const itemTotal = (item.totalPrice !== undefined ? item.totalPrice : 
                          (item.quantity || item.calculatedQuantity || 0) * (item.unitPrice || 0));
        totalAmount += itemTotal;
      });
    });

    const discountAmount = totalAmount * (discountRate / 100);
    const finalAmount = totalAmount - discountAmount;

    return { totalAmount, discountAmount, finalAmount };
  };

  const { totalAmount, discountAmount, finalAmount } = calculateTotals();

  return (
    <div className="mt-6 space-y-4">
      {/* 입력 정보 요약 */}
      <div className="border rounded-lg overflow-hidden">
        <div className="bg-gradient-to-r from-blue-50 to-indigo-50 px-4 py-3 border-b">
          <h3 className="font-medium text-gray-800">입력 정보 요약</h3>
        </div>
        <div className="bg-white p-4 grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
          <div>
            <span className="text-gray-600">제품명:</span>
            <span className="ml-2 font-medium">{calculationResults.basic?.productName || "미선택"}</span>
          </div>
          <div>
            <span className="text-gray-600">카테고리:</span>
            <span className="ml-2 font-medium">{calculationResults.basic?.category}</span>
          </div>
          <div>
            <span className="text-gray-600">오픈사이즈:</span>
            <span className="ml-2 font-medium">W{inputs.w0} × H{inputs.h0}mm</span>
          </div>
          <div>
            <span className="text-gray-600">제작사이즈:</span>
            <span className="ml-2 font-medium">W{calculationResults.basic?.w1?.toFixed(0)} × H{calculationResults.basic?.h1?.toFixed(0)}mm</span>
          </div>
          <div>
            <span className="text-gray-600">면적(M):</span>
            <span className="ml-2 font-medium">{calculationResults.basic?.area?.toFixed(3)}m²</span>
          </div>
          <div>
            <span className="text-gray-600">중량(K):</span>
            <span className="ml-2 font-medium">{calculationResults.basic?.weight?.toFixed(2)}kg</span>
          </div>
          <div>
            <span className="text-gray-600">전원:</span>
            <span className="ml-2 font-medium">{inputs.power}</span>
          </div>
          <div>
            <span className="text-gray-600">수량:</span>
            <span className="ml-2 font-medium">{inputs.quantity}EA</span>
          </div>
        </div>
      </div>

      {/* 디버깅 토글 */}
      <div className="flex justify-end">
        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowDebugInfo(!showDebugInfo)}
          className="h-8"
        >
          {showDebugInfo ? (
            <>
              <BugOff className="h-3.5 w-3.5 mr-1.5" />
              디버깅 정보 숨기기
            </>
          ) : (
            <>
              <Bug className="h-3.5 w-3.5 mr-1.5" />
              디버깅 정보 보기
            </>
          )}
        </Button>
      </div>

      {/* 견적 리스트 */}
      <div className="border rounded-lg overflow-hidden">
        <div className="bg-gradient-to-r from-gray-50 to-gray-100 px-4 py-3 border-b">
          <h3 className="font-medium text-gray-800">견적 상세 내역</h3>
        </div>

        {Object.entries(groupedItems).map(([category, items]) => {
          if (!items || items.length === 0) return null;
          
          const config = categoryConfig[category];
          const isExpanded = expandedCategories[category];
          
          // 카테고리 합계
          const categoryTotal = items.reduce((sum: number, item: any) => {
            const itemTotal = item.totalPrice !== undefined ? item.totalPrice : 
                            (item.quantity || item.calculatedQuantity || 0) * (item.unitPrice || 0);
            return sum + itemTotal;
          }, 0);

          return (
            <div key={category} className="border-b last:border-b-0">
              {/* 카테고리 헤더 */}
              <div 
                className={`${config.bgColor} px-4 py-3 cursor-pointer hover:opacity-80 transition-opacity`}
                onClick={() => toggleCategory(category)}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <h4 className={`font-medium ${config.color}`}>{category}</h4>
                    <span className="text-xs text-gray-600">({items.length}개 항목)</span>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className="font-medium text-gray-700">
                      {categoryTotal.toLocaleString()}원
                    </span>
                    {isExpanded ? (
                      <ChevronUp className="h-4 w-4 text-gray-600" />
                    ) : (
                      <ChevronDown className="h-4 w-4 text-gray-600" />
                    )}
                  </div>
                </div>
              </div>

              {/* 카테고리 항목 리스트 */}
              {isExpanded && (
                <div className="bg-white">
                  {items.map((item: any, idx: number) => {
                    const quantity = item.quantity || item.calculatedQuantity || 0;
                    const unitPrice = item.unitPrice || 0;
                    const totalPrice = item.totalPrice !== undefined ? item.totalPrice : (quantity * unitPrice);

                    return (
                      <div key={idx} className="border-b last:border-b-0 hover:bg-gray-50 transition-colors">
                        {/* 기본 정보 */}
                        <div className="px-4 py-3">
                          <div className="flex items-start justify-between gap-4">
                            <div className="flex-1 min-w-0">
                              {/* 품목코드와 품목명 */}
                              <div className="flex items-center gap-2 mb-1">
                                <code className="text-xs bg-gray-100 text-gray-700 px-2 py-0.5 rounded font-mono">
                                  {item.itemCode}
                                </code>
                                <span className="font-medium text-gray-900">{item.itemName}</span>
                              </div>
                              
                              {/* 수량 및 단위 */}
                              <div className="text-sm text-gray-600 mb-2">
                                수량: <span className="font-medium text-gray-900">{quantity}</span> {item.unit || "EA"}
                              </div>

                              {/* 디버깅 정보 */}
                              {showDebugInfo && (
                                <div className="mt-2 space-y-1 text-xs bg-blue-50 border border-blue-200 rounded p-2">
                                  <div className="font-medium text-blue-900 mb-1">데이터 연동 및 계산 과정:</div>
                                  
                                  {/* 단가 출처 */}
                                  {item.pricingSource && (
                                    <div className="text-blue-800 ml-3">
                                      <strong>단가 출처:</strong> {item.pricingSource}
                                    </div>
                                  )}

                                  {/* 적용된 수식 */}
                                  {item.formulaUsed && (
                                    <div className="text-blue-800 ml-3">
                                      <strong>적용 수식:</strong> {item.formulaUsed}
                                    </div>
                                  )}

                                  {/* 계산 변수 */}
                                  {item.calculationVariables && (
                                    <div className="text-blue-800 ml-3">
                                      <strong>계산 변수:</strong> {item.calculationVariables}
                                    </div>
                                  )}

                                  {/* 수식 계산 과정 */}
                                  {item.formulaCalculation && (
                                    <div className="text-blue-800 ml-3">
                                      <strong>계산 과정:</strong> {item.formulaCalculation}
                                    </div>
                                  )}

                                  {/* BOM 수식 정보 */}
                                  {item.formula && (
                                    <div className="text-blue-800 ml-3">
                                      <strong>BOM 수식:</strong> {item.formula}
                                    </div>
                                  )}

                                  {/* 기준 수량 */}
                                  {item.baseQuantity !== undefined && item.baseQuantity !== quantity && (
                                    <div className="text-blue-800 ml-3">
                                      <strong>기준 수량:</strong> {item.baseQuantity} {item.unit || "EA"}
                                    </div>
                                  )}

                                  {/* 추가 설명 */}
                                  {item.description && (
                                    <div className="text-blue-800 ml-3">
                                      <strong>설명:</strong> {item.description}
                                    </div>
                                  )}

                                  {/* 상세 결과 */}
                                  {item.result && (
                                    <div className="text-blue-800 ml-3">
                                      <strong>산정 결과:</strong> {item.result}
                                    </div>
                                  )}

                                  {/* 단가 계산 과정 */}
                                  <div className="text-blue-800 ml-3 mt-1 pt-1 border-t border-blue-200">
                                    <strong>단가:</strong> {unitPrice.toLocaleString()}원
                                    {quantity > 0 && (
                                      <span className="ml-2">
                                        = {quantity} × {unitPrice.toLocaleString()}원 = <strong>{totalPrice.toLocaleString()}원</strong>
                                      </span>
                                    )}
                                  </div>
                                </div>
                              )}
                            </div>

                            {/* 금액 표시 */}
                            <div className="text-right flex-shrink-0">
                              <div className="text-xs text-gray-600 mb-1">단가</div>
                              <div className="text-sm font-medium text-gray-700 mb-2">
                                {unitPrice.toLocaleString()}원
                              </div>
                              <div className="text-xs text-gray-600 mb-1">금액</div>
                              <div className="font-medium text-gray-900">
                                {totalPrice.toLocaleString()}원
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* 최종 금액 계산 */}
      <div className="border rounded-lg overflow-hidden">
        <div className="bg-white">
          <div className="px-4 py-3 border-b flex items-center justify-between">
            <span className="font-medium text-gray-700">소계</span>
            <span className="font-medium text-gray-900">{totalAmount.toLocaleString()}원</span>
          </div>
          
          <div className="px-4 py-3 border-b flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Label htmlFor="discount-rate" className="text-sm font-medium text-gray-700">할인율</Label>
              <Input
                id="discount-rate"
                type="number"
                min="0"
                max="100"
                step="0.1"
                value={discountRate}
                onChange={(e) => setDiscountRate(parseFloat(e.target.value) || 0)}
                className="w-20 h-8 text-right"
              />
              <span className="text-sm text-gray-600">%</span>
            </div>
            <span className="font-medium text-red-600">-{discountAmount.toLocaleString()}원</span>
          </div>
          
          <div className="px-4 py-4 bg-gradient-to-r from-blue-50 to-indigo-50 flex items-center justify-between">
            <span className="font-medium text-blue-900">최종 금액</span>
            <span className="text-xl font-bold text-blue-900">{finalAmount.toLocaleString()}원</span>
          </div>
        </div>
      </div>

      {/* 디버깅 요약 정보 */}
      {showDebugInfo && (
        <div className="border rounded-lg overflow-hidden">
          <div className="bg-gradient-to-r from-green-50 to-emerald-50 px-4 py-3 border-b">
            <h3 className="font-medium text-green-800">전체 계산 요약</h3>
          </div>
          <div className="bg-white p-4 text-sm space-y-2">
            <div className="text-gray-700">
              <strong>총 {Object.values(groupedItems).reduce((sum, items) => sum + items.length, 0)}개 품목</strong>이 자동으로 산출되었습니다.
            </div>
            <div className="text-gray-700">
              기본 변수: W0={inputs.w0}mm, H0={inputs.h0}mm, W1={calculationResults.basic?.w1?.toFixed(0)}mm, H1={calculationResults.basic?.h1?.toFixed(0)}mm, M={calculationResults.basic?.area?.toFixed(3)}m², K={calculationResults.basic?.weight?.toFixed(2)}kg
            </div>
            <div className="text-gray-700">
              각 품목의 단가는 품목 카테고리에 매핑된 <strong>분류 그룹의 단가 수식</strong>을 통해 자동 계산됩니다.
            </div>
            <div className="text-gray-700">
              수식이 없는 품목은 <strong>품목관리의 판매단가</strong>를 직접 사용합니다.
            </div>
          </div>
        </div>
      )}
    </div>
  );
}