"use client";

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

interface Row { ITEM_CODE: string; ITEM_NAME: string; QTY: number; REVENUE: number; COST: number; MARGIN: number }
const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");

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

  const load = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/m/statistics/margin", {
        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 totalRev = rows.reduce((a, r) => a + Number(r.REVENUE), 0);
  const totalCost = rows.reduce((a, r) => a + Number(r.COST), 0);
  const totalMargin = totalRev - totalCost;
  const marginPct = totalRev ? ((totalMargin / totalRev) * 100).toFixed(1) : "0.0";

  const chartData = [...rows]
    .sort((a, b) => Number(b.MARGIN) - Number(a.MARGIN))
    .slice(0, 10)
    .map((r) => ({
      name: r.ITEM_NAME?.length > 8 ? r.ITEM_NAME.slice(0, 8) + "…" : r.ITEM_NAME,
      fullName: r.ITEM_NAME,
      매출: Number(r.REVENUE),
      원가: Number(r.COST),
      마진: Number(r.MARGIN),
    }));

  const onExport = () => {
    if (rows.length === 0) return;
    downloadXlsx(
      `원가마진_${year}년${month}월`,
      rows,
      [
        { header: "품목코드", key: "ITEM_CODE", width: 16 },
        { header: "품목명", key: "ITEM_NAME", width: 24 },
        { header: "판매수량", key: (r) => Number(r.QTY), width: 10 },
        { header: "매출(공급가)", key: (r) => Number(r.REVENUE), width: 14 },
        { header: "매입원가", key: (r) => Number(r.COST), width: 14 },
        { header: "마진", key: (r) => Number(r.MARGIN), width: 14 },
        { header: "마진율(%)", key: (r) => Number(r.REVENUE) ? Number(((Number(r.MARGIN) / Number(r.REVENUE)) * 100).toFixed(2)) : 0, width: 10 },
      ],
      `${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-2 sm:grid-cols-4 gap-3">
        <Card label="매출(공급가)" value={`₩${fmt(totalRev)}`} color="emerald" />
        <Card label="매입원가" value={`₩${fmt(totalCost)}`} color="amber" />
        <Card label="마진" value={`₩${fmt(totalMargin)}`} color="blue" />
        <Card label="마진율" value={`${marginPct}%`} color="violet" />
      </div>

      <div className="bg-white border rounded-xl p-4">
        <h3 className="font-bold text-slate-700 mb-3 text-sm">마진 TOP 10 품목</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: 20, bottom: 30, left: 10 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                <XAxis dataKey="name" tick={{ fontSize: 10 }} 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 ?? ""}
                />
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Bar dataKey="원가" fill="#f59e0b" />
                <Bar dataKey="마진" fill="#10b981" />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      <div className="bg-white border rounded-xl overflow-x-auto">
        <table className="w-full text-sm min-w-[700px]">
          <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>
              <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={6} className="text-center py-12 text-slate-400">데이터가 없습니다.</td></tr>
            ) : rows.map((r) => {
              const pct = Number(r.REVENUE) ? ((Number(r.MARGIN) / Number(r.REVENUE)) * 100).toFixed(1) : "0.0";
              return (
                <tr key={r.ITEM_CODE} className="border-t border-slate-100">
                  <td className="px-4 py-2.5 font-semibold">{r.ITEM_NAME}</td>
                  <td className="px-4 py-2.5 text-right">{fmt(r.QTY)}</td>
                  <td className="px-4 py-2.5 text-right tabular-nums">₩{fmt(r.REVENUE)}</td>
                  <td className="px-4 py-2.5 text-right tabular-nums text-amber-700">₩{fmt(r.COST)}</td>
                  <td className="px-4 py-2.5 text-right tabular-nums font-bold text-emerald-700">₩{fmt(r.MARGIN)}</td>
                  <td className="px-4 py-2.5 text-right tabular-nums">{pct}%</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Card({ label, value, color }: { label: string; value: string; color: "amber" | "blue" | "violet" | "emerald" }) {
  const cls = {
    amber:   "bg-amber-50 border-amber-200 text-amber-900",
    blue:    "bg-blue-50 border-blue-200 text-blue-900",
    violet:  "bg-violet-50 border-violet-200 text-violet-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-lg sm:text-2xl font-bold tabular-nums">{value}</div>
    </div>
  );
}
