"use client";

import Link from "next/link";
import type { Load } from "@/types";

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 toneClasses(tone: "good" | "watch" | "alert" | "default") {
  if (tone === "good") return "border-emerald-200 bg-emerald-50 text-emerald-700";
  if (tone === "watch") return "border-amber-200 bg-amber-50 text-amber-700";
  if (tone === "alert") return "border-red-200 bg-red-50 text-red-700";
  return "border-slate-200 bg-slate-50 text-slate-700";
}

export function LoadBillingReadinessPanel({ load, compact = false }: { load: Load; compact?: boolean }) {
  const outstanding = Number(load.financialSummary?.outstandingAmount ?? 0);
  const grossRevenue = Number(load.financialSummary?.grossRevenue ?? load.invoiceAmount ?? 0);
  const hasInvoiceRecord = Boolean(load.payments?.length);
  const delivered = load.status === "DELIVERED";
  const invoiced = load.status === "INVOICED" || load.status === "PAID_FULL";
  const paymentFollowUp = invoiced && outstanding > 0;

  const missingInvoiceData = [
    !load.broker?.id ? "Assign broker / bill-to party" : null,
    !grossRevenue ? "Set invoice amount or billable revenue" : null,
    !load.deliveryDate ? "Confirm delivery date" : null,
    !load.pickupDate ? "Confirm pickup date" : null,
  ].filter(Boolean) as string[];

  const invoiceReadinessTone: "good" | "watch" | "alert" | "default" =
    invoiced ? "good" : delivered && missingInvoiceData.length === 0 ? "watch" : delivered ? "alert" : "default";

  const nextBillingAction =
    invoiced && outstanding <= 0
      ? "Billing loop closed"
      : paymentFollowUp
        ? "Follow up on receivable and payment reference"
        : delivered && missingInvoiceData.length === 0
          ? "Generate invoice record and send billing package"
          : delivered
            ? "Complete missing invoice data before billing"
            : "Complete delivery before invoicing";

  const handoffItems = [
    {
      label: "Invoice check",
      value: invoiced ? "Invoice record active" : delivered ? "Ready to bill after delivery" : "Pending delivery completion",
      tone: invoiceReadinessTone,
    },
    {
      label: "Payment follow-up",
      value: paymentFollowUp ? `Outstanding ${money(load.financialSummary?.outstandingAmount)}` : invoiced ? "No active payment follow-up required" : "Not yet in payment follow-up",
      tone: paymentFollowUp ? "alert" as const : invoiced ? "good" as const : "default" as const,
    },
    {
      label: "Billing step",
      value: delivered ? `Delivery ${formatDate(load.deliveryDate)} • Invoice ${hasInvoiceRecord ? "record exists" : "not yet created"}` : "Billing opens after delivery",
      tone: delivered ? "watch" as const : "default" as const,
    },
  ];

  return (
    <section className={`rounded-2xl border bg-white shadow-sm ${compact ? "p-4" : "p-6"}`}>
      <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <h3 className="text-base font-semibold text-slate-900">Billing check</h3>
          <p className="mt-1 text-sm text-slate-600">Invoice prompts and payment follow-up for this load.</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link href={`/loads/${load.id}/invoice`} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
            Open invoice view
          </Link>
        </div>
      </div>

      <div className="rounded-2xl border bg-slate-50 p-4">
        <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Next billing action</div>
        <div className="mt-2 text-sm font-semibold text-slate-900">{nextBillingAction}</div>
        <div className="mt-2 text-xs text-slate-600">
          Gross revenue {money(load.financialSummary?.grossRevenue || load.invoiceAmount)} • Outstanding {money(load.financialSummary?.outstandingAmount)}
        </div>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-3">
        {handoffItems.map((item) => (
          <div key={item.label} className={`rounded-2xl border p-4 ${toneClasses(item.tone)}`}>
            <div className="text-xs font-semibold uppercase tracking-[0.16em]">{item.label}</div>
            <div className="mt-2 text-sm font-semibold">{item.value}</div>
          </div>
        ))}
      </div>

      <div className="mt-4 grid gap-4 lg:grid-cols-[1.2fr_0.8fr]">
        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Invoice check prompts</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {missingInvoiceData.length ? (
              missingInvoiceData.map((item) => (
                <div key={item} className="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-amber-800">{item}</div>
              ))
            ) : (
              <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-800">No invoice issues are visible for this load.</div>
            )}
          </div>
        </div>

        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Payment follow-up</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            <div><span className="font-medium">Invoice record:</span> {hasInvoiceRecord ? "Present" : "Not yet created"}</div>
            <div><span className="font-medium">Payment status:</span> {load.financialSummary?.paymentStatusSummary || "-"}</div>
            <div><span className="font-medium">Outstanding:</span> {money(load.financialSummary?.outstandingAmount)}</div>
            <div><span className="font-medium">Billing step:</span> {delivered ? "Open" : "Pending delivery"}</div>
          </div>
        </div>
      </div>
    </section>
  );
}
