"use client";

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

interface Row { DAY: string; ORDER_CNT: number; TOTAL: number; TAX_FREE: number; TAXABLE: number }
const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");

function defaultRange() {
  const e = new Date(), s = new Date();
  s.setDate(s.getDate() - 29);
  return [s.toISOString().slice(0, 10), e.toISOString().slice(0, 10)];
}

export default function DailyStatsPage() {
  const [[from, to], setRange] = useState(defaultRange());
  const [rows, setRows] = useState<Row[]>([]);
  const [loading, setLoading] = useState(false);

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

  const total = rows.reduce((a, r) => a + Number(r.TOTAL), 0);
  const totalFree = rows.reduce((a, r) => a + Number(r.TAX_FREE), 0);
  const totalTaxable = rows.reduce((a, r) => a + Number(r.TAXABLE), 0);
  const totalCnt = rows.reduce((a, r) => a + Number(r.ORDER_CNT), 0);

  const chartData = rows.map((r) => ({
    day: r.DAY.slice(5),
    면세: Number(r.TAX_FREE),
    과세: Number(r.TAXABLE),
    합계: Number(r.TOTAL),
    건수: Number(r.ORDER_CNT),
  }));

  const onExport = () => {
    if (rows.length === 0) return;
    downloadXlsx(
      `일별매출_${from}_${to}`,
      rows,
      [
        { header: "일자", key: "DAY", width: 12 },
        { header: "주문건수", key: (r) => Number(r.ORDER_CNT), width: 10 },
        { header: "면세 합계", key: (r) => Number(r.TAX_FREE), width: 14 },
        { header: "과세 공급가", key: (r) => Number(r.TAXABLE), width: 14 },
        { header: "총 매출", key: (r) => Number(r.TOTAL), width: 14 },
      ],
      "일별매출"
    );
  };

  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 items-end">
        <input type="date" value={from} onChange={(e) => setRange([e.target.value, to])} className="h-10 px-3 rounded-lg border border-slate-200 text-sm" />
        <input type="date" value={to} onChange={(e) => setRange([from, e.target.value])} className="h-10 px-3 rounded-lg border border-slate-200 text-sm" />
        <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(totalCnt)}건`} color="slate" />
        <Card label="면세 합계" value={`₩${fmt(totalFree)}`} color="violet" />
        <Card label="과세 공급가" value={`₩${fmt(totalTaxable)}`} color="rose" />
        <Card label="총 매출 (VAT)" value={`₩${fmt(total)}`} color="emerald" />
      </div>

      <div className="bg-white border rounded-xl p-4">
        <h3 className="font-bold text-slate-700 mb-3 text-sm">일별 매출 추이</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>
              <ComposedChart data={chartData} margin={{ top: 10, right: 20, bottom: 0, left: 10 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                <XAxis dataKey="day" tick={{ fontSize: 10 }} />
                <YAxis yAxisId="left" tick={{ fontSize: 10 }} tickFormatter={(v) => `${(v / 10000).toFixed(0)}만`} />
                <YAxis yAxisId="right" orientation="right" tick={{ fontSize: 10 }} />
                <Tooltip
                  formatter={(v, name) => name === "건수" ? `${Number(v)}건` : `₩${fmt(Number(v))}`}
                />
                <Legend wrapperStyle={{ fontSize: 11 }} />
                <Bar yAxisId="left" dataKey="면세" stackId="a" fill="#8b5cf6" />
                <Bar yAxisId="left" dataKey="과세" stackId="a" fill="#f43f5e" />
                <Line yAxisId="right" type="monotone" dataKey="건수" stroke="#0ea5e9" strokeWidth={2} dot={{ r: 3 }} />
              </ComposedChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      <div className="bg-white border 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>
              <th className="text-right px-4 py-3">합계</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 ? (
              <tr><td colSpan={5} className="text-center py-12 text-slate-400">선택한 기간의 매출 데이터가 없습니다.</td></tr>
            ) : rows.map((r) => (
              <tr key={r.DAY} className="border-t border-slate-100">
                <td className="px-4 py-2.5 font-semibold">{r.DAY}</td>
                <td className="px-4 py-2.5 text-right">{r.ORDER_CNT}건</td>
                <td className="px-4 py-2.5 text-right tabular-nums text-violet-700">₩{fmt(r.TAX_FREE)}</td>
                <td className="px-4 py-2.5 text-right tabular-nums text-rose-700">₩{fmt(r.TAXABLE)}</td>
                <td className="px-4 py-2.5 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: "slate" | "violet" | "rose" | "emerald" }) {
  const cls = {
    slate:   "bg-slate-50 border-slate-200 text-slate-800",
    violet:  "bg-violet-50 border-violet-200 text-violet-800",
    rose:    "bg-rose-50 border-rose-200 text-rose-800",
    emerald: "bg-emerald-50 border-emerald-200 text-emerald-800",
  }[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>
  );
}
