"use client";

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

type Tone = "good" | "watch" | "alert" | "default";

type ReadinessItem = {
  key: string;
  label: string;
  value: string;
  complete: boolean;
  helpText: string;
};

export type LoadDocumentComplianceState = {
  readinessTone: Tone;
  readinessLabel: string;
  nextAction: string;
  readinessItems: ReadinessItem[];
  missingPrompts: string[];
  complianceHighlights: Array<{ label: string; value: string; tone: Tone }>;
};

function toneClasses(tone: Tone) {
  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";
}

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

function hasPODVisibility(load: Load) {
  const combined = [
    load.notesText,
    load.specialRequirements,
    ...(load.statusHistory?.map((item) => item.note || "") ?? []),
    ...(load.payments?.map((item) => item.notesText || "") ?? []),
  ]
    .join(" ")
    .toLowerCase();

  return load.status === "PAID_FULL" || combined.includes("pod") || combined.includes("proof of delivery") || combined.includes("delivered");
}

export function getLoadDocumentComplianceState(load: Load): LoadDocumentComplianceState {
  const hasRateCon = Boolean(load.rateConfirmationNumber);
  const hasBrokerLane = Boolean(load.broker?.name && load.broker?.phone);
  const hasDeliveryEvidence = hasPODVisibility(load);
  const hasInvoiceAnchor = Boolean(load.payments?.length || load.invoiceAmount || load.financialSummary?.grossRevenue);

  const readinessItems: ReadinessItem[] = [
    {
      key: "rate-confirmation",
      label: "Rate confirmation visibility",
      value: hasRateCon ? `Rate con ${load.rateConfirmationNumber}` : "No rate confirmation visible",
      complete: hasRateCon,
      helpText: "Dispatchers need a visible rate confirmation reference before treating a load as document-ready for broker execution.",
    },
    {
      key: "broker-billing-lane",
      label: "Broker billing contact path",
      value: hasBrokerLane ? `${load.broker?.name} • ${load.broker?.phone}` : "Broker billing phone path not visible",
      complete: hasBrokerLane,
      helpText: "Billing and paperwork follow-up need a visible broker contact path.",
    },
    {
      key: "delivery-evidence",
      label: "POD / delivery evidence visibility",
      value: hasDeliveryEvidence ? "Delivery evidence is visible in notes or lifecycle history" : load.status === "DELIVERED" || load.status === "INVOICED" || load.status === "PAID_FULL" ? "Delivered state visible, but POD proof is not clearly anchored" : "Delivery evidence opens after delivery",
      complete: hasDeliveryEvidence,
      helpText: "POD or another proof of delivery should be visible before billing is treated as clean.",
    },
    {
      key: "invoice-anchor",
      label: "Invoice anchor visibility",
      value: hasInvoiceAnchor ? "Invoice amount or invoice record is visible" : "No invoice anchor is visible yet",
      complete: hasInvoiceAnchor,
      helpText: "An invoice anchor helps dispatch and billing stay aligned once delivery is complete.",
    },
  ];

  const missingPrompts = [
    !hasRateCon ? "Capture or confirm the rate confirmation reference before relying on document completeness." : null,
    !hasBrokerLane ? "Add a broker billing phone path so POD, invoice, and payment follow-up do not stall." : null,
    (load.status === "DELIVERED" || load.status === "INVOICED" || load.status === "PAID_FULL") && !hasDeliveryEvidence ? "Add POD or delivery proof in notes or status history before treating paperwork as clean." : null,
    (load.status === "DELIVERED" || load.status === "INVOICED" || load.status === "PAID_FULL") && !hasInvoiceAnchor ? "Create or confirm the invoice record so closeout does not drift." : null,
  ].filter(Boolean) as string[];

  const readinessTone: Tone = missingPrompts.length === 0 ? "good" : missingPrompts.length <= 2 ? "watch" : "alert";
  const readinessLabel = missingPrompts.length === 0 ? "Document-ready" : missingPrompts.length <= 2 ? "Needs follow-up" : "Compliance blockers visible";

  const nextAction =
    !hasRateCon ? "Capture the rate confirmation reference" :
    !hasBrokerLane ? "Document the broker billing contact path" :
    (load.status === "DELIVERED" || load.status === "INVOICED" || load.status === "PAID_FULL") && !hasDeliveryEvidence ? "Anchor POD or proof of delivery" :
    (load.status === "DELIVERED" || load.status === "INVOICED" || load.status === "PAID_FULL") && !hasInvoiceAnchor ? "Create or refresh the invoice record" :
    "Continue the load with clean document visibility";

  const complianceHighlights: Array<{ label: string; value: string; tone: Tone }> = [
    {
      label: "Compliance status surfacing",
      value: readinessLabel,
      tone: readinessTone,
    },
    {
      label: "Missing-file prompts",
      value: missingPrompts.length ? `${missingPrompts.length} visible operational prompt${missingPrompts.length === 1 ? "" : "s"}` : "No visible missing-file prompts",
      tone: missingPrompts.length ? (missingPrompts.length > 2 ? "alert" : "watch") : "good",
    },
    {
      label: "Delivery evidence",
      value: hasDeliveryEvidence ? `Visible • ${formatDate(load.deliveryDate)}` : load.deliveryDate ? `Delivery set for ${formatDate(load.deliveryDate)}` : "Delivery timing not yet anchored",
      tone: hasDeliveryEvidence ? "good" : load.status === "DELIVERED" || load.status === "INVOICED" ? "watch" : "default",
    },
  ];

  return {
    readinessTone,
    readinessLabel,
    nextAction,
    readinessItems,
    missingPrompts,
    complianceHighlights,
  };
}

export function LoadsDocumentCompliancePanel({ load, compact = false }: { load: Load; compact?: boolean }) {
  const state = getLoadDocumentComplianceState(load);

  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">Document readiness visibility</h3>
          <p className="mt-1 text-sm text-slate-600">Operational document minimums, missing-file prompts, and compliance status surfacing for this load.</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Link href={`/loads/${load.id}/edit`} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
            Update load
          </Link>
          <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 p-4 ${toneClasses(state.readinessTone)}`}>
        <div className="text-xs font-semibold uppercase tracking-[0.18em]">Next document action</div>
        <div className="mt-2 text-sm font-semibold">{state.nextAction}</div>
        <div className="mt-2 text-xs">Compliance state: {state.readinessLabel}</div>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-3">
        {state.complianceHighlights.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.15fr_0.85fr]">
        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Document readiness visibility</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {state.readinessItems.map((item) => (
              <div key={item.key} className={`rounded-xl border px-3 py-3 ${item.complete ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-amber-200 bg-amber-50 text-amber-800"}`}>
                <div className="font-medium">{item.label}</div>
                <div className="mt-1">{item.value}</div>
                <div className="mt-1 text-xs opacity-80">{item.helpText}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Missing-file operational prompts</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {state.missingPrompts.length ? (
              state.missingPrompts.map((prompt) => (
                <div key={prompt} className="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-amber-800">{prompt}</div>
              ))
            ) : (
              <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-800">No visible missing-file prompts remain on this load.</div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
