"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";
}

export function QuoteCallContinuity({ phone, contactName, launchHref }: { phone?: string | null; contactName?: string | null; 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(() => {
    const normalizedPhone = (phone || "").trim();
    const normalizedName = (contactName || "").trim().toLowerCase();
    return logs.filter((entry) => {
      if (normalizedPhone && entry.phone === normalizedPhone) return true;
      if (normalizedName && entry.targetName.trim().toLowerCase() === normalizedName) return true;
      return false;
    }).slice(0, 4);
  }, [contactName, logs, phone]);

  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">Quote call notes</div>
          <div className="mt-1 text-sm text-slate-500">Recent quote-prep call sessions tied to this CRM record stay visible so the dispatcher can restart the pricing discussion quickly.</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}</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} · {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-2 text-xs text-slate-500">{entry.quoteSummary}</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 quote-call log is saved for this record yet. Use Quote Call to start a linked pricing session and the most recent call summary will appear here.</div>
        )}
      </div>
    </section>
  );
}
