import type { Load, LoadPayment } 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();
}

export function getLatestPayment(load: Load): LoadPayment | null {
  return [...(load.payments ?? [])].sort((a, b) => {
    const aDate = new Date(a.invoiceDate || a.createdAt || 0).getTime();
    const bDate = new Date(b.invoiceDate || b.createdAt || 0).getTime();
    return bDate - aDate;
  })[0] ?? null;
}

function getConfidenceModel(load: Load, payment: LoadPayment | null) {
  const outstanding = Number(load.financialSummary?.outstandingAmount ?? 0);
  const amountPaid = Number(payment?.amountPaid ?? 0);
  const amountDue = Number(payment?.amountDue ?? 0);
  const hasReference = Boolean(payment?.paymentReference);
  const paidAt = Boolean(payment?.paidAt);
  const markedPaid = payment?.paymentStatus === "PAID" || load.status === "PAID_FULL";
  const closedFinancialLoop = outstanding <= 0;
  const paidCoversDue = amountDue > 0 ? amountPaid >= amountDue : amountPaid > 0;

  const mismatches = [
    markedPaid && !closedFinancialLoop ? "Marked paid while exposure is still open" : null,
    markedPaid && !paidAt ? "Paid state is missing a paid date" : null,
    markedPaid && !hasReference ? "Paid state is missing a payment reference" : null,
    markedPaid && amountDue > 0 && !paidCoversDue ? "Paid amount does not cover the visible amount due" : null,
    !markedPaid && closedFinancialLoop && (amountPaid > 0 || hasReference) ? "Collections loop looks closed but payment state is not confirmed" : null,
  ].filter(Boolean) as string[];

  if (!payment) {
    return {
      label: "Low confidence",
      tone: "border-red-200 bg-red-50 text-red-700",
      summary: "No payment record is attached yet, so payment status cannot be trusted.",
      mismatches: ["Create or refresh the invoice payment record first."],
    };
  }

  if (!mismatches.length && markedPaid && closedFinancialLoop && hasReference && paidAt) {
    return {
      label: "High confidence",
      tone: "border-emerald-200 bg-emerald-50 text-emerald-700",
      summary: "Paid state, exposure, paid date, and payment reference all agree.",
      mismatches: [],
    };
  }

  if (mismatches.length <= 1) {
    return {
      label: "Medium confidence",
      tone: "border-amber-200 bg-amber-50 text-amber-700",
      summary: "Most signals agree, but one visible gap should be cleaned up.",
      mismatches,
    };
  }

  return {
    label: "Low confidence",
    tone: "border-red-200 bg-red-50 text-red-700",
    summary: "Visible payment signals are not aligned yet.",
    mismatches,
  };
}

export function PaymentStatusConfidencePanel({
  load,
  onMarkPaid,
  onMarkUnpaid,
  working,
}: {
  load: Load;
  onMarkPaid?: () => void;
  onMarkUnpaid?: () => void;
  working?: boolean;
}) {
  const payment = getLatestPayment(load);
  const confidence = getConfidenceModel(load, payment);
  const outstanding = Number(load.financialSummary?.outstandingAmount ?? 0);

  const controls = payment ? (
    payment.paymentStatus === "PAID" ? (
      <button onClick={onMarkUnpaid} disabled={working || !onMarkUnpaid} className="rounded-xl border bg-white px-3 py-2 text-sm font-medium disabled:opacity-60">
        Mark unpaid
      </button>
    ) : (
      <button onClick={onMarkPaid} disabled={working || !onMarkPaid} className="rounded-xl bg-black px-3 py-2 text-sm font-medium text-white disabled:opacity-60">
        Confirm paid
      </button>
    )
  ) : null;

  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <div className="text-sm font-semibold text-slate-900">Payment-status confidence controls</div>
          <div className="text-xs text-slate-500">Compare visible payment status, exposure, references, and paid date before closing the loop.</div>
        </div>
        {controls}
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-3">
        <div className="rounded-2xl border p-4">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Confidence</div>
          <div className={`mt-2 inline-flex rounded-full border px-3 py-1 text-xs font-semibold ${confidence.tone}`}>{confidence.label}</div>
          <div className="mt-2 text-xs text-slate-500">{confidence.summary}</div>
        </div>
        <div className="rounded-2xl border p-4">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Visible status</div>
          <div className="mt-2 text-sm font-semibold text-slate-900">{payment?.paymentStatus || "No payment record"}</div>
          <div className="mt-2 text-xs text-slate-500">Load status: {load.status}</div>
        </div>
        <div className="rounded-2xl border p-4">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Exposure</div>
          <div className="mt-2 text-sm font-semibold text-slate-900">{outstanding > 0 ? money(load.financialSummary?.outstandingAmount) : "No open exposure"}</div>
          <div className="mt-2 text-xs text-slate-500">Paid date {formatDate(payment?.paidAt)} • Reference {payment?.paymentReference || "missing"}</div>
        </div>
      </div>

      <div className="mt-4 rounded-2xl border p-4">
        <div className="text-sm font-semibold text-slate-900">Confidence gaps to resolve</div>
        <div className="mt-3 space-y-2 text-sm text-slate-700">
          {confidence.mismatches.length ? confidence.mismatches.map((item) => (
            <div key={item} className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">{item}</div>
          )) : (
            <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-800">No visible confidence gaps are active on this record.</div>
          )}
        </div>
      </div>
    </section>
  );
}

export function BrokerCollectionsNoteCapturePanel({ load }: { load: Load }) {
  const payment = getLatestPayment(load);
  const latestNote = payment?.notesText || load.notesText || "No collections note has been captured yet.";
  const prompts = [
    payment?.paymentReference ? `Reference captured: ${payment.paymentReference}` : "Capture the broker's payment reference or promised-pay detail.",
    payment?.paidAt ? `Paid date visible: ${formatDate(payment.paidAt)}` : "Record the promised-pay or confirmed-paid date when the broker responds.",
    Number(load.financialSummary?.outstandingAmount ?? 0) > 0 ? "Log the next follow-up owner, channel, and date in the collections note." : "Use the closeout note to confirm the billing loop is complete.",
  ];

  const noteTemplate = [
    "Channel: call / email / portal",
    "Owner: broker AP contact or operations rep",
    "Commitment: promised pay date, dispute, or confirmation",
    "Next follow-up: exact next action and target date",
  ];

  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div>
        <div className="text-sm font-semibold text-slate-900">Broker collections note capture refinement</div>
        <div className="text-xs text-slate-500">Keep every collections step tied to a clean note so billing follow-up stays clear between operators.</div>
      </div>

      <div className="mt-4 rounded-2xl border p-4">
        <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Latest visible collections note</div>
        <div className="mt-2 whitespace-pre-wrap text-sm text-slate-700">{latestNote}</div>
      </div>

      <div className="mt-4 grid gap-3 md:grid-cols-2">
        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Next note should capture</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {prompts.map((prompt) => (
              <div key={prompt} className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2">{prompt}</div>
            ))}
          </div>
        </div>
        <div className="rounded-2xl border p-4">
          <div className="text-sm font-semibold text-slate-900">Suggested note structure</div>
          <div className="mt-3 space-y-2 text-sm text-slate-700">
            {noteTemplate.map((line) => (
              <div key={line} className="rounded-xl border border-dashed border-slate-300 px-3 py-2">{line}</div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

export function CloseoutWorkflowVisibilityPanel({ load }: { load: Load }) {
  const payment = getLatestPayment(load);
  const outstanding = Number(load.financialSummary?.outstandingAmount ?? 0);
  const steps = [
    {
      label: "Invoice record visible",
      state: payment ? "Complete" : "Pending",
      done: Boolean(payment),
      help: payment ? `Invoice ${payment.invoiceNumber || "record"} is visible.` : "Create or refresh the invoice record first.",
    },
    {
      label: "Collections loop closed",
      state: outstanding <= 0 ? "Complete" : "Pending",
      done: outstanding <= 0,
      help: outstanding <= 0 ? "Outstanding exposure appears closed." : "Balance is still open.",
    },
    {
      label: "Paid confirmation anchored",
      state: payment?.paymentStatus === "PAID" || load.status === "PAID_FULL" ? "Complete" : "Pending",
      done: payment?.paymentStatus === "PAID" || load.status === "PAID_FULL",
      help: payment?.paymentReference ? `Reference ${payment.paymentReference}` : "Payment reference or paid status still needs confirmation.",
    },
    {
      label: "Ready for closeout review",
      state: outstanding <= 0 && (payment?.paymentStatus === "PAID" || load.status === "PAID_FULL") ? "Ready" : "Watch",
      done: outstanding <= 0 && (payment?.paymentStatus === "PAID" || load.status === "PAID_FULL"),
      help: outstanding <= 0 && (payment?.paymentStatus === "PAID" || load.status === "PAID_FULL")
        ? "This load is ready for operator closeout review and archive-ready handling."
        : "Keep the record in billing follow-up until payment evidence and exposure both close.",
    },
  ];

  return (
    <section className="rounded-2xl border bg-white p-5 shadow-sm">
      <div>
        <div className="text-sm font-semibold text-slate-900">Closeout workflow visibility</div>
        <div className="text-xs text-slate-500">Show whether the record is still in billing motion or ready to leave the active operator loop.</div>
      </div>

      <div className="mt-4 space-y-3">
        {steps.map((step) => (
          <div key={step.label} className="rounded-2xl border p-4">
            <div className="flex flex-wrap items-start justify-between gap-3">
              <div>
                <div className="text-sm font-semibold text-slate-900">{step.label}</div>
                <div className="mt-1 text-xs text-slate-500">{step.help}</div>
              </div>
              <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${step.done ? "border-emerald-200 bg-emerald-50 text-emerald-700" : "border-slate-200 bg-slate-50 text-slate-700"}`}>{step.state}</span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}
