"use client";

import { useEffect, useState } from "react";
import { CYCLE_OPTIONS, cycleLabel, formatVND } from "@/lib/finance";
import { CurrencyInput } from "@/components/CurrencyInput";

const STATUS_LABEL: Record<string, string> = {
  OPEN: "Đang mở",
  PARTIAL: "Thu/trả một phần",
  COLLECTED: "Đã thu",
  PAID: "Đã trả",
  WRITTEN_OFF: "Xoá nợ",
};

export default function DebtsPage() {
  const [debts, setDebts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState({
    scope: "BUSINESS",
    type: "RECEIVABLE",
    counterparty: "",
    amount: "",
    dueDate: "",
    probability: "0.7",
    isInstallment: false,
    interestRate: "",
    paymentAmount: "",
    paymentCycle: "MONTHLY",
  });

  async function load() {
    setLoading(true);
    const res = await fetch("/api/debts");
    const json = await res.json();
    setDebts(json.debts);
    setLoading(false);
  }

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

  async function createDebt() {
    if (!form.counterparty || !form.amount || !form.dueDate) return;
    await fetch("/api/debts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        scope: form.scope,
        type: form.type,
        counterparty: form.counterparty,
        amount: Number(form.amount),
        dueDate: new Date(form.dueDate).toISOString(),
        probability: Number(form.probability),
        isInstallment: form.isInstallment,
        interestRate: form.isInstallment && form.interestRate ? Number(form.interestRate) : undefined,
        paymentAmount: form.isInstallment && form.paymentAmount ? Number(form.paymentAmount) : undefined,
        paymentCycle: form.isInstallment ? form.paymentCycle : undefined,
      }),
    });
    setForm({ ...form, counterparty: "", amount: "", dueDate: "", interestRate: "", paymentAmount: "" });
    load();
  }

  async function updateStatus(id: string, status: string) {
    await fetch(`/api/debts/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    });
    load();
  }

  return (
    <div>
      <div className="border-b border-slate-100 bg-white px-8 py-5">
        <h1 className="text-2xl font-extrabold text-slate-800">Công nợ phải thu / phải trả</h1>
        <p className="text-sm text-slate-400">Nguồn dữ liệu cho hành động #1 (thu công nợ cũ), #6 (hoãn chi) và dự báo dòng tiền.</p>
      </div>

      <div className="flex flex-col gap-6 p-8">
        <div className="card flex flex-col gap-3 p-5">
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-6">
            <select value={form.scope} onChange={(e) => setForm({ ...form, scope: e.target.value })} className="rounded-lg border border-slate-200 px-3 py-2 text-sm">
              <option value="PERSONAL">Cá nhân</option>
              <option value="BUSINESS">Doanh nghiệp</option>
            </select>
            <select value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })} className="rounded-lg border border-slate-200 px-3 py-2 text-sm">
              <option value="RECEIVABLE">Phải thu</option>
              <option value="PAYABLE">Phải trả</option>
            </select>
            <input
              placeholder="Đối tác / chủ nợ"
              value={form.counterparty}
              onChange={(e) => setForm({ ...form, counterparty: e.target.value })}
              className="rounded-lg border border-slate-200 px-3 py-2 text-sm"
            />
            <CurrencyInput
              placeholder="Tổng dư nợ"
              value={form.amount}
              onChange={(v) => setForm({ ...form, amount: v })}
              className="rounded-lg border border-slate-200 px-3 py-2 text-sm"
            />
            <input type="date" value={form.dueDate} onChange={(e) => setForm({ ...form, dueDate: e.target.value })} className="rounded-lg border border-slate-200 px-3 py-2 text-sm" />
            <button onClick={createDebt} className="rounded-lg bg-teal-500 px-4 py-2 text-sm font-semibold text-white hover:bg-teal-600">
              + Thêm công nợ
            </button>
          </div>

          <label className="flex items-center gap-2 text-xs font-medium text-slate-600">
            <input type="checkbox" checked={form.isInstallment} onChange={(e) => setForm({ ...form, isInstallment: e.target.checked })} />
            Khoản vay trả góp (có gốc/lãi, lịch trả riêng)
          </label>

          {form.isInstallment && (
            <div className="grid grid-cols-1 gap-3 rounded-lg bg-slate-50 p-3 sm:grid-cols-3">
              <label className="text-xs text-slate-500">
                Lãi suất (%/năm, tuỳ chọn)
                <input
                  type="number"
                  step="0.1"
                  value={form.interestRate}
                  onChange={(e) => setForm({ ...form, interestRate: e.target.value })}
                  className="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                />
              </label>
              <label className="text-xs text-slate-500">
                Số tiền trả mỗi kỳ
                <CurrencyInput
                  value={form.paymentAmount}
                  onChange={(v) => setForm({ ...form, paymentAmount: v })}
                  className="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                />
              </label>
              <label className="text-xs text-slate-500">
                Chu kỳ trả
                <select
                  value={form.paymentCycle}
                  onChange={(e) => setForm({ ...form, paymentCycle: e.target.value })}
                  className="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                >
                  {CYCLE_OPTIONS.filter((c) => c.value !== "ONCE").map((c) => (
                    <option key={c.value} value={c.value}>
                      {c.label}
                    </option>
                  ))}
                </select>
              </label>
            </div>
          )}
        </div>

        <div className="card overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 text-xs uppercase text-slate-400">
              <tr>
                <th className="px-4 py-3 text-left">Đối tác</th>
                <th className="px-4 py-3 text-left">Loại</th>
                <th className="px-4 py-3 text-left">Phạm vi</th>
                <th className="px-4 py-3 text-left">Số tiền còn lại</th>
                <th className="px-4 py-3 text-left">Hạn</th>
                <th className="px-4 py-3 text-left">Lịch trả góp</th>
                <th className="px-4 py-3 text-left">Xác suất</th>
                <th className="px-4 py-3 text-left">Trạng thái</th>
              </tr>
            </thead>
            <tbody>
              {!loading &&
                debts.map((d) => {
                  const daysLeft = Math.ceil((new Date(d.dueDate).getTime() - Date.now()) / 86400000);
                  return (
                    <tr key={d.id} className="border-t border-slate-50">
                      <td className="px-4 py-3 font-medium text-slate-700">{d.counterparty}</td>
                      <td className="px-4 py-3">{d.type === "RECEIVABLE" ? "Phải thu" : "Phải trả"}</td>
                      <td className="px-4 py-3 text-slate-500">{d.scope === "PERSONAL" ? "Cá nhân" : "Doanh nghiệp"}</td>
                      <td className="px-4 py-3 font-semibold">{formatVND(d.amount - d.collectedAmt)}</td>
                      <td className="px-4 py-3 text-slate-500">
                        <div>{new Date(d.dueDate).toLocaleDateString("vi-VN")}</div>
                        {d.status !== "COLLECTED" && d.status !== "PAID" && d.status !== "WRITTEN_OFF" && (
                          <div className={`text-[11px] ${daysLeft < 0 ? "text-rose-500" : daysLeft <= 3 ? "text-amber-500" : "text-slate-400"}`}>
                            {daysLeft < 0 ? `Quá hạn ${Math.abs(daysLeft)} ngày` : `Còn ${daysLeft} ngày`}
                          </div>
                        )}
                      </td>
                      <td className="px-4 py-3 text-slate-500">
                        {d.isInstallment ? (
                          <div className="text-xs">
                            <div>{d.paymentAmount ? formatVND(d.paymentAmount) : "—"} / {d.paymentCycle ? cycleLabel(d.paymentCycle) : "—"}</div>
                            {d.interestRate ? <div className="text-slate-400">Lãi {d.interestRate}%/năm</div> : null}
                          </div>
                        ) : (
                          "—"
                        )}
                      </td>
                      <td className="px-4 py-3 text-slate-500">{Math.round(d.probability * 100)}%</td>
                      <td className="px-4 py-3">
                        <select value={d.status} onChange={(e) => updateStatus(d.id, e.target.value)} className="rounded-lg border border-slate-200 px-2 py-1 text-xs">
                          {Object.entries(STATUS_LABEL).map(([k, v]) => (
                            <option key={k} value={k}>
                              {v}
                            </option>
                          ))}
                        </select>
                      </td>
                    </tr>
                  );
                })}
              {!loading && debts.length === 0 && (
                <tr>
                  <td colSpan={8} className="px-4 py-6 text-center text-sm text-slate-400">
                    Chưa có công nợ nào.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
