/**
 * 수식 보기 모달 (개발용)
 * - 10단계 계산 과정 (debug_steps)
 * - 실제 계산 수식 표시
 */

"use client";

import { Calculator, ChevronDown, ChevronRight } from "lucide-react";
import { useState } from "react";
import { formatNumber } from "@/lib/utils/amount";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "../ui/dialog";
import { ScrollArea } from "../ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";

import type { LocationItem, BomDebugStep } from "./types";

interface FormulaViewModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  locations: LocationItem[];
}

// 수식 항목 타입
interface FormulaItem {
  var?: string;
  desc?: string;
  formula?: string;
  calculation?: string;
  result?: number | string;
  value?: number | string;
  unit?: string;
  item?: string;
  qty_formula?: string;
  qty_result?: number;
  unit_price?: number;
  price_formula?: string;
  price_calc?: string;
  total?: number;
  category?: string;
}

export function FormulaViewModal({
  open,
  onOpenChange,
  locations,
}: FormulaViewModalProps) {
  const locationsWithBom = locations.filter((loc) => loc.bomResult);

  if (locationsWithBom.length === 0) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Calculator className="h-5 w-5" />
              수식 및 계산 결과
            </DialogTitle>
          </DialogHeader>
          <div className="py-8 text-center text-gray-500">
            계산된 결과가 없습니다. 견적 산출을 먼저 실행해주세요.
          </div>
        </DialogContent>
      </Dialog>
    );
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[95vw] w-[1600px] max-h-[90vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Calculator className="h-5 w-5" />
            수식 및 계산 결과
          </DialogTitle>
        </DialogHeader>

        <Tabs defaultValue={locationsWithBom[0]?.id} className="w-full">
          <TabsList className="mb-3 flex-wrap h-auto gap-1">
            {locationsWithBom.map((loc) => (
              <TabsTrigger key={loc.id} value={loc.id} className="text-xs">
                {loc.floor}/{loc.code}
              </TabsTrigger>
            ))}
          </TabsList>

          {locationsWithBom.map((location) => (
            <TabsContent key={location.id} value={location.id}>
              <ScrollArea className="h-[78vh] pr-4">
                <LocationDetail location={location} />
              </ScrollArea>
            </TabsContent>
          ))}
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}

function LocationDetail({ location }: { location: LocationItem }) {
  const bom = location.bomResult;
  if (!bom) return null;

  const debugSteps = bom.debug_steps || [];

  return (
    <div className="space-y-2 pb-6">
      {/* 10단계 계산 과정 */}
      {debugSteps.length > 0 ? (
        <div className="space-y-1">
          {debugSteps.map((step, idx) => (
            <DebugStepCard key={idx} step={step} />
          ))}
        </div>
      ) : (
        <div className="text-sm text-gray-500 p-3 bg-yellow-50 rounded border border-yellow-200">
          수식 정보가 없습니다. 견적을 다시 산출하면 10단계 계산 과정이 표시됩니다.
        </div>
      )}

      {/* 합계 */}
      <div className="flex justify-between items-center bg-blue-50 p-3 rounded-lg border border-blue-200 mt-4">
        <div className="text-sm">
          <span className="text-gray-600">완제품:</span>{" "}
          <span className="font-mono">{bom.finished_goods?.code}</span>{" "}
          <span className="text-gray-500">{bom.finished_goods?.name}</span>
        </div>
        <div className="text-right">
          <span className="text-sm text-gray-600">1개당 </span>
          <span className="font-bold text-blue-600">{formatNumber(bom.grand_total)}원</span>
          <span className="mx-2">×</span>
          <span className="text-sm">{location.quantity}개 =</span>
          <span className="font-bold text-green-600 text-lg ml-2">
            {formatNumber(bom.grand_total * location.quantity)}원
          </span>
        </div>
      </div>
    </div>
  );
}

function DebugStepCard({ step }: { step: BomDebugStep }) {
  const [expanded, setExpanded] = useState(step.step >= 1 && step.step <= 3);

  const stepColors: Record<number, string> = {
    0: "bg-gray-400",
    1: "bg-blue-500",
    2: "bg-blue-600",
    3: "bg-green-500",
    4: "bg-green-600",
    5: "bg-yellow-500",
    6: "bg-yellow-600",
    7: "bg-orange-500",
    8: "bg-purple-500",
    9: "bg-purple-600",
    10: "bg-red-500",
  };

  // formulas 배열이 있는지 확인
  const formulas = step.data.formulas as FormulaItem[] | undefined;
  const hasFormulas = formulas && Array.isArray(formulas) && formulas.length > 0;

  return (
    <div className="border rounded overflow-hidden">
      <button
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center gap-2 px-3 py-2 bg-gray-50 hover:bg-gray-100 text-left text-sm"
      >
        {expanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
        <span className={`w-6 h-6 rounded text-white text-xs flex items-center justify-center flex-shrink-0 ${stepColors[step.step] || "bg-gray-500"}`}>
          {step.step}
        </span>
        <span className="font-medium">{step.name}</span>
        {hasFormulas && (
          <span className="text-xs text-blue-500 ml-2">({formulas.length}개 수식)</span>
        )}
      </button>
      {expanded && (
        <div className="p-3 bg-white border-t">
          {hasFormulas ? (
            <FormulaTable formulas={formulas} stepName={step.name} />
          ) : (
            <GenericDataView data={step.data} />
          )}
        </div>
      )}
    </div>
  );
}

function FormulaTable({ formulas, stepName: _stepName }: { formulas: FormulaItem[]; stepName: string }) {
  // 입력값 (Step 1)
  if (formulas[0]?.var && formulas[0]?.value !== undefined) {
    return (
      <table className="w-full text-sm border-collapse">
        <thead>
          <tr className="bg-gray-100">
            <th className="p-2 text-left border w-28">변수</th>
            <th className="p-2 text-left border">설명</th>
            <th className="p-2 text-right border w-32">값</th>
            <th className="p-2 text-left border w-20">단위</th>
          </tr>
        </thead>
        <tbody>
          {formulas.map((f, i) => (
            <tr key={i} className="border-b hover:bg-gray-50">
              <td className="p-2 border font-mono font-bold text-blue-600">{f.var}</td>
              <td className="p-2 border text-gray-600">{f.desc}</td>
              <td className="p-2 border text-right font-mono">{typeof f.value === 'number' ? formatNumber(f.value) : f.value}</td>
              <td className="p-2 border text-gray-500">{f.unit}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }

  // 변수 계산 (Step 3) - formula, calculation, result
  if (formulas[0]?.formula && formulas[0]?.calculation) {
    return (
      <table className="w-full text-sm border-collapse">
        <thead>
          <tr className="bg-gray-100">
            <th className="p-2 text-left border w-36">변수</th>
            <th className="p-2 text-left border">수식</th>
            <th className="p-2 text-left border">대입</th>
            <th className="p-2 text-right border w-28">결과</th>
          </tr>
        </thead>
        <tbody>
          {formulas.map((f, i) => (
            <tr key={i} className="border-b hover:bg-gray-50">
              <td className="p-2 border">
                <span className="font-mono font-bold text-blue-600">{f.var}</span>
                <span className="text-gray-500 text-xs ml-2">{f.desc}</span>
              </td>
              <td className="p-2 border font-mono text-purple-600">{f.formula}</td>
              <td className="p-2 border font-mono text-gray-600">{f.calculation}</td>
              <td className="p-2 border text-right">
                <span className="font-mono font-bold">{typeof f.result === 'number' ? formatNumber(f.result) : f.result}</span>
                <span className="text-gray-500 text-xs ml-1">{f.unit}</span>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }

  // 품목 수량/금액 계산 (Step 6, 7)
  if (formulas[0]?.item) {
    return (
      <table className="w-full text-sm border-collapse">
        <thead>
          <tr className="bg-gray-100">
            <th className="p-2 text-left border">품목</th>
            <th className="p-2 text-left border w-40">수량 수식</th>
            <th className="p-2 text-right border w-20">수량</th>
            <th className="p-2 text-right border w-24">단가</th>
            <th className="p-2 text-left border w-40">금액 계산</th>
            <th className="p-2 text-right border w-28">금액</th>
          </tr>
        </thead>
        <tbody>
          {formulas.map((f, i) => (
            <tr key={i} className="border-b hover:bg-gray-50">
              <td className="p-2 border font-medium">{f.item}</td>
              <td className="p-2 border font-mono text-purple-600 text-xs">{f.qty_formula}</td>
              <td className="p-2 border text-right font-mono">{f.qty_result}</td>
              <td className="p-2 border text-right font-mono">{formatNumber(f.unit_price)}</td>
              <td className="p-2 border font-mono text-gray-600 text-xs">{f.price_calc}</td>
              <td className="p-2 border text-right font-mono font-bold">{formatNumber(f.total)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }

  // 소계 (Step 9)
  if (formulas[0]?.category) {
    return (
      <table className="w-full text-sm border-collapse">
        <thead>
          <tr className="bg-gray-100">
            <th className="p-2 text-left border w-32">카테고리</th>
            <th className="p-2 text-left border">포함 품목</th>
            <th className="p-2 text-right border w-28">소계</th>
          </tr>
        </thead>
        <tbody>
          {formulas.map((f, i) => (
            <tr key={i} className="border-b hover:bg-gray-50">
              <td className="p-2 border font-medium">{f.category}</td>
              <td className="p-2 border text-gray-600 text-xs">{f.formula}</td>
              <td className="p-2 border text-right font-mono font-bold">{typeof f.result === 'number' ? formatNumber(f.result) : f.result}원</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }

  // 기본 폴백 — 범용 렌더러
  return <GenericDataView data={formulas} />;
}

// =============================================================================
// 범용 JSON 데이터 렌더러 (formulas 없는 step용)
// =============================================================================

// 금액성 키 감지
const AMOUNT_KEYS = ['subtotal', 'grand_total', 'total_price', 'unit_price', 'total'];
const LABEL_MAP: Record<string, string> = {
  tenant_id: '테넌트 ID',
  handler: '계산 핸들러',
  handler_class: '핸들러 클래스',
  finished_goods: '완제품 코드',
  code: '코드',
  name: '제품명',
  item_category: '품목 카테고리',
  total_items: '총 품목 수',
  item_codes: '품목 코드',
  items: '품목 목록',
  groups: '카테고리 그룹',
  count: '품목 수',
  subtotal: '소계',
  grand_total: '총합계',
  formatted: '금액',
  item_count: '품목 수',
  formula: '수식',
  calculation: '계산',
  result: '결과',
  category: '카테고리',
  item_categories: '품목 카테고리',
};

function isAmountKey(key: string): boolean {
  return AMOUNT_KEYS.some(k => key.toLowerCase().includes(k));
}

function formatValue(key: string, value: unknown): string {
  if (value === null || value === undefined) return '-';
  if (typeof value === 'number') {
    if (isAmountKey(key)) return `${formatNumber(value)}원`;
    return formatNumber(value);
  }
  return String(value);
}

function GenericDataView({ data }: { data: unknown }) {
  if (data === null || data === undefined) return null;

  // 배열 처리
  if (Array.isArray(data)) {
    // 객체 배열 → 카드 리스트
    if (data.length > 0 && typeof data[0] === 'object') {
      return (
        <div className="space-y-2">
          {data.map((item, i) => (
            <div key={i} className="bg-gray-50 rounded border p-2">
              <GenericDataView data={item} />
            </div>
          ))}
        </div>
      );
    }
    // 단순 배열 → 태그
    return (
      <div className="flex flex-wrap gap-1">
        {data.map((item, i) => (
          <span key={i} className="inline-block bg-blue-100 text-blue-700 text-xs px-2 py-0.5 rounded">
            {String(item)}
          </span>
        ))}
      </div>
    );
  }

  // 객체 처리
  if (typeof data === 'object') {
    const entries = Object.entries(data as Record<string, unknown>);
    return (
      <div className="space-y-1.5">
        {entries.map(([key, value]) => (
          <GenericField key={key} fieldKey={key} value={value} />
        ))}
      </div>
    );
  }

  // 원시 값
  return <span className="text-sm font-mono">{String(data)}</span>;
}

function GenericField({ fieldKey, value }: { fieldKey: string; value: unknown }) {
  const label = LABEL_MAP[fieldKey] || fieldKey;

  // 중첩 객체/배열 → 접이식
  if (typeof value === 'object' && value !== null) {
    const isArray = Array.isArray(value);
    const count = isArray ? value.length : Object.keys(value as object).length;

    return (
      <div className="border-l-2 border-gray-200 pl-3">
        <div className="text-xs font-medium text-gray-500 mb-1">
          {label}
          {isArray && <span className="text-blue-500 ml-1">({count}개)</span>}
        </div>
        <GenericDataView data={value} />
      </div>
    );
  }

  // 단순 key-value
  const isAmount = isAmountKey(fieldKey);
  return (
    <div className="flex items-baseline gap-2 text-sm">
      <span className="text-gray-500 text-xs min-w-[80px] shrink-0">{label}</span>
      <span className={`font-mono ${isAmount ? 'font-bold text-blue-600' : 'text-gray-800'}`}>
        {formatValue(fieldKey, value)}
      </span>
    </div>
  );
}