"use client";

import { useEffect, useState, useCallback } from "react";
import { Download, RefreshCcw } from "lucide-react";
import { downloadXlsx } from "@/lib/xlsx-export";

interface DayCell { TAXFREE: number; TAXABLE: number }
interface Row { COMPANY_NAME: string; CUSTOMER_OBJID: string; BY_DAY: Record<string, DayCell>; TOTAL_TAXFREE: number; TOTAL_TAXABLE: number }
interface PivotResp {
  dates: string[];
  rows: Row[];
  totalsByDay: Record<string, DayCell>;
  grandTotal: { TAXFREE: number; TAXABLE: number; TOTAL: number };
}

const fmt = (n: number | undefined | null) => Number(n || 0).toLocaleString("ko-KR");

export default function PivotStatsPage() {
  const [year, setYear] = useState(new Date().getFullYear());
  const [month, setMonth] = useState(new Date().getMonth() + 1);
  const [data, setData] = useState<PivotResp | null>(null);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/m/statistics/monthly-pivot", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ year, month }),
      });
      const j = await res.json();
      if (j.success) setData(j);
    } finally { setLoading(false); }
  }, [year, month]);

  useEffect(() => { load(); }, []); // eslint-disable-line

  const dayLabel = (d: string) => {
    const [, mm, dd] = d.split("-");
    return `${Number(mm)}/${Number(dd)}`;
  };

  const onExport = () => {
    if (!data || data.rows.length === 0) return;
    // 각 row 를 (업체 + 일자별 면세/과세) 평면화
    const rows = data.rows.map((r) => {
      const o: Record<string, string | number> = {
        업체명: r.COMPANY_NAME,
        면세매출합: r.TOTAL_TAXFREE,
        과세매출합: r.TOTAL_TAXABLE,
      };
      data.dates.forEach((d) => {
        const c = r.BY_DAY[d] ?? { TAXFREE: 0, TAXABLE: 0 };
        o[`${dayLabel(d)} 면세`] = c.TAXFREE;
        o[`${dayLabel(d)} 과세`] = c.TAXABLE;
      });
      return o;
    });
    // 헤더 컬럼 자동 도출
    const cols: { header: string; key: keyof typeof rows[number]; width?: number }[] = [
      { header: "업체명", key: "업체명", width: 16 },
      { header: "면세매출합", key: "면세매출합", width: 14 },
      { header: "과세매출합", key: "과세매출합", width: 14 },
      ...data.dates.flatMap((d) => [
        { header: `${dayLabel(d)} 면세`, key: `${dayLabel(d)} 면세` as keyof typeof rows[number], width: 12 },
        { header: `${dayLabel(d)} 과세`, key: `${dayLabel(d)} 과세` as keyof typeof rows[number], width: 12 },
      ]),
    ];
    downloadXlsx(`거래처별_일자별매출_${year}_${month}`, rows, cols, `${year}_${month}`);
  };

  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <h1 className="text-xl sm:text-2xl font-bold">통계 — 거래처×일자 매출 (피벗)</h1>
          <p className="text-xs text-slate-500 mt-0.5">월간 토탈 면세/과세 + 일자별 분리. 부가세 신고 자료로 활용하세요.</p>
        </div>
        <div className="flex gap-2">
          <button onClick={load} className="inline-flex items-center gap-1 h-9 px-3 rounded-lg border border-slate-200 text-xs font-bold hover:bg-slate-50">
            <RefreshCcw size={14} /> 새로고침
          </button>
          <button onClick={onExport} disabled={!data || data.rows.length === 0}
            className="inline-flex items-center gap-1 h-9 px-3 rounded-lg bg-emerald-700 text-white text-xs font-bold hover:bg-emerald-800 disabled:opacity-50">
            <Download size={14} /> 엑셀
          </button>
        </div>
      </div>

      <div className="flex gap-2 flex-wrap">
        <select value={year} onChange={(e) => setYear(Number(e.target.value))}
          className="h-10 px-3 rounded-lg border border-slate-200 text-sm bg-white">
          {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => <option key={y} value={y}>{y}년</option>)}
        </select>
        <select value={month} onChange={(e) => setMonth(Number(e.target.value))}
          className="h-10 px-3 rounded-lg border border-slate-200 text-sm bg-white">
          {Array.from({ length: 12 }, (_, i) => i + 1).map((mm) => <option key={mm} value={mm}>{mm}월</option>)}
        </select>
        <button onClick={load} className="h-10 px-4 rounded-lg bg-slate-800 text-white text-sm font-semibold">조회</button>
      </div>

      {data && (
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
          <Card label={`${year}년 ${month}월 면세 합계`}  value={`₩${fmt(data.grandTotal.TAXFREE)}`} color="violet" />
          <Card label={`${year}년 ${month}월 과세 공급가`} value={`₩${fmt(data.grandTotal.TAXABLE)}`} color="rose" />
          <Card label={`총 매출 (면세+과세 공급가)`}     value={`₩${fmt(data.grandTotal.TOTAL)}`}   color="emerald" />
        </div>
      )}

      <div className="bg-white border border-slate-200 rounded-xl overflow-x-auto">
        {loading ? (
          <div className="text-center py-12 text-slate-400">불러오는 중...</div>
        ) : !data || data.rows.length === 0 ? (
          <div className="text-center py-12 text-slate-400">선택한 월의 매출 데이터가 없습니다.</div>
        ) : (
          <table className="text-[11px] tabular-nums" style={{ borderCollapse: "collapse", minWidth: "100%" }}>
            <thead className="bg-slate-100 sticky top-0">
              <tr>
                <th rowSpan={2} className="border border-slate-300 px-2 py-2 text-center bg-slate-200 sticky left-0 z-10" style={{ minWidth: 110 }}>업체명</th>
                <th colSpan={2} className="border border-slate-300 px-2 py-1 text-center bg-amber-100 font-bold">{year}.{month}월 TOT</th>
                {data.dates.map((d) => (
                  <th key={d} colSpan={2} className="border border-slate-300 px-2 py-1 text-center bg-emerald-50 font-bold">{year}년 {dayLabel(d).replace("/", "월 ")}일</th>
                ))}
              </tr>
              <tr>
                <th className="border border-slate-300 px-2 py-1 text-center bg-violet-100 font-bold" style={{ minWidth: 90 }}>면세매출합</th>
                <th className="border border-slate-300 px-2 py-1 text-center bg-rose-100 font-bold" style={{ minWidth: 90 }}>과세매출합</th>
                {data.dates.map((d) => (
                  <th key={`${d}-h`} colSpan={2} className="p-0">
                    <div className="grid grid-cols-2">
                      <div className="border border-slate-300 px-2 py-1 text-center text-violet-700" style={{ minWidth: 80 }}>면세</div>
                      <div className="border border-slate-300 px-2 py-1 text-center text-rose-700" style={{ minWidth: 80 }}>과세</div>
                    </div>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {/* TOT 행 */}
              <tr className="bg-amber-50/60 font-bold">
                <td className="border border-slate-300 px-2 py-2 text-center sticky left-0 bg-amber-100 z-10">TOT</td>
                <td className="border border-slate-300 px-2 py-2 text-right text-violet-700">{fmt(data.grandTotal.TAXFREE)}</td>
                <td className="border border-slate-300 px-2 py-2 text-right text-rose-700">{fmt(data.grandTotal.TAXABLE)}</td>
                {data.dates.map((d) => {
                  const c = data.totalsByDay[d];
                  return (
                    <td key={`tot-${d}`} colSpan={2} className="p-0">
                      <div className="grid grid-cols-2">
                        <div className="border border-slate-300 px-2 py-2 text-right text-violet-700">{fmt(c?.TAXFREE)}</div>
                        <div className="border border-slate-300 px-2 py-2 text-right text-rose-700">{fmt(c?.TAXABLE)}</div>
                      </div>
                    </td>
                  );
                })}
              </tr>

              {/* 거래처 행 */}
              {data.rows.map((r) => (
                <tr key={r.CUSTOMER_OBJID} className="hover:bg-emerald-50/30">
                  <td className="border border-slate-300 px-2 py-1.5 font-semibold sticky left-0 bg-white z-10">{r.COMPANY_NAME}</td>
                  <td className="border border-slate-300 px-2 py-1.5 text-right text-violet-700">{fmt(r.TOTAL_TAXFREE)}</td>
                  <td className="border border-slate-300 px-2 py-1.5 text-right text-rose-700">{fmt(r.TOTAL_TAXABLE)}</td>
                  {data.dates.map((d) => {
                    const c = r.BY_DAY[d];
                    return (
                      <td key={`${r.CUSTOMER_OBJID}-${d}`} colSpan={2} className="p-0">
                        <div className="grid grid-cols-2">
                          <div className="border border-slate-300 px-2 py-1.5 text-right">{c ? fmt(c.TAXFREE) : <span className="text-slate-300">-</span>}</div>
                          <div className="border border-slate-300 px-2 py-1.5 text-right">{c ? fmt(c.TAXABLE) : <span className="text-slate-300">-</span>}</div>
                        </div>
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

function Card({ label, value, color }: { label: string; value: string; color: "violet" | "rose" | "emerald" }) {
  const cls = {
    violet:  "bg-violet-50 border-violet-200 text-violet-900",
    rose:    "bg-rose-50 border-rose-200 text-rose-900",
    emerald: "bg-emerald-50 border-emerald-200 text-emerald-900",
  }[color];
  return (
    <div className={`rounded-xl border ${cls} p-4 sm:p-5`}>
      <div className="text-xs font-semibold opacity-80 mb-1">{label}</div>
      <div className="text-xl sm:text-2xl font-bold tabular-nums">{value}</div>
    </div>
  );
}
