"use client";

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

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

type IntakeHighlight = {
  label: string;
  value: string;
  tone: Tone;
};

type ContinuityStage = {
  key: string;
  label: string;
  state: "complete" | "current" | "pending";
  detail: string;
};

export type LoadDocumentIntakeState = {
  intakeTone: Tone;
  intakeLabel: string;
  nextAction: string;
  brokerDocumentIntakeHighlights: IntakeHighlight[];
  documentCapturePrompts: string[];
  lifecycleContinuity: ContinuityStage[];
};

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 statusOrder(status?: string | null) {
  const order = ["DRAFT", "AVAILABLE", "ASSIGNED", "IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"];
  const index = order.indexOf(status || "");
  return index === -1 ? 0 : index;
}

export function getLoadDocumentIntakeState(load: Load): LoadDocumentIntakeState {
  const hasBroker = Boolean(load.broker?.id || load.broker?.name);
  const hasBrokerPhone = Boolean(load.broker?.phone);
  const brokerNotesText = [load.specialRequirements, load.notesText].filter(Boolean).join(" ").toLowerCase();
  const hasBrokerDocumentCue = Boolean(load.rateConfirmationNumber) || brokerNotesText.includes("rate con") || brokerNotesText.includes("rate confirmation") || brokerNotesText.includes("pod") || brokerNotesText.includes("invoice");
  const hasInvoiceAnchor = Boolean(load.payments?.length || load.invoiceAmount || load.financialSummary?.grossRevenue);
  const hasPaymentReference = Boolean(load.payments?.some((payment) => payment.paymentReference));
  const deliveredOrLater = ["DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status);
  const invoicedOrLater = ["INVOICED", "PAID_FULL"].includes(load.status);

  const documentCapturePrompts = [
    !hasBroker ? "Assign the broker before treating this load as intake-complete." : null,
    hasBroker && !hasBrokerPhone ? "Add the broker phone number so paperwork and billing follow-up do not stall." : null,
    !load.rateConfirmationNumber && ["AVAILABLE", "ASSIGNED", "IN_TRANSIT", "DELIVERED", "INVOICED", "PAID_FULL"].includes(load.status) ? "Capture the rate confirmation number so broker-document intake has a visible anchor." : null,
    deliveredOrLater && !hasBrokerDocumentCue ? "Add POD, invoice, or broker-facing notes so the record stays clear." : null,
    invoicedOrLater && !hasInvoiceAnchor ? "Create or confirm the invoice record so the billing lifecycle has a visible document anchor." : null,
    load.status === "PAID_FULL" && !hasPaymentReference ? "Add the payment reference so closeout has a clean final proof anchor." : null,
  ].filter(Boolean) as string[];

  const intakeTone: Tone = documentCapturePrompts.length === 0 ? "good" : documentCapturePrompts.length <= 2 ? "watch" : "alert";
  const intakeLabel = documentCapturePrompts.length === 0 ? "Broker details look good" : documentCapturePrompts.length <= 2 ? "Some documents still need to be added" : "Important documents are still missing";

  const nextAction =
    !hasBroker ? "Assign broker intake owner" :
    !hasBrokerPhone ? "Add broker contact path" :
    !load.rateConfirmationNumber ? "Capture rate confirmation reference" :
    deliveredOrLater && !hasBrokerDocumentCue ? "Anchor POD / broker-facing document note" :
    invoicedOrLater && !hasInvoiceAnchor ? "Create invoice document anchor" :
    load.status === "PAID_FULL" && !hasPaymentReference ? "Record payment reference for closeout" :
    "Keep working with the documents already on file";

  const brokerDocumentIntakeHighlights: IntakeHighlight[] = [
    {
      label: "Broker-document intake visibility",
      value: hasBroker ? `${load.broker?.name || "Broker"}${hasBrokerPhone ? ` • ${load.broker?.phone}` : " • phone missing"}` : "Broker intake not assigned",
      tone: hasBroker ? (hasBrokerPhone ? "good" : "watch") : "alert",
    },
    {
      label: "Document-capture workflow prompts",
      value: documentCapturePrompts.length ? `${documentCapturePrompts.length} active prompt${documentCapturePrompts.length === 1 ? "" : "s"}` : "No active prompts",
      tone: documentCapturePrompts.length ? (documentCapturePrompts.length > 2 ? "alert" : "watch") : "good",
    },
    {
      label: "Lifecycle anchor",
      value: load.rateConfirmationNumber ? `Rate con ${load.rateConfirmationNumber}` : hasInvoiceAnchor ? "Invoice anchor visible" : `Status ${load.status}`,
      tone: load.rateConfirmationNumber || hasInvoiceAnchor ? "good" : ["DRAFT", "AVAILABLE"].includes(load.status) ? "default" : "watch",
    },
  ];

  const currentOrder = statusOrder(load.status);
  const lifecycleContinuity: ContinuityStage[] = [
    {
      key: "intake",
      label: "Broker intake",
      state: currentOrder > 1 ? "complete" : currentOrder === 0 || currentOrder === 1 ? "current" : "pending",
      detail: hasBroker ? `${load.broker?.name || "Broker"} visible` : "Broker not yet anchored",
    },
    {
      key: "rate-con",
      label: "Rate confirmation",
      state: load.rateConfirmationNumber ? "complete" : currentOrder >= 2 ? "current" : "pending",
      detail: load.rateConfirmationNumber ? `Visible • ${load.rateConfirmationNumber}` : "Awaiting visible rate-con reference",
    },
    {
      key: "movement",
      label: "Dispatch movement",
      state: currentOrder >= 3 ? (load.status === "IN_TRANSIT" ? "current" : "complete") : "pending",
      detail: load.pickupDate ? `Pickup ${formatDate(load.pickupDate)}` : "Pickup timing not yet anchored",
    },
    {
      key: "delivery-proof",
      label: "Delivery proof",
      state: deliveredOrLater ? (hasBrokerDocumentCue ? "complete" : "current") : "pending",
      detail: deliveredOrLater ? (hasBrokerDocumentCue ? "Proof / broker-facing note visible" : "Needs POD or paperwork note") : "Opens after delivery",
    },
    {
      key: "invoice",
      label: "Invoice follow-up",
      state: invoicedOrLater ? (hasInvoiceAnchor ? "complete" : "current") : "pending",
      detail: hasInvoiceAnchor ? "Invoice anchor visible" : "Invoice anchor not yet visible",
    },
    {
      key: "closeout",
      label: "Closeout proof",
      state: load.status === "PAID_FULL" ? (hasPaymentReference ? "complete" : "current") : "pending",
      detail: load.status === "PAID_FULL" ? (hasPaymentReference ? "Payment reference visible" : "Needs payment reference") : "Opens after payment",
    },
  ];

  return {
    intakeTone,
    intakeLabel,
    nextAction,
    brokerDocumentIntakeHighlights,
    documentCapturePrompts,
    lifecycleContinuity,
  };
}

export function LoadsDocumentIntakePanel({ load, compact = false, editHref, invoiceHref }: { load: Load; compact?: boolean; editHref?: string; invoiceHref?: string }) {
  const state = getLoadDocumentIntakeState(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">Broker-document intake visibility</h3>
          <p className="mt-1 text-sm text-slate-600">Broker intake details, paperwork prompts, and document status across the load.</p>
        </div>
        {(editHref || invoiceHref) ? (
          <div className="flex flex-wrap gap-2">
            {editHref ? <Link href={editHref} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">Update load</Link> : null}
            {invoiceHref ? <Link href={invoiceHref} 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> : null}
          </div>
        ) : null}
      </div>

      <div className={`rounded-2xl border p-4 ${toneClasses(state.intakeTone)}`}>
        <div className="text-xs font-semibold uppercase tracking-[0.18em]">Next paperwork action</div>
        <div className="mt-2 text-sm font-semibold">{state.nextAction}</div>
        <div className="mt-2 text-xs">Current paperwork state: {state.intakeLabel}</div>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-3">
        {state.brokerDocumentIntakeHighlights.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-[0.95fr_1.05fr]">
        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Document-capture workflow prompts</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {state.documentCapturePrompts.length ? state.documentCapturePrompts.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 document-capture prompts remain on this load.</div>
            )}
          </div>
        </div>

        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Paperwork status across the load</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {state.lifecycleContinuity.map((stage) => (
              <div
                key={stage.key}
                className={`rounded-xl border px-3 py-3 ${
                  stage.state === "complete"
                    ? "border-emerald-200 bg-emerald-50 text-emerald-800"
                    : stage.state === "current"
                      ? "border-amber-200 bg-amber-50 text-amber-800"
                      : "border-slate-200 bg-slate-50 text-slate-700"
                }`}
              >
                <div className="font-medium">{stage.label}</div>
                <div className="mt-1">{stage.detail}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
