"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import { apiGet, apiPost } from "@/lib/api";
import type { Load } from "@/types";
import { PageHeader } from "@/components/ui/page-header";
import { getInvoiceDate, getInvoiceLineItems, getInvoiceNumber, getInvoiceTotal, hasInvoiceRecord } from "@/src/modules/loads/invoice";
import { LoadBillingReadinessPanel } from "@/components/loads-billing-readiness-panel";
import { LoadsDocumentCompliancePanel } from "@/components/loads-document-compliance-panel";
import { LoadsDocumentIntakePanel } from "@/components/loads-document-intake-panel";
import { LoadDocumentAccessPanel } from "@/components/load-document-access-panel";
import { appendReturnTo, resolveReturnTo } from "@/src/modules/loads/load-navigation";

function money(value?: string | null) {
  if (!value) return "-";
  const num = Number(value);
  if (Number.isNaN(num)) return value;
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(num);
}

function formatDate(value?: string | null) {
  if (!value) return "-";
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString();
}

function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="rounded-2xl border bg-white p-6 shadow-sm print:shadow-none print:border-gray-300">
      <h3 className="mb-4 text-base font-semibold">{title}</h3>
      {children}
    </section>
  );
}

export default function LoadInvoicePage() {
  const params = useParams<{ id: string }>();
  const searchParams = useSearchParams();
  const requestedReturnTo = searchParams.get("returnTo");
  const resolvedReturnTo = resolveReturnTo(requestedReturnTo, "/loads");
  const [load, setLoad] = useState<Load | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [working, setWorking] = useState(false);

  async function loadRecord() {
    if (!params?.id) return;
    try {
      setError(null);
      const data = await apiGet<{ load: Load }>(`/api/loads/${params.id}`);
      setLoad(data.load);
    } catch (err: any) {
      setError(err?.message ?? "Failed to load invoice");
    }
  }

  useEffect(() => {
    loadRecord();
  }, [params?.id]);

  const invoiceNumber = useMemo(() => getInvoiceNumber(load), [load]);
  const invoiceDate = useMemo(() => getInvoiceDate(load), [load]);
  const lineItems = useMemo(() => getInvoiceLineItems(load), [load]);
  const invoiceTotal = useMemo(() => getInvoiceTotal(load), [load]);
  const invoiceExists = useMemo(() => hasInvoiceRecord(load), [load]);

  async function createInvoiceRecord() {
    if (!load) return;
    try {
      setWorking(true);
      setError(null);
      if (!invoiceExists) {
        await apiPost(`/api/loads/${load.id}/payments`, {
          paymentStatus: "UNPAID",
          invoiceNumber,
          invoiceDate,
          amountDue: invoiceTotal,
          amountPaid: "",
          paymentReference: "",
          notesText: "Invoice generated from load record.",
        });
      }
      if (load.status !== "INVOICED" && load.status !== "PAID_FULL") {
        await apiPost(`/api/loads/${load.id}/status`, {
          status: "INVOICED",
          note: `Invoice ${invoiceNumber} generated`,
        });
      }
      await loadRecord();
    } catch (err: any) {
      setError(err?.message ?? "Failed to create invoice record");
    } finally {
      setWorking(false);
    }
  }

  if (error) return <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>;
  if (!load) return <div className="text-sm text-gray-500">Loading invoice...</div>;

  return (
    <div className="space-y-6 print:space-y-4">
      <PageHeader
        title={`Invoice ${invoiceNumber}`}
        subtitle="Review the invoice, save the invoice record, then print or save as PDF."
        action={
          <div className="flex gap-2 print:hidden">
            <Link href={requestedReturnTo ? resolvedReturnTo : appendReturnTo(`/loads/${load.id}`, requestedReturnTo)} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium">{requestedReturnTo ? "Return to queue" : "Back to load"}</Link>
            <button onClick={createInvoiceRecord} disabled={working} className="rounded-xl border bg-white px-4 py-2 text-sm font-medium disabled:opacity-60">
              {working ? "Working..." : invoiceExists ? "Update invoice record" : "Save invoice record"}
            </button>
            <button onClick={() => window.print()} className="rounded-xl bg-black px-4 py-2 text-sm font-medium text-white">Print / Save PDF</button>
          </div>
        }
      />

      <details className="rounded-2xl border bg-white p-5 shadow-sm print:hidden">
        <summary className="cursor-pointer list-none text-sm font-semibold text-slate-900">Show invoice checks</summary>
        <p className="mt-1 text-sm text-slate-500">Open these only when you need to check billing or paperwork before sending the invoice.</p>
        <div className="mt-5 grid gap-6 xl:grid-cols-2">
          <LoadBillingReadinessPanel load={load} />
          <LoadsDocumentCompliancePanel load={load} />
        </div>
        <div className="mt-6 space-y-6">
          <LoadsDocumentIntakePanel
            load={load}
            editHref={appendReturnTo(`/loads/${load.id}/edit`, requestedReturnTo)}
            invoiceHref={appendReturnTo(`/loads/${load.id}/invoice`, requestedReturnTo)}
          />
          <LoadDocumentAccessPanel load={load} />
        </div>
      </details>

      <section className="rounded-2xl border bg-white p-8 shadow-sm print:shadow-none print:border-gray-300">
        <div className="flex flex-col gap-8 md:flex-row md:items-start md:justify-between">
          <div>
            <div className="text-2xl font-semibold tracking-tight">{load.organization?.name || "Your Company"}</div>
            <div className="mt-2 text-sm text-gray-600">Invoice issuer / billing entity</div>
            <div className="mt-1 text-xs text-gray-500">Powered by Dispatch Spot</div>
          </div>
          <div className="text-sm md:text-right">
            <div><span className="font-medium">Invoice #:</span> {invoiceNumber}</div>
            <div><span className="font-medium">Invoice date:</span> {formatDate(invoiceDate)}</div>
            <div><span className="font-medium">Load ref:</span> {load.referenceNumber || load.id.slice(0, 8)}</div>
            <div><span className="font-medium">Status:</span> {load.status}</div>
          </div>
        </div>

        <div className="mt-8 grid gap-6 md:grid-cols-3">
          <Card title="From">
            <div className="space-y-1 text-sm">
              <div className="font-medium">{load.organization?.name || "Your Company"}</div>
              <div>{load.organization?.slug ? `${load.organization.slug}.dispatchspot` : "Company workspace"}</div>
            </div>
          </Card>
          <Card title="Bill to">
            <div className="space-y-1 text-sm">
              <div className="font-medium">{load.broker?.name || "Unassigned broker"}</div>
              <div>{load.broker?.phone || "Phone not available"}</div>
            </div>
          </Card>
          <Card title="Load movement">
            <div className="space-y-1 text-sm">
              <div><span className="font-medium">Pickup:</span> {load.pickupLocation || "-"}</div>
              <div><span className="font-medium">Delivery:</span> {load.deliveryLocation || "-"}</div>
              <div><span className="font-medium">Pickup date:</span> {formatDate(load.pickupDate)}</div>
              <div><span className="font-medium">Delivery date:</span> {formatDate(load.deliveryDate)}</div>
            </div>
          </Card>
        </div>

        <div className="mt-8 overflow-hidden rounded-2xl border">
          <table className="min-w-full divide-y divide-gray-200 text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left font-medium text-gray-600">Code</th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">Description</th>
                <th className="px-4 py-3 text-right font-medium text-gray-600">Amount</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 bg-white">
              {lineItems.length ? lineItems.map((item, index) => (
                <tr key={`${item.code}-${index}`}>
                  <td className="px-4 py-3">{item.code}</td>
                  <td className="px-4 py-3">{item.description}</td>
                  <td className="px-4 py-3 text-right font-medium">{money(item.amount)}</td>
                </tr>
              )) : (
                <tr>
                  <td className="px-4 py-4 text-gray-500" colSpan={3}>No billable items are attached to this load yet.</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        <div className="mt-8 grid gap-6 md:grid-cols-[1fr_320px]">
          <Card title="Notes">
            <div className="space-y-2 text-sm text-gray-700">
              <div>{load.specialRequirements || "No special requirements noted."}</div>
              <div>{load.notesText || "No internal notes attached to this invoice view."}</div>
            </div>
          </Card>
          <Card title="Invoice summary">
            <div className="space-y-3 text-sm">
              <div className="flex items-center justify-between"><span>Base rate</span><span className="font-medium">{money(load.invoiceAmount)}</span></div>
              <div className="flex items-center justify-between"><span>Accessorial total</span><span className="font-medium">{money(load.financialSummary?.accessorialTotal)}</span></div>
              <div className="flex items-center justify-between border-t pt-3 text-base"><span className="font-semibold">Invoice total</span><span className="font-semibold">{money(invoiceTotal)}</span></div>
              <div className="flex items-center justify-between"><span>Amount paid</span><span className="font-medium">{money(load.financialSummary?.amountPaidTotal)}</span></div>
              <div className="flex items-center justify-between border-t pt-3 text-base"><span className="font-semibold">Outstanding</span><span className="font-semibold">{money(load.financialSummary?.outstandingAmount ?? invoiceTotal)}</span></div>
            </div>
          </Card>
        </div>
      </section>
    </div>
  );
}
