"use client";

import Link from "next/link";
import { useParams } from "next/navigation";
import { useState } from "react";
import { ArrowLeft, Mail, MessageSquare, Printer, Send } from "lucide-react";
import { api, useApi } from "@/lib/client";
import { Badge, Button, Card, useToast } from "@/components/ui";
import { formatDate, money } from "@/lib/utils";

interface InvoiceData {
  bill: {
    id: number;
    invoiceNo: string;
    period: string;
    billingDate: string;
    dueDate: string;
    expiryDate: string;
    status: string;
    notes: string | null;
  };
  customer: { name: string; customerCode: string; mobile: string; email: string | null; address: string | null };
  items: { id: number; label: string; quantity: string; unitPrice: string; amount: string }[];
  payments: { id: number; receiptNo: string; amount: string; methodName: string | null; paymentDate: string }[];
  totals: { gross: number; discount: number; total: number; paid: number; due: number };
  periodLabel: string;
  settings: Record<string, unknown>;
}

export default function InvoicePage() {
  const params = useParams<{ id: string }>();
  const toast = useToast();
  const { data, loading } = useApi<InvoiceData>(`/api/invoices/${params.id}`);
  const [busy, setBusy] = useState(false);

  if (loading && !data) return <div className="skeleton mx-auto my-10 h-[70vh] max-w-3xl rounded-2xl" />;
  if (!data) return <p className="p-10 text-center text-sm text-slate-400">Invoice not found.</p>;

  const s = data.settings;

  return (
    <div className="min-h-screen px-4 py-6 sm:px-8">
      <div className="no-print mx-auto mb-4 flex max-w-3xl flex-wrap items-center justify-between gap-2">
        <Link href="/admin/billing">
          <Button variant="secondary" size="sm" icon={<ArrowLeft className="h-4 w-4" />}>
            Back
          </Button>
        </Link>
        <div className="flex flex-wrap gap-2">
          <Button
            variant="secondary"
            size="sm"
            icon={<MessageSquare className="h-4 w-4" />}
            loading={busy}
            onClick={async () => {
              setBusy(true);
              try {
                const res = await api<{ sms: string; email: string }>(`/api/invoices/${params.id}`, { method: "POST" });
                toast.push(`SMS ${res.sms} · Email ${res.email}`, "success");
              } catch (err) {
                toast.push(err instanceof Error ? err.message : "Send failed", "error");
              } finally {
                setBusy(false);
              }
            }}
          >
            Send SMS / Email
          </Button>
          <Button size="sm" icon={<Printer className="h-4 w-4" />} onClick={() => window.print()}>
            Print / Save PDF
          </Button>
        </div>
      </div>

      <div className="print-area mx-auto max-w-3xl">
        <Card className="overflow-hidden">
          <div className="flex flex-wrap items-start justify-between gap-4 border-b border-white/10 bg-gradient-to-r from-brand-500/15 to-transparent p-6">
            <div className="flex items-center gap-3">
              <span className="grid h-12 w-12 place-items-center rounded-2xl bg-gradient-to-br from-brand-500 to-cyan-400 text-sm font-bold text-ink-950">IS</span>
              <div>
                <h1 className="text-lg font-bold text-slate-50">{String(s.isp_name ?? "ISP DIGITAL")}</h1>
                <p className="text-xs text-slate-400">{String(s.isp_legal_name ?? "")}</p>
                <p className="text-xs text-slate-500">{String(s.isp_address ?? "")}</p>
                <p className="text-xs text-slate-500">
                  {String(s.isp_phone ?? "")} · {String(s.isp_email ?? "")}
                </p>
              </div>
            </div>
            <div className="text-right">
              <p className="text-[11px] uppercase tracking-widest text-slate-500">Invoice</p>
              <p className="font-mono text-lg font-semibold text-slate-50">{data.bill.invoiceNo}</p>
              <Badge value={data.bill.status} />
            </div>
          </div>

          <div className="grid gap-6 p-6 sm:grid-cols-2">
            <div>
              <p className="text-[11px] uppercase tracking-wider text-slate-500">Billed to</p>
              <p className="mt-1 text-sm font-semibold text-slate-100">{data.customer.name}</p>
              <p className="text-xs text-slate-400">{data.customer.customerCode}</p>
              <p className="text-xs text-slate-400">{data.customer.mobile}</p>
              <p className="text-xs text-slate-400">{data.customer.email ?? "—"}</p>
              <p className="text-xs text-slate-400">{data.customer.address ?? "—"}</p>
            </div>
            <div className="text-right">
              <p className="text-[11px] uppercase tracking-wider text-slate-500">Billing period</p>
              <p className="text-sm text-slate-100">{data.periodLabel}</p>
              <p className="mt-2 text-[11px] uppercase tracking-wider text-slate-500">Billing date</p>
              <p className="text-sm text-slate-100">{formatDate(data.bill.billingDate)}</p>
              <p className="mt-2 text-[11px] uppercase tracking-wider text-slate-500">Due date</p>
              <p className="text-sm text-slate-100">{formatDate(data.bill.dueDate)}</p>
              <p className="mt-2 text-[11px] uppercase tracking-wider text-slate-500">Service expiry</p>
              <p className="text-sm text-slate-100">{formatDate(data.bill.expiryDate)}</p>
            </div>
          </div>

          <div className="px-6">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-white/10 text-left text-[11px] uppercase tracking-wider text-slate-500">
                  <th className="py-2">Description</th>
                  <th className="py-2 text-right">Qty</th>
                  <th className="py-2 text-right">Unit price</th>
                  <th className="py-2 text-right">Amount</th>
                </tr>
              </thead>
              <tbody>
                {data.items.map((item) => (
                  <tr key={item.id} className="border-b border-white/6">
                    <td className="py-2.5 text-slate-200">{item.label}</td>
                    <td className="py-2.5 text-right text-slate-300">{item.quantity}</td>
                    <td className="py-2.5 text-right text-slate-300">{money(item.unitPrice)}</td>
                    <td className="py-2.5 text-right text-slate-100">{money(item.amount)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="flex flex-wrap justify-end gap-6 p-6">
            <div className="w-full max-w-xs space-y-1.5 text-sm">
              <div className="flex justify-between text-slate-400">
                <span>Subtotal</span>
                <span>{money(data.totals.gross)}</span>
              </div>
              <div className="flex justify-between text-slate-400">
                <span>Discount</span>
                <span>- {money(data.totals.discount)}</span>
              </div>
              <div className="flex justify-between border-t border-white/10 pt-1.5 text-base font-semibold text-slate-50">
                <span>Total</span>
                <span>{money(data.totals.total)}</span>
              </div>
              <div className="flex justify-between text-emerald-300">
                <span>Paid</span>
                <span>{money(data.totals.paid)}</span>
              </div>
              <div className="flex justify-between border-t border-white/10 pt-1.5 text-base font-semibold text-rose-300">
                <span>Balance due</span>
                <span>{money(data.totals.due)}</span>
              </div>
            </div>
          </div>

          {data.payments.length ? (
            <div className="px-6 pb-6">
              <p className="mb-2 text-[11px] uppercase tracking-wider text-slate-500">Payment history</p>
              <ul className="space-y-1 text-xs text-slate-400">
                {data.payments.map((p) => (
                  <li key={p.id} className="flex justify-between">
                    <span>
                      <span className="font-mono">{p.receiptNo}</span> · {p.methodName ?? "—"} · {formatDate(p.paymentDate)}
                    </span>
                    <span className="text-emerald-300">{money(p.amount)}</span>
                  </li>
                ))}
              </ul>
            </div>
          ) : null}

          <div className="border-t border-white/10 p-6 text-[11px] text-slate-500">
            <p>{String(s.invoice_terms ?? "")}</p>
            <p className="mt-1">{String(s.invoice_footer ?? "Thank you for your business.")}</p>
            <p className="mt-3 flex items-center gap-1.5">
              <Mail className="h-3.5 w-3.5" /> Generated by ISP DIGITAL billing engine on {formatDate(new Date().toISOString())}
            </p>
          </div>
        </Card>
      </div>
    </div>
  );
}
