import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { 
  Bug, 
  ChevronDown, 
  ChevronRight,
  AlertCircle,
  CheckCircle,
  Calculator,
  DollarSign,
  Package,
  FileText
} from "lucide-react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";

export interface DebugInfo {
  timestamp: string;
  productInfo: {
    id: string;
    code: string;
    name: string;
    category: string;
    salesPrice: number;
    laborCost: number;
    installCost: number;
  };
  openSize: {
    width: number;
    height: number;
  };
  bomItems: Array<{
    itemCode: string;
    itemName: string;
    itemType: string;
    baseQuantity: number;
    calculatedQuantity: number;
    formula?: string;
    formulaEvaluation?: string;
    formulaSource?: string; // 수식 출처 (어느 FormulaRule에서 왔는지)
    formulaCategory?: string; // 수식 카테고리
    unit: string;
    unitPrice: number;
    unitPriceSource: 'salesPrice' | 'purchasePrice' | 'default';
    dataSource?: string; // 상세 데이터 출처 (품목마스터, 단가관리 등)
    totalPrice: number;
    warnings?: string[];
  }>;
  calculations: {
    materialCost: number;
    laborCost: number;
    installCost: number;
    subtotal: number;
    quantity: number;
    total: number;
  };
  warnings: string[];
  errors: string[];
}

interface QuoteDebugPanelProps {
  debugInfo: DebugInfo | null;
  isOpen?: boolean;
}

export function QuoteDebugPanel({ debugInfo, isOpen: initialIsOpen = false }: QuoteDebugPanelProps) {
  const [isOpen, setIsOpen] = useState(initialIsOpen);
  const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['product', 'bom']));

  if (!debugInfo) {
    return null;
  }

  const toggleSection = (section: string) => {
    setExpandedSections(prev => {
      const next = new Set(prev);
      if (next.has(section)) {
        next.delete(section);
      } else {
        next.add(section);
      }
      return next;
    });
  };

  const hasZeroPriceItems = debugInfo.bomItems.some(item => item.unitPrice === 0);
  const hasFormulaErrors = debugInfo.bomItems.some(item => item.warnings && item.warnings.length > 0);

  return (
    <Card className="border-2 border-yellow-500/30 bg-yellow-50/10">
      <CardHeader>
        <div 
          className="flex items-center justify-between cursor-pointer"
          onClick={() => setIsOpen(!isOpen)}
        >
          <div className="flex items-center gap-2">
            <Bug className="h-5 w-5 text-yellow-600" />
            <CardTitle className="text-yellow-900">견적 디버깅 정보</CardTitle>
            {(hasZeroPriceItems || hasFormulaErrors) && (
              <Badge variant="outline" className="bg-yellow-100 text-yellow-800 border-yellow-400">
                <AlertCircle className="h-3 w-3 mr-1" />
                주의 필요
              </Badge>
            )}
          </div>
          {isOpen ? <ChevronDown className="h-5 w-5" /> : <ChevronRight className="h-5 w-5" />}
        </div>
      </CardHeader>

      {isOpen && (
        <CardContent className="space-y-4">
          {/* 경고 및 에러 */}
          {(debugInfo.warnings.length > 0 || debugInfo.errors.length > 0) && (
            <div className="space-y-2">
              {debugInfo.errors.map((error, idx) => (
                <div key={idx} className="flex items-start gap-2 p-3 bg-red-50 border border-red-200 rounded-lg">
                  <AlertCircle className="h-4 w-4 text-red-600 mt-0.5" />
                  <p className="text-sm text-red-800">{error}</p>
                </div>
              ))}
              {debugInfo.warnings.map((warning, idx) => (
                <div key={idx} className="flex items-start gap-2 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                  <AlertCircle className="h-4 w-4 text-yellow-600 mt-0.5" />
                  <p className="text-sm text-yellow-800">{warning}</p>
                </div>
              ))}
            </div>
          )}

          {/* 제품 정보 */}
          <div className="border rounded-lg overflow-hidden">
            <button
              onClick={() => toggleSection('product')}
              className="w-full flex items-center justify-between p-3 bg-slate-50 hover:bg-slate-100 transition-colors"
            >
              <div className="flex items-center gap-2">
                <Package className="h-4 w-4" />
                <span className="font-semibold">제품 정보</span>
              </div>
              {expandedSections.has('product') ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
            </button>
            {expandedSections.has('product') && (
              <div className="p-4 space-y-2 bg-white">
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div><span className="text-muted-foreground">품목코드:</span> <strong>{debugInfo.productInfo.code}</strong></div>
                  <div><span className="text-muted-foreground">품목명:</span> <strong>{debugInfo.productInfo.name}</strong></div>
                  <div><span className="text-muted-foreground">카테고리:</span> <Badge>{debugInfo.productInfo.category}</Badge></div>
                  <div><span className="text-muted-foreground">판매단가:</span> <strong className={debugInfo.productInfo.salesPrice === 0 ? 'text-red-600' : ''}>{debugInfo.productInfo.salesPrice.toLocaleString()}원</strong></div>
                  <div><span className="text-muted-foreground">인건비:</span> {debugInfo.productInfo.laborCost.toLocaleString()}원</div>
                  <div><span className="text-muted-foreground">설치비:</span> {debugInfo.productInfo.installCost.toLocaleString()}원</div>
                  <div><span className="text-muted-foreground">오픈사이즈:</span> {debugInfo.openSize.width} × {debugInfo.openSize.height} mm</div>
                </div>
              </div>
            )}
          </div>

          {/* BOM 상세 정보 */}
          <div className="border rounded-lg overflow-hidden">
            <button
              onClick={() => toggleSection('bom')}
              className="w-full flex items-center justify-between p-3 bg-slate-50 hover:bg-slate-100 transition-colors"
            >
              <div className="flex items-center gap-2">
                <FileText className="h-4 w-4" />
                <span className="font-semibold">BOM 상세 ({debugInfo.bomItems.length}개 항목)</span>
                {hasZeroPriceItems && (
                  <Badge variant="outline" className="bg-red-50 text-red-700 border-red-300">
                    단가 누락
                  </Badge>
                )}
              </div>
              {expandedSections.has('bom') ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
            </button>
            {expandedSections.has('bom') && (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>품목코드</TableHead>
                      <TableHead>품목명</TableHead>
                      <TableHead>타입</TableHead>
                      <TableHead className="text-right">기준수량</TableHead>
                      <TableHead className="text-right">계산수량</TableHead>
                      <TableHead>수식/출처</TableHead>
                      <TableHead className="text-right">단가</TableHead>
                      <TableHead>데이터 출처</TableHead>
                      <TableHead className="text-right">합계</TableHead>
                      <TableHead>상태</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {debugInfo.bomItems.map((item, idx) => (
                      <TableRow key={idx} className={item.unitPrice === 0 ? 'bg-red-50' : ''}>
                        <TableCell className="font-mono text-xs">{item.itemCode}</TableCell>
                        <TableCell>{item.itemName}</TableCell>
                        <TableCell>
                          <Badge variant="outline" className="text-xs">
                            {item.itemType}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">{item.baseQuantity}</TableCell>
                        <TableCell className="text-right font-semibold">{item.calculatedQuantity.toFixed(2)}</TableCell>
                        <TableCell>
                          {item.formula ? (
                            <div className="space-y-1">
                              <code className="text-xs bg-slate-100 px-1 py-0.5 rounded">{item.formula}</code>
                              {item.formulaEvaluation && (
                                <div className="text-xs text-muted-foreground">{item.formulaEvaluation}</div>
                              )}
                              {item.formulaCategory && (
                                <Badge variant="outline" className="text-xs bg-purple-50 text-purple-700 border-purple-300">
                                  {item.formulaCategory}
                                </Badge>
                              )}
                              {item.formulaSource && (
                                <div className="text-xs text-blue-600">📍 {item.formulaSource}</div>
                              )}
                            </div>
                          ) : (
                            <span className="text-muted-foreground text-xs">기본수량</span>
                          )}
                        </TableCell>
                        <TableCell className={`text-right font-semibold ${item.unitPrice === 0 ? 'text-red-600' : ''}`}>
                          {item.unitPrice.toLocaleString()}원
                        </TableCell>
                        <TableCell>
                          <div className="space-y-1">
                            <Badge 
                              variant="outline" 
                              className={
                                item.unitPriceSource === 'default' 
                                  ? 'bg-red-50 text-red-700 border-red-300' 
                                  : item.unitPriceSource === 'salesPrice'
                                  ? 'bg-green-50 text-green-700 border-green-300'
                                  : 'bg-blue-50 text-blue-700 border-blue-300'
                              }
                            >
                              {item.unitPriceSource === 'salesPrice' ? '판매단가' : 
                               item.unitPriceSource === 'purchasePrice' ? '구매단가' : '미설정'}
                            </Badge>
                            {item.dataSource && (
                              <div className="text-xs text-green-600">📦 {item.dataSource}</div>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="text-right font-semibold">{item.totalPrice.toLocaleString()}원</TableCell>
                        <TableCell>
                          {item.warnings && item.warnings.length > 0 ? (
                            <div className="space-y-1">
                              {item.warnings.map((warning, wIdx) => (
                                <Badge key={wIdx} variant="outline" className="bg-yellow-50 text-yellow-700 border-yellow-300 text-xs">
                                  <AlertCircle className="h-3 w-3 mr-1" />
                                  {warning}
                                </Badge>
                              ))}
                            </div>
                          ) : (
                            <CheckCircle className="h-4 w-4 text-green-600" />
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </div>

          {/* 계산 요약 */}
          <div className="border rounded-lg overflow-hidden">
            <button
              onClick={() => toggleSection('calculation')}
              className="w-full flex items-center justify-between p-3 bg-slate-50 hover:bg-slate-100 transition-colors"
            >
              <div className="flex items-center gap-2">
                <Calculator className="h-4 w-4" />
                <span className="font-semibold">계산 요약</span>
              </div>
              {expandedSections.has('calculation') ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
            </button>
            {expandedSections.has('calculation') && (
              <div className="p-4 space-y-3 bg-white">
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">자재비:</span>
                    <strong>{debugInfo.calculations.materialCost.toLocaleString()}원</strong>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">인건비:</span>
                    <strong>{debugInfo.calculations.laborCost.toLocaleString()}원</strong>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">설치비:</span>
                    <strong>{debugInfo.calculations.installCost.toLocaleString()}원</strong>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">소계:</span>
                    <strong>{debugInfo.calculations.subtotal.toLocaleString()}원</strong>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">수량:</span>
                    <strong>{debugInfo.calculations.quantity}개</strong>
                  </div>
                  <div className="flex justify-between border-t pt-2">
                    <span className="text-muted-foreground font-semibold">총 금액:</span>
                    <strong className="text-lg text-primary">{debugInfo.calculations.total.toLocaleString()}원</strong>
                  </div>
                </div>

                <div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center gap-2 mb-2">
                    <DollarSign className="h-4 w-4 text-blue-600" />
                    <span className="font-semibold text-blue-900">계산식</span>
                  </div>
                  <div className="text-sm text-blue-800 space-y-1">
                    <div>소계 = 자재비 + 인건비 + 설치비</div>
                    <div>= {debugInfo.calculations.materialCost.toLocaleString()} + {debugInfo.calculations.laborCost.toLocaleString()} + {debugInfo.calculations.installCost.toLocaleString()}</div>
                    <div>= {debugInfo.calculations.subtotal.toLocaleString()}원</div>
                    <div className="pt-2 border-t border-blue-300">총 금액 = 소계 × 수량 = {debugInfo.calculations.subtotal.toLocaleString()} × {debugInfo.calculations.quantity} = {debugInfo.calculations.total.toLocaleString()}원</div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* 타임스탬프 */}
          <div className="text-xs text-muted-foreground text-center">
            계산 시각: {new Date(debugInfo.timestamp).toLocaleString('ko-KR')}
          </div>
        </CardContent>
      )}
    </Card>
  );
}