"use client";

import { useEffect, useState, useCallback, useMemo } from "react";
import { FileText, Send, Download, RefreshCcw, AlertCircle } from "lucide-react";
import Swal from "sweetalert2";
import { downloadXlsx } from "@/lib/xlsx-export";
import { SearchableSelect } from "@/components/ui/searchable-select";

interface Einvoice {
  OBJID: string;
  ORDER_OBJID: string | null;
  CUSTOMER_OBJID: string;
  BUYER_NAME: string;
  INVOICE_KIND: "TAX" | "TAXFREE";
  INVOICE_TYPE: "NORMAL" | "MODIFIED" | "CANCELED";
  ISSUE_METHOD: "NTS" | "POPBILL" | "MANUAL";
  ISSUE_DATE: string;
  TOTAL_SUPPLY: number;
  TOTAL_VAT: number;
  TOTAL_AMOUNT: number;
  NTS_INVOICE_NO: string | null;
  NTS_RESPONSE_CODE: string | null;
  NTS_RESPONSE_MSG: string | null;
  STATUS: string;
  REGDATE: string;
}

interface PendingOrder {
  OBJID: string;
  ORDER_NO: string;
  ORDER_DATE: string;
  COMPANY_NAME: string;
  TOTAL_AMOUNT: number;
  STATUS: string;
}

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

const STATUS_LABEL: Record<string, string> = {
  DRAFT: "작성중", QUEUED: "전송대기", SENT: "전송완료", ACK: "승인완료", FAIL: "실패", CANCELED: "취소",
};
const STATUS_COLOR: Record<string, string> = {
  DRAFT:   "bg-slate-100 text-slate-600",
  QUEUED:  "bg-amber-100 text-amber-700",
  SENT:    "bg-blue-100 text-blue-700",
  ACK:     "bg-emerald-100 text-emerald-700",
  FAIL:    "bg-rose-100 text-rose-700",
  CANCELED:"bg-slate-100 text-slate-500",
};

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

interface Customer { USER_ID: string; USER_NAME: string }

export default function EinvoicesPage() {
  const [[from, to], setRange] = useState(defaultRange());
  const [statusFilter, setStatusFilter] = useState("");
  const [customerFilter, setCustomerFilter] = useState("");
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [list, setList] = useState<Einvoice[]>([]);
  const [pending, setPending] = useState<PendingOrder[]>([]);
  const [busy, setBusy] = useState(false);

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

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

  // 면세/과세/합계 합산
  const summary = useMemo(() => {
    let taxFreeAmount = 0, taxableSupply = 0, taxableVat = 0, total = 0;
    for (const e of list) {
      total += Number(e.TOTAL_AMOUNT) || 0;
      if (e.INVOICE_KIND === "TAXFREE") {
        taxFreeAmount += Number(e.TOTAL_SUPPLY) || 0;
      } else {
        taxableSupply += Number(e.TOTAL_SUPPLY) || 0;
        taxableVat    += Number(e.TOTAL_VAT) || 0;
      }
    }
    return { taxFreeAmount, taxableSupply, taxableVat, taxableTotal: taxableSupply + taxableVat, total };
  }, [list]);

  const loadPending = useCallback(async () => {
    // 발주 + 발행이력 동시 조회 후 이미 발행된 건은 제외
    const [ordersRes, invRes] = await Promise.all([
      fetch("/api/m/orders/list", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }),
      fetch("/api/m/einvoices/list", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }),
    ]);
    const orders: PendingOrder[] = (await ordersRes.json()).RESULTLIST ?? [];
    const invoices: Einvoice[] = (await invRes.json()).RESULTLIST ?? [];
    // FAIL/CANCELED 가 아닌 발행이 있으면 그 발주는 제외
    const issuedOrderIds = new Set(
      invoices
        .filter((e) => e.ORDER_OBJID && !["FAIL", "CANCELED"].includes(e.STATUS))
        .map((e) => e.ORDER_OBJID as string)
    );
    setPending(orders.filter((o) =>
      ["APPROVED", "SHIPPED", "PAID"].includes(o.STATUS) && !issuedOrderIds.has(o.OBJID)
    ));
  }, []);

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

  const issueFromOrder = async (orderObjid: string, kind: "TAX" | "TAXFREE" = "TAX") => {
    const ok = await Swal.fire({
      icon: "question",
      title: `${kind === "TAX" ? "세금계산서" : "계산서(면세)"} 발행`,
      text: "선택한 발주에 대해 전자세금계산서를 발행하시겠습니까?",
      showCancelButton: true,
      confirmButtonText: "발행",
      cancelButtonText: "취소",
      confirmButtonColor: "#0f766e",
    });
    if (!ok.isConfirmed) return;
    setBusy(true);
    try {
      const res = await fetch("/api/m/einvoices/issue", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ orderObjid, invoiceKind: kind, invoiceType: "NORMAL" }),
      });
      const j = await res.json();
      if (j.success) {
        await Swal.fire({
          icon: "success",
          title: "발행 완료",
          html: `
            <div class="text-sm">
              <div>승인번호: <b>${j.ntsInvoiceNo ?? "-"}</b></div>
              <div>상태: ${j.status}</div>
              <div>처리방식: ${j.provider}</div>
              ${j.message ? `<div class="text-xs text-slate-500 mt-2">${j.message}</div>` : ""}
            </div>`,
        });
        load();
      } else {
        Swal.fire({ icon: "error", title: "발행 실패", text: j.message ?? "오류" });
      }
    } finally { setBusy(false); }
  };

  const onExport = () => {
    if (list.length === 0) return;
    downloadXlsx("전자세금계산서_발행이력", list, [
      { header: "발행일",     key: "ISSUE_DATE",      width: 12 },
      { header: "거래처",     key: "BUYER_NAME",      width: 24 },
      { header: "구분",       key: (r) => r.INVOICE_KIND === "TAX" ? "세금계산서" : "계산서", width: 12 },
      { header: "유형",       key: (r) => r.INVOICE_TYPE,           width: 10 },
      { header: "처리방식",   key: "ISSUE_METHOD",    width: 10 },
      { header: "공급가",     key: (r) => Number(r.TOTAL_SUPPLY),   width: 14 },
      { header: "세액",       key: (r) => Number(r.TOTAL_VAT),      width: 12 },
      { header: "합계",       key: (r) => Number(r.TOTAL_AMOUNT),   width: 14 },
      { header: "승인번호",   key: "NTS_INVOICE_NO",  width: 30 },
      { header: "상태",       key: (r) => STATUS_LABEL[r.STATUS] ?? r.STATUS, width: 10 },
    ]);
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <h1 className="text-xl sm:text-2xl font-bold text-slate-900">전자세금계산서 발행</h1>
          <p className="text-xs text-slate-500 mt-0.5">출고/입금 완료된 발주에 대해 전자(세금)계산서를 발행하고 이력을 관리합니다.</p>
        </div>
        <div className="flex gap-2">
          <button onClick={() => { load(); loadPending(); }} className="inline-flex items-center gap-1.5 h-9 px-3 rounded-lg border border-slate-200 text-xs font-bold hover:bg-slate-50">
            <RefreshCcw size={14} /> 새로고침
          </button>
          <button onClick={onExport} disabled={list.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>

      {/* 안내 배너 — STUB 모드 */}
      <div className="border border-amber-200 bg-amber-50 rounded-lg p-3 flex items-start gap-2 text-xs text-amber-900">
        <AlertCircle size={14} className="mt-0.5 shrink-0" />
        <div>
          <b>국세청 직접 연동 어댑터 골격만 구현된 상태</b> — 현재 발행은 DB 기록만 됩니다.
          실제 국세청 전송은 (1) 사업자용 공동인증서 발급, (2) 홈택스 ERP 연계 신청 승인, (3) <code>NTS_ESERO_MODE</code> 환경변수를 <code>test</code>/<code>prod</code> 로 설정 후 활성화됩니다.
        </div>
      </div>

      {/* 발행 가능 발주 (출고/입금 완료) */}
      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="px-4 py-2.5 bg-slate-50 border-b border-slate-200 text-sm font-bold text-slate-700 flex items-center gap-2">
          <FileText size={14} /> 발행 가능 발주 ({pending.length}건)
          <span className="text-xs font-normal text-slate-500">— 출고완료 / 입금완료 상태</span>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-xs min-w-[600px]">
            <thead className="bg-slate-50 text-slate-600">
              <tr>
                <th className="text-left px-3 py-2">발주번호</th>
                <th className="text-left px-3 py-2">발주일</th>
                <th className="text-left px-3 py-2">거래처</th>
                <th className="text-right px-3 py-2">합계</th>
                <th className="text-center px-3 py-2">상태</th>
                <th className="text-right px-3 py-2 w-[180px]">발행</th>
              </tr>
            </thead>
            <tbody>
              {pending.length === 0 ? (
                <tr><td colSpan={6} className="text-center py-8 text-slate-400">발행 가능한 발주가 없습니다.</td></tr>
              ) : pending.map((o) => (
                <tr key={o.OBJID} className="border-t border-slate-100">
                  <td className="px-3 py-2 font-semibold">{o.ORDER_NO}</td>
                  <td className="px-3 py-2">{o.ORDER_DATE}</td>
                  <td className="px-3 py-2">{o.COMPANY_NAME}</td>
                  <td className="px-3 py-2 text-right tabular-nums font-bold">₩{fmt(o.TOTAL_AMOUNT)}</td>
                  <td className="px-3 py-2 text-center text-[11px] text-slate-500">{o.STATUS}</td>
                  <td className="px-3 py-2 text-right">
                    <button
                      onClick={() => issueFromOrder(o.OBJID, "TAX")}
                      disabled={busy}
                      className="inline-flex items-center gap-1 h-7 px-2.5 rounded bg-emerald-700 text-white text-[11px] font-bold hover:bg-emerald-800 disabled:opacity-50"
                    >
                      <Send size={11} /> 세금계산서
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 발행 이력 */}
      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="px-4 py-2.5 bg-slate-50 border-b border-slate-200 text-sm font-bold text-slate-700 flex flex-wrap items-center gap-2 justify-between">
          <span>발행 이력 ({list.length}건)</span>
          <div className="flex gap-2 items-center text-xs font-normal flex-wrap">
            <input type="date" value={from} onChange={(e) => setRange([e.target.value, to])}
              className="h-8 px-2 rounded border border-slate-200" />
            <span className="text-slate-400">~</span>
            <input type="date" value={to} onChange={(e) => setRange([from, e.target.value])}
              className="h-8 px-2 rounded border border-slate-200" />
            <div className="min-w-[180px]">
              <SearchableSelect
                options={[{ value: "", label: "전체 거래처" }, ...customers.map((c) => ({ value: c.USER_ID, label: c.USER_NAME }))]}
                value={customerFilter}
                onChange={setCustomerFilter}
                placeholder="거래처"
              />
            </div>
            <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}
              className="h-8 px-2 rounded border border-slate-200 bg-white">
              <option value="">전체 상태</option>
              {Object.entries(STATUS_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
            </select>
            <button onClick={load} className="h-8 px-3 rounded bg-slate-800 text-white text-xs font-semibold">조회</button>
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-xs min-w-[800px]">
            <thead className="bg-slate-50 text-slate-600">
              <tr>
                <th className="text-left px-3 py-2">발행일</th>
                <th className="text-left px-3 py-2">거래처</th>
                <th className="text-center px-3 py-2">구분</th>
                <th className="text-center px-3 py-2">처리</th>
                <th className="text-right px-3 py-2">공급가</th>
                <th className="text-right px-3 py-2">세액</th>
                <th className="text-right px-3 py-2">합계</th>
                <th className="text-left px-3 py-2">승인번호</th>
                <th className="text-center px-3 py-2">상태</th>
              </tr>
            </thead>
            <tbody>
              {list.length === 0 ? (
                <tr><td colSpan={9} className="text-center py-8 text-slate-400">발행 이력이 없습니다.</td></tr>
              ) : list.map((e) => (
                <tr key={e.OBJID} className="border-t border-slate-100">
                  <td className="px-3 py-2">{e.ISSUE_DATE}</td>
                  <td className="px-3 py-2 font-semibold">{e.BUYER_NAME}</td>
                  <td className="px-3 py-2 text-center">
                    <span className={`text-[10px] px-1.5 py-0.5 rounded font-bold ${e.INVOICE_KIND === "TAX" ? "bg-rose-100 text-rose-700" : "bg-violet-100 text-violet-700"}`}>
                      {e.INVOICE_KIND === "TAX" ? "세금" : "면세"}
                    </span>
                  </td>
                  <td className="px-3 py-2 text-center text-[11px] text-slate-500">{e.ISSUE_METHOD}</td>
                  <td className="px-3 py-2 text-right tabular-nums">{fmt(e.TOTAL_SUPPLY)}</td>
                  <td className="px-3 py-2 text-right tabular-nums">{fmt(e.TOTAL_VAT)}</td>
                  <td className="px-3 py-2 text-right tabular-nums font-bold">₩{fmt(e.TOTAL_AMOUNT)}</td>
                  <td className="px-3 py-2 font-mono text-[10px] text-slate-600">{e.NTS_INVOICE_NO || "-"}</td>
                  <td className="px-3 py-2 text-center">
                    <span className={`text-[10px] px-1.5 py-0.5 rounded font-semibold ${STATUS_COLOR[e.STATUS] ?? "bg-slate-100 text-slate-500"}`}>
                      {STATUS_LABEL[e.STATUS] ?? e.STATUS}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
            {list.length > 0 && (
              <tfoot className="bg-slate-50 border-t-2 border-slate-300 font-bold text-[11px]">
                <tr>
                  <td colSpan={4} className="px-3 py-2 text-right text-slate-600">면세 합계</td>
                  <td className="px-3 py-2 text-right tabular-nums text-violet-700" colSpan={3}>₩{fmt(summary.taxFreeAmount)}</td>
                  <td colSpan={2}></td>
                </tr>
                <tr>
                  <td colSpan={4} className="px-3 py-2 text-right text-slate-600">과세 합계 (공급가 + 세액)</td>
                  <td className="px-3 py-2 text-right tabular-nums text-rose-700">₩{fmt(summary.taxableSupply)}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-rose-700">₩{fmt(summary.taxableVat)}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-rose-700">₩{fmt(summary.taxableTotal)}</td>
                  <td colSpan={2}></td>
                </tr>
                <tr className="border-t border-slate-300">
                  <td colSpan={4} className="px-3 py-2 text-right text-slate-700">총 합계</td>
                  <td colSpan={3} className="px-3 py-2 text-right tabular-nums text-emerald-700 text-sm">₩{fmt(summary.total)}</td>
                  <td colSpan={2}></td>
                </tr>
              </tfoot>
            )}
          </table>
        </div>
      </div>
    </div>
  );
}
