"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";

type QuoteCallLog = {
  id: string;
  startedAt: string;
  targetName: string;
  phone: string;
  brokerId?: string | null;
  sourceLabel: string;
  laneSummary: string;
  quoteSummary: string;
  postedRate: number;
  targetRate: number;
  openingQuote: number;
  status: "PASS" | "NEGOTIATE" | "TAKE";
};

const CALL_LOG_KEY = "dispatchspot-cori-quotes-call-logs-v218";

function money(value: number) {
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(Number.isFinite(value) ? value : 0);
}

function tone(status: QuoteCallLog["status"]) {
  if (status === "TAKE") return "bg-emerald-50 text-emerald-700";
  if (status === "NEGOTIATE") return "bg-amber-50 text-amber-700";
  return "bg-rose-50 text-rose-700";
}

function buildResumeHref(entry: QuoteCallLog, fallbackSource: string) {
  const params = new URLSearchParams({
    source: entry.sourceLabel || fallbackSource,
    contactName: entry.targetName || "",
    phone: entry.phone || "",
  });
  if (entry.brokerId) params.set("brokerId", entry.brokerId);
  return `/cori/quotes?${params.toString()}`;
}

export function RecentCallContinuity({
  title,
  sourceLabel,
  launchHref,
}: {
  title?: string;
  sourceLabel: string;
  launchHref: string;
}) {
  const [logs, setLogs] = useState<QuoteCallLog[]>([]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      const raw = window.localStorage.getItem(CALL_LOG_KEY);
      if (!raw) return;
      setLogs(JSON.parse(raw) as QuoteCallLog[]);
    } catch {
      // ignore
    }
  }, []);

  const relevantLogs = useMemo(
    () => logs.filter((entry) => (entry.sourceLabel || "").toLowerCase() === sourceLabel.toLowerCase()).slice(0, 4),
    [logs, sourceLabel],
  );

  return (
    <section className="rounded-[28px] border border-slate-200 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">{title || "Recent call notes"}</div>
          <div className="mt-1 text-sm text-slate-500">Recent quote-call sessions from this CRM workspace stay visible so dispatchers can resume pricing conversations faster.</div>
        </div>
        <Link href={launchHref} className="inline-flex items-center justify-center rounded-full bg-sky-600 px-4 py-2 text-sm font-semibold text-white hover:bg-sky-700">Open CORI’s Quotes</Link>
      </div>
      <div className="mt-4 space-y-3">
        {relevantLogs.length ? relevantLogs.map((entry) => (
          <div key={entry.id} className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-600">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <div className="font-medium text-slate-900">{entry.targetName || "Quote call"}</div>
              <div className={`inline-flex rounded-full px-2.5 py-1 text-xs font-semibold ${tone(entry.status)}`}>{entry.status}</div>
            </div>
            <div className="mt-1 text-xs text-slate-500">{entry.laneSummary || "Lane not captured yet"} · {new Date(entry.startedAt).toLocaleString()}</div>
            <div className="mt-2 flex flex-wrap gap-2 text-xs">
              <span className="rounded-full bg-white px-2.5 py-1 text-slate-700 ring-1 ring-slate-200">Posted {money(entry.postedRate)}</span>
              <span className="rounded-full bg-white px-2.5 py-1 text-slate-700 ring-1 ring-slate-200">Target {money(entry.targetRate)}</span>
              <span className="rounded-full bg-white px-2.5 py-1 text-slate-700 ring-1 ring-slate-200">Open {money(entry.openingQuote)}</span>
            </div>
            <div className="mt-3 flex flex-wrap gap-3 text-xs font-semibold">
              <Link href={buildResumeHref(entry, sourceLabel)} className="text-sky-700 hover:text-sky-800">Resume quote call</Link>
            </div>
          </div>
        )) : (
          <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-4 py-5 text-sm text-slate-500">No recent quote-call notes are saved yet. Start a Quote Call from a record or open CORI’s Quotes.</div>
        )}
      </div>
    </section>
  );
}
