"use client";

import { useEffect, useState, useMemo, useCallback } from "react";
import Swal from "sweetalert2";
import { SearchableSelect } from "@/components/ui/searchable-select";
import { Loading } from "@/components/ui/loading";
import { makeSwalDraggable } from "@/lib/swal-draggable";

interface Proc {
  OBJID: string;
  PROC_NO: string;
  PROC_DATE: string;
  VENDOR_OBJID: string;
  VENDOR_NAME: string;
  VENDOR_CONTACT: string;
  TOTAL_AMOUNT: number;
  TOTAL_QTY: number;
  RECEIVED_QTY: number;
  RECEIVED_AMOUNT: number;
  PENDING_AMOUNT: number;
  STATUS: string;
  IS_PAID: boolean;
  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> = {
  OPEN: "작성중", REQUESTED: "발주요청", PARTIAL: "부분입고", RECEIVED: "입고완료", CANCELLED: "취소",
};
const STATUS_COLOR: Record<string, string> = {
  OPEN: "bg-slate-100 text-slate-600",
  REQUESTED: "bg-amber-100 text-amber-700",
  PARTIAL: "bg-sky-100 text-sky-700",
  RECEIVED: "bg-blue-100 text-blue-700",
  CANCELLED: "bg-rose-100 text-rose-600",
};

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 [payFilter, setPayFilter] = useState("");   // "" | PAID | UNPAID
  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,
        payStatus: payFilter || undefined,
      }),
    });
    setList((await res.json()).RESULTLIST ?? []);
  }, [from, to, vendorFilter, payFilter]);

  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.IS_PAID) { paid++; paidAmt += Number(p.PAID_AMOUNT || p.TOTAL_AMOUNT) || 0; }
      else           { requested++; requestedAmt += Number(p.TOTAL_AMOUNT) || 0; }
    }
    return { requested, requestedAmt, paid, paidAmt };
  }, [list]);

  const onPay = async (p: Proc) => {
    // 입금 금액 기본값 = 실제 입고된 만큼(입고금액). 부분입고면 미입고분 만큼 줄어든 금액이 제안됨.
    // 입고 전(RECEIVED_AMOUNT=0) 이면 발주금액으로 폴백.
    const suggested = Number(p.RECEIVED_AMOUNT) > 0 ? Number(p.RECEIVED_AMOUNT) : Number(p.TOTAL_AMOUNT);
    const result = await Swal.fire({
      title: "입금 처리",
      html: `
        <div class="text-left text-sm space-y-1">
          <div><b>발주번호</b> ${p.PROC_NO}</div>
          <div><b>공급업체</b> ${p.VENDOR_NAME ?? "-"}</div>
          <div><b>발주</b> ₩${fmt(p.TOTAL_AMOUNT)} <span class="text-slate-400">(${fmt(p.TOTAL_QTY)}개)</span></div>
          <div><b>입고</b> <span class="text-emerald-700">₩${fmt(p.RECEIVED_AMOUNT)}</span> <span class="text-slate-400">(${fmt(p.RECEIVED_QTY)}개)</span></div>
          <div><b>미입고</b> <span class="text-rose-600">₩${fmt(p.PENDING_AMOUNT)}</span></div>
        </div>
        <div class="mt-3 space-y-2 text-left">
          <input id="sw-amount"  class="swal2-input" placeholder="입금 금액 (기본=입고금액)" value="${suggested}" 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,
      didOpen: () => makeSwalDraggable(),
      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) || suggested, 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);
    }
  };

  // 입금완료(PAID) 건 수정 — 입금액/입금일/방법/메모 수정 또는 입금 취소
  const onEdit = async (p: Proc) => {
    const today = new Date().toISOString().slice(0, 10);
    const result = await Swal.fire({
      title: "입금 정보 수정",
      html: `
        <div class="text-left text-sm space-y-1">
          <div><b>발주번호</b> ${p.PROC_NO}</div>
          <div><b>공급업체</b> ${p.VENDOR_NAME ?? "-"}</div>
          <div><b>발주</b> ₩${fmt(p.TOTAL_AMOUNT)} <span class="text-slate-400">(${fmt(p.TOTAL_QTY)}개)</span></div>
          <div><b>입고</b> <span class="text-emerald-700">₩${fmt(p.RECEIVED_AMOUNT)}</span> <span class="text-slate-400">(${fmt(p.RECEIVED_QTY)}개)</span></div>
          <div><b>미입고</b> <span class="text-rose-600">₩${fmt(p.PENDING_AMOUNT)}</span></div>
        </div>
        <div class="mt-3 space-y-2 text-left">
          <label class="text-xs text-slate-500">입금일</label>
          <input id="sw-date"   class="swal2-input" type="date" value="${p.PAID_DATE || today}" />
          <label class="text-xs text-slate-500">입금 금액 (권장=입고금액)</label>
          <input id="sw-amount" class="swal2-input" type="number" value="${p.PAID_AMOUNT ?? (Number(p.RECEIVED_AMOUNT) > 0 ? Number(p.RECEIVED_AMOUNT) : Number(p.TOTAL_AMOUNT))}" />
          <input id="sw-method" class="swal2-input" placeholder="입금 방법 (예: 계좌이체)" value="${p.PAID_METHOD ?? ""}" />
          <input id="sw-memo"   class="swal2-input" placeholder="메모 (선택)" value="${p.PAID_MEMO ?? ""}" />
        </div>
      `,
      showCancelButton: true,
      showDenyButton: true,
      confirmButtonText: "저장",
      denyButtonText: "입금 취소",
      cancelButtonText: "닫기",
      confirmButtonColor: "#0f766e",
      denyButtonColor: "#dc2626",
      focusConfirm: false,
      didOpen: () => makeSwalDraggable(),
      preConfirm: () => ({
        paidDate: (document.getElementById("sw-date") as HTMLInputElement)?.value || undefined,
        amount: Number((document.getElementById("sw-amount") as HTMLInputElement)?.value) || Number(p.TOTAL_AMOUNT),
        method: (document.getElementById("sw-method") as HTMLInputElement)?.value,
        memo: (document.getElementById("sw-memo") as HTMLInputElement)?.value,
      }),
    });

    if (result.isConfirmed && result.value) {
      setBusy(true);
      try {
        const res = await fetch("/api/m/admin/proc-payments/update", {
          method: "POST", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ objid: p.OBJID, action: "edit", ...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); }
    } else if (result.isDenied) {
      const ok = await Swal.fire({
        icon: "warning", title: "입금을 취소하시겠습니까?",
        text: "입금완료를 해제하고 입금 정보를 지웁니다. (입고 진행 상태로 되돌아갑니다)",
        showCancelButton: true, confirmButtonText: "입금 취소", cancelButtonText: "닫기",
        confirmButtonColor: "#dc2626",
      });
      if (!ok.isConfirmed) return;
      setBusy(true);
      try {
        const res = await fetch("/api/m/admin/proc-payments/update", {
          method: "POST", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ objid: p.OBJID, action: "cancel" }),
        });
        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">
      {busy && <Loading message="저장 중..." />}
      <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={payFilter} onChange={(e) => setPayFilter(e.target.value)}
          className="h-8 px-2 rounded border border-slate-200 bg-white shrink-0">
          <option value="">결재 전체</option>
          <option value="UNPAID">미입금</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-bold text-base truncate">{p.VENDOR_NAME ?? "-"}</div>
                <div className="text-[11px] text-slate-500 flex items-center gap-1.5">
                  <span>{p.PROC_DATE}</span>
                  <span className="text-slate-300">·</span>
                  <span className="font-semibold text-slate-600">{p.PROC_NO}</span>
                </div>
              </div>
              <div className="flex flex-col items-end gap-1 shrink-0">
                <span className={`text-[10px] px-1.5 py-0.5 rounded font-semibold ${STATUS_COLOR[p.STATUS] ?? "bg-slate-100 text-slate-500"}`}>
                  {STATUS_LABEL[p.STATUS] || p.STATUS}
                </span>
                <span className={`text-[10px] px-1.5 py-0.5 rounded font-bold ${p.IS_PAID ? "bg-emerald-100 text-emerald-700" : "bg-rose-100 text-rose-600"}`}>
                  {p.IS_PAID ? "입금완료" : "미입금"}
                </span>
              </div>
            </div>
            <div className="grid grid-cols-3 gap-2 text-[11px] py-1.5 mb-2 border-t border-slate-100">
              <div>
                <div className="text-slate-400">발주</div>
                <div className="font-bold tabular-nums">₩{fmt(p.TOTAL_AMOUNT)}</div>
                <div className="text-[10px] text-slate-400 tabular-nums">{fmt(p.TOTAL_QTY)}개</div>
              </div>
              <div>
                <div className="text-emerald-700/80">입고</div>
                <div className="font-bold text-emerald-700 tabular-nums">₩{fmt(p.RECEIVED_AMOUNT)}</div>
                <div className="text-[10px] text-emerald-700/70 tabular-nums">{fmt(p.RECEIVED_QTY)}개</div>
              </div>
              <div>
                <div className="text-rose-600/80">미입고</div>
                <div className={`font-bold tabular-nums ${Number(p.PENDING_AMOUNT) > 0 ? "text-rose-600" : "text-slate-300"}`}>₩{fmt(p.PENDING_AMOUNT)}</div>
                <div className="text-[10px] text-rose-600/70 tabular-nums">{fmt(Number(p.TOTAL_QTY) - Number(p.RECEIVED_QTY))}개</div>
              </div>
            </div>
            {!p.IS_PAID ? (
              <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="flex items-center justify-between gap-2">
                <div className="text-[11px] text-emerald-700 min-w-0 truncate">
                  입금일 {p.PAID_DATE} · ₩{fmt(p.PAID_AMOUNT)} {p.PAID_METHOD && `· ${p.PAID_METHOD}`}
                </div>
                <button onClick={() => onEdit(p)} disabled={busy}
                  className="shrink-0 h-7 px-2 rounded border border-slate-300 bg-white text-slate-600 text-[11px] font-bold disabled:opacity-50">수정</button>
              </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-1.5">발주번호</th>
              <th className="text-left px-3 py-1.5">발주일</th>
              <th className="text-left px-3 py-1.5">공급업체</th>
              <th className="text-right px-3 py-1.5">발주</th>
              <th className="text-right px-3 py-1.5 text-emerald-700">입고</th>
              <th className="text-right px-3 py-1.5 text-rose-600">미입고</th>
              <th className="text-center px-3 py-1.5">진행상태</th>
              <th className="text-center px-3 py-1.5">결재상태</th>
              <th className="text-left px-3 py-1.5">입금일</th>
              <th className="text-right px-3 py-1.5">입금액</th>
              <th className="text-center px-3 py-2.5 w-[120px]">동작</th>
            </tr>
          </thead>
          <tbody>
            {list.length === 0 ? (
              <tr><td colSpan={11} 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-1.5">{p.PROC_DATE}</td>
                <td className="px-3 py-1.5">{p.VENDOR_NAME ?? "-"}</td>
                <td className="px-3 py-2.5 text-right tabular-nums">
                  <div className="font-bold text-slate-800 text-sm">₩{fmt(p.TOTAL_AMOUNT)}</div>
                  <div className="text-[11px] text-slate-400">{fmt(p.TOTAL_QTY)}개</div>
                </td>
                <td className="px-3 py-2.5 text-right tabular-nums">
                  <div className="font-bold text-emerald-700 text-sm">₩{fmt(p.RECEIVED_AMOUNT)}</div>
                  <div className="text-[11px] text-emerald-700/70">{fmt(p.RECEIVED_QTY)}개</div>
                </td>
                <td className="px-3 py-2.5 text-right tabular-nums">
                  <div className={`font-bold text-sm ${Number(p.PENDING_AMOUNT) > 0 ? "text-rose-600" : "text-slate-300"}`}>₩{fmt(p.PENDING_AMOUNT)}</div>
                  <div className={`text-[11px] ${Number(p.PENDING_AMOUNT) > 0 ? "text-rose-600/70" : "text-slate-300"}`}>{fmt(Number(p.TOTAL_QTY) - Number(p.RECEIVED_QTY))}개</div>
                </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] ?? "bg-slate-100 text-slate-500"}`}>
                    {STATUS_LABEL[p.STATUS] || p.STATUS}
                  </span>
                </td>
                <td className="px-3 py-2.5 text-center">
                  <span className={`text-[10px] px-1.5 py-0.5 rounded font-bold ${p.IS_PAID ? "bg-emerald-100 text-emerald-700" : "bg-rose-100 text-rose-600"}`}>
                    {p.IS_PAID ? "입금완료" : "미입금"}
                  </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.IS_PAID ? (
                    <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>
                  ) : (
                    <button onClick={() => onEdit(p)} disabled={busy}
                      className="h-7 px-2 rounded border border-slate-300 bg-white text-slate-600 text-[11px] font-bold hover:bg-slate-50 disabled:opacity-50">
                      수정
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
