"use client";

import { useEffect, useState } from "react";
import { Download } from "lucide-react";
import {
  ResponsiveContainer, BarChart, Bar, XAxis, YAxis, Tooltip, Legend, CartesianGrid, Cell,
} from "recharts";
import { downloadXlsx } from "@/lib/xlsx-export";

interface MonthlyRow {
  COMPANY_NAME: string;
  TAX_FREE: number;
  TAXABLE: number;
  TOTAL: number;
}

const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");
const COLORS = ["#10b981", "#0ea5e9", "#8b5cf6", "#f59e0b", "#ef4444", "#14b8a6", "#6366f1", "#ec4899", "#84cc16"];

export default function StatisticsPage() {
  const [year, setYear] = useState(new Date().getFullYear());
  const [month, setMonth] = useState(new Date().getMonth() + 1);
  const [rows, setRows] = useState<MonthlyRow[]>([]);
  const [loading, setLoading] = useState(false);

  const load = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/m/statistics/monthly", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ year, month }),
      });
      setRows((await res.json()).RESULTLIST ?? []);
    } finally { setLoading(false); }
  };
  useEffect(() => { load(); }, []); // eslint-disable-line

  const grandTotal = rows.reduce((a, r) => a + Number(r.TOTAL), 0);
  const grandFree = rows.reduce((a, r) => a + Number(r.TAX_FREE), 0);
  const grandTaxable = rows.reduce((a, r) => a + Number(r.TAXABLE), 0);

  const chartData = rows
    .map((r) => ({
      name: r.COMPANY_NAME?.length > 8 ? r.COMPANY_NAME.slice(0, 8) + "…" : r.COMPANY_NAME,
      fullName: r.COMPANY_NAME,
      면세: Number(r.TAX_FREE),
      과세: Number(r.TAXABLE),
      합계: Number(r.TOTAL),
    }))
    .sort((a, b) => b.합계 - a.합계)
    .slice(0, 15);

  const onExport = () => {
    if (rows.length === 0) return;
    downloadXlsx(
      `업체별매출_${year}년${month}월`,
      rows,
      [
        { header: "업체명",    key: "COMPANY_NAME", width: 24 },
        { header: "면세 합계", key: (r) => Number(r.TAX_FREE), width: 15 },
        { header: "과세 공급가", key: (r) => Number(r.TAXABLE), width: 15 },
        { header: "총 매출",   key: (r) => Number(r.TOTAL), width: 15 },
      ],
      `${year}_${month}`
    );
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <h1 className="text-xl sm:text-2xl font-bold">업체별 발주통계 (월별)</h1>
        <button
          onClick={onExport}
          disabled={rows.length === 0}
          className="inline-flex items-center gap-1.5 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 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">
          {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">
          {Array.from({ length: 12 }, (_, i) => i + 1).map((m) => <option key={m} value={m}>{m}월</option>)}
        </select>
        <button onClick={load} className="h-10 px-4 rounded-lg bg-slate-800 text-white text-sm font-semibold">조회</button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <Card label="면세 합계" value={fmt(grandFree)} color="violet" />
        <Card label="과세 공급가" value={fmt(grandTaxable)} color="rose" />
        <Card label="총 매출 (VAT포함)" value={fmt(grandTotal)} color="emerald" />
      </div>

      {/* 차트 */}
      <div className="bg-white border border-slate-200 rounded-xl p-4">
        <h3 className="font-bold text-slate-700 mb-3 text-sm">업체별 매출 (TOP 15)</h3>
        <div className="w-full h-72 sm:h-80">
          {loading ? (
            <div className="h-full flex items-center justify-center text-slate-400">불러오는 중...</div>
          ) : chartData.length === 0 ? (
            <div className="h-full flex items-center justify-center text-slate-400">데이터가 없습니다.</div>
          ) : (
            <ResponsiveContainer>
              <BarChart data={chartData} margin={{ top: 10, right: 10, bottom: 30, left: 10 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                <XAxis dataKey="name" tick={{ fontSize: 11 }} interval={0} angle={-25} textAnchor="end" height={50} />
                <YAxis tick={{ fontSize: 10 }} tickFormatter={(v) => `${(v / 10000).toFixed(0)}만`} />
                <Tooltip
                  formatter={(v) => `₩${fmt(Number(v))}`}
                  labelFormatter={(_, payload) => (payload?.[0]?.payload as { fullName: string })?.fullName ?? ""}
                  cursor={{ fill: "rgba(16, 185, 129, 0.05)" }}
                />
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Bar dataKey="면세" stackId="a" fill="#8b5cf6" />
                <Bar dataKey="과세" stackId="a" fill="#f43f5e">
                  {chartData.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} fillOpacity={0.7} />)}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      <div className="bg-white border border-slate-200 rounded-xl overflow-x-auto">
        <table className="w-full text-sm min-w-[600px]">
          <thead className="bg-slate-50 text-slate-600">
            <tr>
              <th className="text-left px-4 py-3">업체명</th>
              <th className="text-right px-4 py-3">면세 합계</th>
              <th className="text-right px-4 py-3">과세 공급가</th>
              <th className="text-right px-4 py-3">총 매출</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 ? (
              <tr><td colSpan={4} className="text-center py-12 text-slate-400">선택한 월의 매출 데이터가 없습니다.</td></tr>
            ) : rows.map((r) => (
              <tr key={r.COMPANY_NAME} className="border-t border-slate-100">
                <td className="px-4 py-3 font-semibold">{r.COMPANY_NAME}</td>
                <td className="px-4 py-3 text-right tabular-nums text-violet-700">{fmt(r.TAX_FREE)}</td>
                <td className="px-4 py-3 text-right tabular-nums text-rose-700">{fmt(r.TAXABLE)}</td>
                <td className="px-4 py-3 text-right tabular-nums font-bold">₩{fmt(r.TOTAL)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Card({ label, value, color }: { label: string; value: string; color: "violet" | "rose" | "emerald" }) {
  const cls = {
    violet: "from-violet-50 to-violet-100 text-violet-800 border-violet-200",
    rose: "from-rose-50 to-rose-100 text-rose-800 border-rose-200",
    emerald: "from-emerald-50 to-emerald-100 text-emerald-800 border-emerald-200",
  }[color];
  return (
    <div className={`rounded-xl border bg-gradient-to-br ${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>
  );
}
