"use client";

import { useCallback, useEffect, useState } from "react";
import { Building2, MapPin, TrendingUp, RefreshCcw } from "lucide-react";

interface BranchRow {
  BRANCH: string; BRANCH_NAME: string;
  REVENUE: number; COST: number; MARGIN: number; ORDER_CNT: number;
  HQ_FEE_RATE: number; HQ_FEE_AMOUNT: number; NET_TO_BRANCH: number;
}

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

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

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

  useEffect(() => { load(); }, [load]);

  // 합계
  const totalRevenue = rows.reduce((a, r) => a + r.REVENUE, 0);
  const totalMargin  = rows.reduce((a, r) => a + r.MARGIN, 0);
  const totalHqFee   = rows.reduce((a, r) => a + r.HQ_FEE_AMOUNT, 0);
  const totalNet     = rows.reduce((a, r) => a + r.NET_TO_BRANCH, 0);

  return (
    <div className="space-y-4">
      <div className="flex items-end justify-between flex-wrap gap-2">
        <div>
          <h1 className="text-xl font-bold flex items-center gap-2">
            <Building2 size={20} className="text-emerald-700" />
            지사 관리 — 본사 수수료
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            계산서가 <b>김포 등 지사 명의</b>로 발행된 매출만 표시. 본사(HQ) 발주는 제외. 지사 마진의 20% 가 본사 수수료.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <select value={year} onChange={(e) => setYear(Number(e.target.value))}
            className="h-9 px-3 rounded border border-slate-300 bg-white 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-9 px-3 rounded border border-slate-300 bg-white text-sm">
            {Array.from({ length: 12 }, (_, i) => i + 1).map((m) => (
              <option key={m} value={m}>{m}월</option>
            ))}
          </select>
          <button onClick={load} disabled={loading}
            className="h-9 px-3 rounded bg-slate-800 text-white text-sm font-bold inline-flex items-center gap-1 hover:bg-slate-900 disabled:opacity-50">
            <RefreshCcw size={14} /> 조회
          </button>
        </div>
      </div>

      {/* 합계 카드 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <div className="bg-white border border-slate-200 rounded-xl p-4">
          <div className="text-[11px] text-slate-500 mb-1">총 매출</div>
          <div className="text-xl font-bold text-slate-800 tabular-nums">₩{fmt(totalRevenue)}</div>
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-4">
          <div className="text-[11px] text-slate-500 mb-1">총 순수 마진</div>
          <div className="text-xl font-bold text-emerald-700 tabular-nums">₩{fmt(totalMargin)}</div>
        </div>
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
          <div className="text-[11px] text-amber-700 mb-1 font-semibold">본사 수수료 (지사 마진의 20%)</div>
          <div className="text-xl font-bold text-amber-700 tabular-nums">₩{fmt(totalHqFee)}</div>
        </div>
        <div className="bg-white border border-slate-200 rounded-xl p-4">
          <div className="text-[11px] text-slate-500 mb-1">지사 실수령 (마진 − 수수료)</div>
          <div className="text-xl font-bold text-slate-800 tabular-nums">₩{fmt(totalNet)}</div>
        </div>
      </div>

      {/* 지사별 표 */}
      <div className="bg-white border border-slate-200 rounded-xl overflow-x-auto">
        <table className="w-full text-sm">
          <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 bg-amber-50 text-amber-700">본사 수수료 (20%)</th>
              <th className="text-right px-4 py-3">지사 실수령</th>
            </tr>
          </thead>
          <tbody className="tabular-nums">
            {rows.length === 0 ? (
              <tr><td colSpan={7} className="text-center py-12 text-slate-400">{loading ? "조회 중..." : "데이터가 없습니다."}</td></tr>
            ) : rows.map((r) => (
              <tr key={r.BRANCH} className="border-t border-slate-100">
                <td className="px-4 py-3">
                  <div className="inline-flex items-center gap-1.5">
                    <MapPin size={14} className="text-sky-700" />
                    <span className="font-semibold">{r.BRANCH_NAME}</span>
                    <span className="text-xs text-slate-400">({r.BRANCH})</span>
                  </div>
                </td>
                <td className="px-4 py-3 text-right">{fmt(r.ORDER_CNT)}</td>
                <td className="px-4 py-3 text-right">{fmt(r.REVENUE)}</td>
                <td className="px-4 py-3 text-right text-slate-500">{fmt(r.COST)}</td>
                <td className="px-4 py-3 text-right font-semibold text-emerald-700">{fmt(r.MARGIN)}</td>
                <td className="px-4 py-3 text-right bg-amber-50/60 font-bold text-amber-700">
                  ₩{fmt(r.HQ_FEE_AMOUNT)}
                </td>
                <td className="px-4 py-3 text-right font-bold">{fmt(r.NET_TO_BRANCH)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="text-[11px] text-slate-500 flex items-start gap-1.5">
        <TrendingUp size={12} className="mt-0.5 text-slate-400" />
        <div>
          계산서 발행 명의가 <b>본사(HQ) 외</b> 인 발주만 표시. 본사 수수료 = 지사 순수 마진 × 20%.
          매출/마진은 출고완료(APPROVED) 이상 (계산서발행/입금완료 포함) 만 집계.
        </div>
      </div>
    </div>
  );
}
