"use client";

import { useEffect, useState, FormEvent } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  PageHeader, PageLoader, EmptyState, Modal, Badge, TableShell,
  fmtKes, inputCls, btnPrimary, btnGhost, btnDanger, Field, Spinner,
} from "@/components/ui";

interface Invoice {
  id: number;
  invoiceNo: string;
  clientId: number;
  clientName: string;
  issueDate: string;
  dueDate: string;
  status: string;
  total: number;
  amountPaid: number;
}

interface ClientOpt { id: number; name: string }
interface Item { description: string; quantity: number; unitPrice: number }

export default function InvoicesPage() {
  const [rows, setRows] = useState<Invoice[] | null>(null);
  const [clients, setClients] = useState<ClientOpt[]>([]);
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [filter, setFilter] = useState("all");
  const router = useRouter();

  const today = new Date().toISOString().slice(0, 10);
  const in30 = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10);
  const [form, setForm] = useState({ clientId: "", issueDate: today, dueDate: in30, taxRate: 16, notes: "", status: "sent" });
  const [items, setItems] = useState<Item[]>([{ description: "", quantity: 1, unitPrice: 0 }]);

  useEffect(() => {
    fetch("/api/invoices").then((r) => r.json()).then(setRows);
    fetch("/api/clients").then((r) => r.json()).then((d) => setClients(d.map((c: { id: number; name: string }) => ({ id: c.id, name: c.name }))));
  }, []);

  const subtotal = items.reduce((s, it) => s + it.quantity * it.unitPrice, 0);
  const tax = subtotal * (form.taxRate / 100);

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const res = await fetch("/api/invoices", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, items: items.filter((i) => i.description.trim()) }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create invoice");
      setOpen(false);
      router.push(`/dashboard/invoices/${data.id}`);
    } catch (err) {
      setError((err as Error).message);
      setSaving(false);
    }
  };

  const remove = async (row: Invoice) => {
    if (!confirm(`Delete invoice ${row.invoiceNo}?`)) return;
    const prev = rows;
    setRows((r) => (r ?? []).filter((x) => x.id !== row.id));
    const res = await fetch(`/api/invoices/${row.id}`, { method: "DELETE" });
    if (!res.ok) setRows(prev);
  };

  const filtered = (rows ?? []).filter((r) => filter === "all" || r.status === filter);

  return (
    <div>
      <PageHeader
        title="Invoices"
        subtitle="Create, send and collect payment on invoices"
        action={<button onClick={() => { setError(""); setOpen(true); }} className={btnPrimary}>+ New invoice</button>}
      />

      <div className="mb-4 flex flex-wrap gap-2">
        {["all", "draft", "sent", "partial", "paid", "overdue"].map((s) => (
          <button
            key={s}
            onClick={() => setFilter(s)}
            className={`rounded-full px-3 py-1.5 text-xs font-medium capitalize transition ${
              filter === s ? "bg-blue-700 text-white" : "bg-white text-slate-600 ring-1 ring-slate-200 hover:bg-slate-50"
            }`}
          >
            {s}
          </button>
        ))}
      </div>

      {!rows ? (
        <PageLoader label="Loading invoices…" />
      ) : filtered.length === 0 ? (
        <EmptyState
          icon="🧾"
          title={filter === "all" ? "No invoices yet" : `No ${filter} invoices`}
          description="Create an invoice and collect payment via M-Pesa STK push."
          action={filter === "all" && <button onClick={() => setOpen(true)} className={btnPrimary}>+ New invoice</button>}
        />
      ) : (
        <TableShell head={["Invoice", "Client", "Issued", "Due", "Total", "Balance", "Status", ""]}>
          {filtered.map((r) => (
            <tr key={r.id} className="hover:bg-slate-50">
              <td className="px-4 py-3">
                <Link href={`/dashboard/invoices/${r.id}`} className="font-medium text-blue-700 hover:underline">
                  {r.invoiceNo}
                </Link>
              </td>
              <td className="max-w-[160px] truncate px-4 py-3 text-slate-600">{r.clientName}</td>
              <td className="whitespace-nowrap px-4 py-3 text-slate-500">{r.issueDate}</td>
              <td className="whitespace-nowrap px-4 py-3 text-slate-500">{r.dueDate}</td>
              <td className="whitespace-nowrap px-4 py-3 font-medium">{fmtKes(r.total)}</td>
              <td className="whitespace-nowrap px-4 py-3 text-amber-700">{fmtKes(Math.max(0, r.total - r.amountPaid))}</td>
              <td className="px-4 py-3"><Badge value={r.status} /></td>
              <td className="whitespace-nowrap px-4 py-3 text-right">
                <div className="flex justify-end gap-2">
                  <Link href={`/dashboard/invoices/${r.id}`} className={btnGhost}>Open</Link>
                  <button onClick={() => remove(r)} className={btnDanger}>Delete</button>
                </div>
              </td>
            </tr>
          ))}
        </TableShell>
      )}

      <Modal open={open} onClose={() => setOpen(false)} title="New invoice" wide>
        <form onSubmit={submit}>
          {error && <div className="mb-4 rounded-lg bg-rose-50 px-3 py-2 text-sm text-rose-700">{error}</div>}
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
            <Field label="Client *" className="lg:col-span-2">
              <select className={inputCls} required value={form.clientId} onChange={(e) => setForm({ ...form, clientId: e.target.value })}>
                <option value="">Select client…</option>
                {clients.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </Field>
            <Field label="Issue date"><input type="date" className={inputCls} value={form.issueDate} onChange={(e) => setForm({ ...form, issueDate: e.target.value })} /></Field>
            <Field label="Due date"><input type="date" className={inputCls} value={form.dueDate} onChange={(e) => setForm({ ...form, dueDate: e.target.value })} /></Field>
          </div>

          <p className="mb-2 mt-5 text-xs font-semibold uppercase tracking-wide text-slate-500">Line items</p>
          <div className="space-y-2">
            {items.map((it, i) => (
              <div key={i} className="grid grid-cols-12 gap-2">
                <input
                  className={`${inputCls} col-span-12 sm:col-span-6`}
                  placeholder="Description"
                  value={it.description}
                  onChange={(e) => setItems(items.map((x, j) => (j === i ? { ...x, description: e.target.value } : x)))}
                />
                <input
                  type="number" min={0} step="any"
                  className={`${inputCls} col-span-3 sm:col-span-2`}
                  placeholder="Qty"
                  value={it.quantity}
                  onChange={(e) => setItems(items.map((x, j) => (j === i ? { ...x, quantity: Number(e.target.value) } : x)))}
                />
                <input
                  type="number" min={0} step="any"
                  className={`${inputCls} col-span-6 sm:col-span-3`}
                  placeholder="Unit price"
                  value={it.unitPrice}
                  onChange={(e) => setItems(items.map((x, j) => (j === i ? { ...x, unitPrice: Number(e.target.value) } : x)))}
                />
                <button
                  type="button"
                  onClick={() => setItems(items.filter((_, j) => j !== i))}
                  disabled={items.length === 1}
                  className="col-span-3 rounded-lg text-rose-500 hover:bg-rose-50 disabled:opacity-30 sm:col-span-1"
                  aria-label="Remove line"
                >
                  ✕
                </button>
              </div>
            ))}
          </div>
          <button type="button" onClick={() => setItems([...items, { description: "", quantity: 1, unitPrice: 0 }])} className={`${btnGhost} mt-2`}>
            + Add line
          </button>

          <div className="mt-4 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
            <Field label="VAT rate (%)" className="sm:w-32">
              <input type="number" min={0} className={inputCls} value={form.taxRate} onChange={(e) => setForm({ ...form, taxRate: Number(e.target.value) })} />
            </Field>
            <div className="rounded-xl bg-slate-50 px-4 py-3 text-sm sm:text-right">
              <p className="text-slate-500">Subtotal: <span className="font-medium text-slate-800">{fmtKes(subtotal)}</span></p>
              <p className="text-slate-500">VAT: <span className="font-medium text-slate-800">{fmtKes(tax)}</span></p>
              <p className="mt-1 text-base font-bold text-slate-900">Total: {fmtKes(subtotal + tax)}</p>
            </div>
          </div>

          <div className="mt-6 flex justify-end gap-2">
            <button type="button" onClick={() => setOpen(false)} className={btnGhost}>Cancel</button>
            <button type="submit" disabled={saving} className={btnPrimary}>
              {saving && <Spinner className="h-4 w-4 text-white" />}
              {saving ? "Creating…" : "Create invoice"}
            </button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
