"use client";

import { useEffect, useState, useMemo, useCallback } from "react";
import Swal from "sweetalert2";
import { SearchableSelect } from "@/components/ui/searchable-select";

interface Proc {
  OBJID: string;
  PROC_NO: string;
  PROC_DATE: string;
  VENDOR_OBJID: string;
  VENDOR_NAME: string;
  VENDOR_CONTACT: string;
  TOTAL_AMOUNT: number;
  STATUS: string;
  PAYMENT_TERMS: string | null;
  PAID_DATE: string | null;
  PAID_AMOUNT: number | null;
  PAID_METHOD: string | null;
  PAID_MEMO: string | null;
}
interface Vendor { OBJID: string; VENDOR_NAME: string }

const fmt = (n: number | string | null | undefined) => Number(n || 0).toLocaleString("ko-KR");
const STATUS_LABEL: Record<string, string> = { REQUESTED: "발주요청", PAID: "입금완료" };
const STATUS_COLOR: Record<string, string> = {
  REQUESTED: "bg-amber-100 text-amber-700",
  PAID: "bg-emerald-100 text-emerald-700",
};

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

export default function ProcPaymentsPage() {
  const [list, setList] = useState<Proc[]>([]);
  const [vendors, setVendors] = useState<Vendor[]>([]);
  const [[from, to], setRange] = useState(defaultRange());
  const [vendorFilter, setVendorFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    const res = await fetch("/api/m/admin/proc-payments/list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        dateFrom: from || undefined,
        dateTo: to || undefined,
        vendorObjid: vendorFilter || undefined,
        status: statusFilter || undefined,
      }),
    });
    setList((await res.json()).RESULTLIST ?? []);
  }, [from, to, vendorFilter, statusFilter]);

  const loadVendors = useCallback(async () => {
    const res = await fetch("/api/m/vendors/list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: "{}",
    });
    setVendors((await res.json()).RESULTLIST ?? []);
  }, []);

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

  const summary = useMemo(() => {
    let requested = 0, requestedAmt = 0, paid = 0, paidAmt = 0;
    for (const p of list) {
      if (p.STATUS === "REQUESTED") { requested++; requestedAmt += Number(p.TOTAL_AMOUNT) || 0; }
      if (p.STATUS === "PAID")      { paid++; paidAmt += Number(p.PAID_AMOUNT || p.TOTAL_AMOUNT) || 0; }
    }
    return { requested, requestedAmt, paid, paidAmt };
  }, [list]);

  const onPay = async (p: Proc) => {
    const result = await Swal.fire({
      title: "입금 처리",
      html: `
        <div class="text-left text-sm space-y-2">
          <div><b>발주번호</b> ${p.PROC_NO}</div>
          <div><b>공급업체</b> ${p.VENDOR_NAME ?? "-"}</div>
          <div><b>발주금액</b> ₩${fmt(p.TOTAL_AMOUNT)}</div>
        </div>
        <div class="mt-3 space-y-2 text-left">
          <input id="sw-amount"  class="swal2-input" placeholder="입금 금액 (기본 발주금액)" value="${p.TOTAL_AMOUNT}" type="number" />
          <input id="sw-method"  class="swal2-input" placeholder="입금 방법 (예: 계좌이체)" />
          <input id="sw-memo"    class="swal2-input" placeholder="메모 (선택)" />
        </div>
      `,
      showCancelButton: true,
      confirmButtonText: "입금 완료",
      confirmButtonColor: "#0f766e",
      cancelButtonText: "취소",
      focusConfirm: false,
      preConfirm: () => {
        const a = (document.getElementById("sw-amount") as HTMLInputElement)?.value;
        const m = (document.getElementById("sw-method") as HTMLInputElement)?.value;
        const memo = (document.getElementById("sw-memo") as HTMLInputElement)?.value;
        return { amount: Number(a) || Number(p.TOTAL_AMOUNT), method: m, memo };
      },
    });
    if (!result.isConfirmed || !result.value) return;
    setBusy(true);
    try {
      const res = await fetch("/api/m/admin/proc-payments/confirm", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ objid: p.OBJID, ...result.value }),
      });
      const j = await res.json();
      if (j.success) {
        await Swal.fire({ icon: "success", title: "입금 처리 완료", timer: 1200, showConfirmButton: false });
        load();
      } else {
        Swal.fire({ icon: "error", title: "처리 실패", text: j.message });
      }
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="space-y-3">
      <div>
        <h1 className="text-xl sm:text-2xl font-bold">매입 입금관리</h1>
        <p className="text-xs text-slate-500 mt-0.5">발주 요청된 매입에 대해 입금 처리합니다. 입금 완료된 건은 입고 처리 메뉴에서 입고 등록할 수 있습니다.</p>
      </div>

      {/* 조회조건 — 입력 즉시 반영, 모바일에서도 한 줄 (가로 스크롤) */}
      <div className="bg-white border border-slate-200 rounded-xl p-2 flex gap-1.5 items-center flex-nowrap overflow-x-auto text-xs max-w-full">
        <input type="date" value={from} onChange={(e) => setRange([e.target.value, to])}
          className="h-8 px-2 rounded border border-slate-200 shrink-0 w-[130px]" />
        <span className="text-slate-400 shrink-0">~</span>
        <input type="date" value={to} onChange={(e) => setRange([from, e.target.value])}
          className="h-8 px-2 rounded border border-slate-200 shrink-0 w-[130px]" />
        <div className="shrink-0 w-[150px]">
          <SearchableSelect
            options={[{ value: "", label: "전체 공급업체" }, ...vendors.map((v) => ({ value: v.OBJID, label: v.VENDOR_NAME }))]}
            value={vendorFilter}
            onChange={setVendorFilter}
            placeholder="공급업체"
          />
        </div>
        <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}
          className="h-8 px-2 rounded border border-slate-200 bg-white shrink-0">
          <option value="">전체 상태</option>
          <option value="REQUESTED">발주요청 (미입금)</option>
          <option value="PAID">입금완료</option>
        </select>
      </div>

      {/* 합계 카드 */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
        <div className="bg-amber-50 border border-amber-200 rounded-lg p-3">
          <div className="text-[11px] text-amber-700 font-semibold mb-1.5">미입금 ({summary.requested}건)</div>
          <div className="text-lg font-bold tabular-nums text-amber-700">₩{fmt(summary.requestedAmt)}</div>
        </div>
        <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-3">
          <div className="text-[11px] text-emerald-700 font-semibold mb-1.5">입금완료 ({summary.paid}건)</div>
          <div className="text-lg font-bold tabular-nums text-emerald-700">₩{fmt(summary.paidAmt)}</div>
        </div>
      </div>

      {/* 모바일: 카드 */}
      <div className="space-y-2 sm:hidden">
        {list.length === 0 ? (
          <div className="bg-white border border-slate-200 rounded-xl p-6 text-center text-slate-400 text-sm">발주가 없습니다.</div>
        ) : list.map((p) => (
          <div key={p.OBJID} className="bg-white border border-slate-200 rounded-xl p-3 shadow-sm">
            <div className="flex items-start justify-between gap-2 mb-2">
              <div className="min-w-0">
                <div className="font-semibold text-sm truncate">{p.PROC_NO}</div>
                <div className="text-[11px] text-slate-500">{p.PROC_DATE} · {p.VENDOR_NAME}</div>
              </div>
              <span className={`text-[10px] px-1.5 py-0.5 rounded font-semibold ${STATUS_COLOR[p.STATUS]}`}>
                {STATUS_LABEL[p.STATUS] || p.STATUS}
              </span>
            </div>
            <div className="text-right text-sm font-bold tabular-nums mb-2">₩{fmt(p.TOTAL_AMOUNT)}</div>
            {p.STATUS === "REQUESTED" ? (
              <button onClick={() => onPay(p)} disabled={busy}
                className="w-full h-8 rounded bg-emerald-700 text-white text-xs font-bold disabled:opacity-50">입금 처리</button>
            ) : (
              <div className="text-[11px] text-emerald-700">
                입금일 {p.PAID_DATE} · ₩{fmt(p.PAID_AMOUNT)} {p.PAID_METHOD && `· ${p.PAID_METHOD}`}
              </div>
            )}
          </div>
        ))}
      </div>

      {/* 데스크탑: 표 */}
      <div className="hidden sm:block bg-white border border-slate-200 rounded-xl overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-slate-50 text-slate-600 text-xs">
            <tr>
              <th className="text-left px-3 py-2.5">발주번호</th>
              <th className="text-left px-3 py-2.5">발주일</th>
              <th className="text-left px-3 py-2.5">공급업체</th>
              <th className="text-right px-3 py-2.5">발주금액</th>
              <th className="text-center px-3 py-2.5">상태</th>
              <th className="text-left px-3 py-2.5">입금일</th>
              <th className="text-right px-3 py-2.5">입금액</th>
              <th className="text-center px-3 py-2.5 w-[120px]">동작</th>
            </tr>
          </thead>
          <tbody>
            {list.length === 0 ? (
              <tr><td colSpan={8} className="text-center py-10 text-slate-400">발주가 없습니다.</td></tr>
            ) : list.map((p) => (
              <tr key={p.OBJID} className="border-t border-slate-100 hover:bg-slate-50">
                <td className="px-3 py-2.5 font-semibold">{p.PROC_NO}</td>
                <td className="px-3 py-2.5">{p.PROC_DATE}</td>
                <td className="px-3 py-2.5">{p.VENDOR_NAME ?? "-"}</td>
                <td className="px-3 py-2.5 text-right tabular-nums font-bold">₩{fmt(p.TOTAL_AMOUNT)}</td>
                <td className="px-3 py-2.5 text-center">
                  <span className={`text-[10px] px-1.5 py-0.5 rounded font-semibold ${STATUS_COLOR[p.STATUS]}`}>
                    {STATUS_LABEL[p.STATUS] || p.STATUS}
                  </span>
                </td>
                <td className="px-3 py-2.5 text-[11px] text-slate-600">{p.PAID_DATE || "-"}</td>
                <td className="px-3 py-2.5 text-right tabular-nums text-emerald-700">{p.PAID_AMOUNT ? `₩${fmt(p.PAID_AMOUNT)}` : "-"}</td>
                <td className="px-3 py-2.5 text-center">
                  {p.STATUS === "REQUESTED" ? (
                    <button onClick={() => onPay(p)} disabled={busy}
                      className="h-7 px-2 rounded bg-emerald-700 text-white text-[11px] font-bold disabled:opacity-50">
                      입금 처리
                    </button>
                  ) : <span className="text-[11px] text-slate-400">완료</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
