"use client";

import { useEffect, useState, useCallback } from "react";
import { RefreshCcw } from "lucide-react";
import Swal from "sweetalert2";

interface Order { OBJID: string; ORDER_NO: string; ORDER_DATE: string; COMPANY_NAME: string; STATUS: string; TOTAL_AMOUNT: number; PAID_AMOUNT: number }
const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");
const STATUS_LABEL: Record<string, string> = { APPROVED: "출고완료", PAID: "입금완료", INVOICED: "계산서발행" };

const pad = (n: number) => String(n).padStart(2, "0");
const todayStr = () => { const d = new Date(); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; };
const monthStartStr = () => { const d = new Date(); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-01`; };

// 입금상태 필터: 전체 / 입금 전(APPROVED) / 입금완료(PAID, INVOICED)
type PayFilter = "" | "UNPAID" | "PAID";

export default function PaymentsPage() {
  const [list, setList] = useState<Order[]>([]);
  const [loading, setLoading] = useState(false);

  const [keyword, setKeyword] = useState("");
  const [dateFrom, setDateFrom] = useState(monthStartStr());
  const [dateTo, setDateTo] = useState(todayStr());
  const [payFilter, setPayFilter] = useState<PayFilter>("");

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/m/orders/list", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          dateFrom: dateFrom || undefined,
          dateTo: dateTo || undefined,
          keyword: keyword || undefined,
        }),
      });
      const all = ((await res.json()).RESULTLIST ?? []) as Order[];
      // 출고완료 이후만 (대기/취소 제외) + 상태 필터
      const filtered = all.filter((o) => {
        if (!["APPROVED", "PAID", "INVOICED"].includes(o.STATUS)) return false;
        if (payFilter === "UNPAID" && o.STATUS !== "APPROVED") return false;
        if (payFilter === "PAID" && o.STATUS === "APPROVED") return false;
        return true;
      });
      setList(filtered);
    } finally {
      setLoading(false);
    }
  }, [dateFrom, dateTo, keyword, payFilter]);

  // 최초 1회만 자동 로드. 검색 조건 변경은 [조회] 버튼으로
  useEffect(() => { load(); }, []); // eslint-disable-line

  const onPay = async (o: Order) => {
    const remain = Number(o.TOTAL_AMOUNT) - Number(o.PAID_AMOUNT || 0);
    const r = await Swal.fire({
      title: `${o.COMPANY_NAME} 입금 등록`,
      html: `미입금 ₩${fmt(remain)}`, input: "number", inputValue: remain,
      showCancelButton: true, confirmButtonText: "입금 처리", confirmButtonColor: "#0f766e",
    });
    if (!r.isConfirmed) return;
    const amt = Number(r.value);
    const res = await fetch("/api/m/orders/payment", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ objid: o.OBJID, paidAmount: amt }),
    });
    const j = await res.json();
    if (j.success) {
      Swal.fire({ icon: "success", title: "입금 등록", timer: 1200, showConfirmButton: false });
      load();
    }
  };

  const totalRemain = list.reduce((a, o) => a + Math.max(0, Number(o.TOTAL_AMOUNT) - Number(o.PAID_AMOUNT || 0)), 0);
  const paidCnt = list.filter((o) => o.STATUS !== "APPROVED").length;

  return (
    <div className="space-y-3">
      <div>
        <h1 className="text-xl sm:text-2xl font-bold">입금 관리</h1>
        <p className="text-xs sm:text-sm text-slate-500 mt-1">출고완료 후 거래처 입금 등록 — 완납 시 상태가 입금완료로 자동 변경됩니다.</p>
      </div>

      {/* 검색 영역 — 모바일 1열 / sm 2열 / lg 5열 */}
      <div className="bg-white border border-slate-200 rounded-xl p-3">
        <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-[1fr_1fr_180px_1fr_auto] gap-2">
          <div>
            <label className="block text-[11px] font-semibold text-slate-500 mb-1">시작일</label>
            <input type="date" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)}
              className="w-full h-9 px-2 rounded-lg border border-slate-200 text-sm" />
          </div>
          <div>
            <label className="block text-[11px] font-semibold text-slate-500 mb-1">종료일</label>
            <input type="date" value={dateTo} onChange={(e) => setDateTo(e.target.value)}
              className="w-full h-9 px-2 rounded-lg border border-slate-200 text-sm" />
          </div>
          <div>
            <label className="block text-[11px] font-semibold text-slate-500 mb-1">입금 상태</label>
            <select value={payFilter} onChange={(e) => setPayFilter(e.target.value as PayFilter)}
              className="w-full h-9 px-2 rounded-lg border border-slate-200 text-sm bg-white">
              <option value="">전체</option>
              <option value="UNPAID">입금 전 (출고완료)</option>
              <option value="PAID">입금완료</option>
            </select>
          </div>
          <div className="col-span-2 sm:col-span-2 lg:col-span-1">
            <label className="block text-[11px] font-semibold text-slate-500 mb-1">업체명 / 발주번호</label>
            <input value={keyword} onChange={(e) => setKeyword(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && load()}
              placeholder="검색어"
              className="w-full h-9 px-2 rounded-lg border border-slate-200 text-sm" />
          </div>
          <div className="col-span-2 sm:col-span-2 lg:col-span-1 flex items-end gap-2">
            <button
              onClick={() => { setDateFrom(monthStartStr()); setDateTo(todayStr()); setKeyword(""); setPayFilter(""); }}
              className="h-9 px-3 rounded-lg border border-slate-200 bg-white text-slate-600 text-xs font-semibold hover:bg-slate-50"
            >
              초기화
            </button>
            <button onClick={load} disabled={loading}
              className="flex-1 lg:flex-none h-9 px-4 rounded-lg bg-slate-800 text-white text-sm font-bold hover:bg-slate-900 disabled:opacity-50 inline-flex items-center justify-center gap-1.5">
              <RefreshCcw size={14} className={loading ? "animate-spin" : ""} /> 조회
            </button>
          </div>
        </div>
      </div>

      {/* 요약 카드 */}
      <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 sm:gap-3">
        <div className="bg-white border border-slate-200 rounded-lg p-3">
          <div className="text-xs text-slate-500">전체 건</div>
          <div className="text-lg sm:text-xl font-bold mt-0.5">{list.length}건</div>
        </div>
        <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-3">
          <div className="text-xs text-emerald-700">입금 처리됨</div>
          <div className="text-lg sm:text-xl font-bold text-emerald-800 mt-0.5">{paidCnt}건</div>
        </div>
        <div className="col-span-2 sm:col-span-1 bg-rose-50 border border-rose-200 rounded-lg p-3">
          <div className="text-xs text-rose-700">미수금 합계</div>
          <div className="text-lg sm:text-xl font-bold text-rose-800 mt-0.5 tabular-nums">₩{fmt(totalRemain)}</div>
        </div>
      </div>

      {/* 모바일: 카드 리스트 */}
      <div className="space-y-2 sm:hidden">
        {list.length === 0 ? (
          <div className="bg-white border border-slate-200 rounded-xl p-8 text-center text-slate-400">
            {loading ? "조회 중..." : "조회 결과가 없습니다."}
          </div>
        ) : list.map((o) => {
          const remain = Number(o.TOTAL_AMOUNT) - Number(o.PAID_AMOUNT || 0);
          const paid = o.STATUS === "PAID" || o.STATUS === "INVOICED";
          return (
            <div key={o.OBJID} className="bg-white border border-slate-200 rounded-xl p-3 shadow-sm">
              <div className="flex items-center justify-between mb-1.5">
                <div>
                  <div className="font-semibold text-sm">{o.ORDER_NO}</div>
                  <div className="text-[11px] text-slate-500">{o.ORDER_DATE} · {o.COMPANY_NAME}</div>
                </div>
                <span className={`px-2 py-0.5 rounded text-[10px] font-semibold ${paid ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700"}`}>
                  {STATUS_LABEL[o.STATUS]}
                </span>
              </div>
              <div className="grid grid-cols-3 gap-2 text-[11px] py-2 border-t border-slate-100">
                <div>
                  <div className="text-slate-400">합계</div>
                  <div className="font-semibold tabular-nums">₩{fmt(o.TOTAL_AMOUNT)}</div>
                </div>
                <div>
                  <div className="text-slate-400">입금</div>
                  <div className="font-semibold text-emerald-700 tabular-nums">₩{fmt(o.PAID_AMOUNT || 0)}</div>
                </div>
                <div>
                  <div className="text-slate-400">미수금</div>
                  <div className={`font-bold tabular-nums ${remain > 0 ? "text-rose-700" : "text-slate-400"}`}>₩{fmt(remain)}</div>
                </div>
              </div>
              {o.STATUS !== "INVOICED" && (
                <button onClick={() => onPay(o)}
                  className="w-full mt-2 h-9 rounded-lg bg-emerald-700 text-white text-xs font-bold hover:bg-emerald-800">
                  💰 입금 등록
                </button>
              )}
            </div>
          );
        })}
      </div>

      {/* 데스크탑: 표 */}
      <div className="hidden sm:block bg-white border border-slate-200 rounded-xl overflow-x-auto">
        <table className="w-full text-sm min-w-[800px]">
          <thead className="bg-slate-50 text-slate-600">
            <tr>
              <th className="text-left px-4 py-3">발주번호</th>
              <th className="text-left px-4 py-3">발주일</th>
              <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-center px-4 py-3">상태</th>
              <th className="text-right px-4 py-3"></th>
            </tr>
          </thead>
          <tbody>
            {list.length === 0 ? (
              <tr><td colSpan={8} className="text-center py-12 text-slate-400">{loading ? "조회 중..." : "조회 결과가 없습니다."}</td></tr>
            ) : list.map((o) => {
              const remain = Number(o.TOTAL_AMOUNT) - Number(o.PAID_AMOUNT || 0);
              return (
                <tr key={o.OBJID} className="border-t border-slate-100">
                  <td className="px-4 py-3 font-semibold">{o.ORDER_NO}</td>
                  <td className="px-4 py-3">{o.ORDER_DATE}</td>
                  <td className="px-4 py-3">{o.COMPANY_NAME}</td>
                  <td className="px-4 py-3 text-right tabular-nums">₩{fmt(o.TOTAL_AMOUNT)}</td>
                  <td className="px-4 py-3 text-right tabular-nums text-emerald-700">₩{fmt(o.PAID_AMOUNT || 0)}</td>
                  <td className={`px-4 py-3 text-right tabular-nums font-bold ${remain > 0 ? "text-rose-700" : "text-slate-400"}`}>₩{fmt(remain)}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-1 rounded text-xs font-semibold ${o.STATUS === "PAID" || o.STATUS === "INVOICED" ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700"}`}>
                      {STATUS_LABEL[o.STATUS]}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-right">
                    {o.STATUS !== "INVOICED" && (
                      <button onClick={() => onPay(o)} className="text-xs px-3 h-8 rounded-md bg-emerald-700 text-white hover:bg-emerald-800 font-semibold">
                        입금 등록
                      </button>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
