"use client";

import { useEffect, useMemo, useState } from "react";
import { apiGet, apiPut } from "@/lib/api";

type CallNoteRecord = {
  id: string;
  savedAt: string;
  entityType: "broker" | "company" | "shipper" | "ownerOperator";
  entityId: string;
  entityName: string;
  contactName: string;
  phoneNumber: string;
  callDirection: "OUTBOUND" | "INBOUND";
  result: "CONNECTED" | "LEFT_VM" | "NO_ANSWER" | "FOLLOW_UP";
  note: string;
  nextStep: string;
};

type QuotePersistenceResponse = {
  scenarios: unknown[];
  presets: unknown[];
  outcomes: unknown[];
  callNotes?: CallNoteRecord[];
};

const toneMap: Record<CallNoteRecord["result"], string> = {
  CONNECTED: "bg-emerald-50 text-emerald-700",
  LEFT_VM: "bg-amber-50 text-amber-700",
  NO_ANSWER: "bg-rose-50 text-rose-700",
  FOLLOW_UP: "bg-sky-50 text-sky-700",
};

export function CallNoteContinuity({
  entityType,
  entityId,
  entityName,
  contactName,
  phoneNumber,
}: {
  entityType: CallNoteRecord["entityType"];
  entityId: string;
  entityName: string;
  contactName: string;
  phoneNumber?: string | null;
}) {
  const [allNotes, setAllNotes] = useState<CallNoteRecord[]>([]);
  const [note, setNote] = useState("");
  const [nextStep, setNextStep] = useState("");
  const [callDirection, setCallDirection] = useState<CallNoteRecord["callDirection"]>("OUTBOUND");
  const [result, setResult] = useState<CallNoteRecord["result"]>("CONNECTED");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    apiGet<QuotePersistenceResponse>("/api/cori/quotes/persistence")
      .then((data) => setAllNotes(Array.isArray(data.callNotes) ? data.callNotes : []))
      .catch(() => undefined);
  }, []);

  const notes = useMemo(
    () => allNotes.filter((entry) => entry.entityType === entityType && entry.entityId === entityId).slice(0, 6),
    [allNotes, entityId, entityType],
  );

  async function saveNote() {
    if (!note.trim()) return;
    setSaving(true);
    const nextRecord: CallNoteRecord = {
      id: `${Date.now()}`,
      savedAt: new Date().toISOString(),
      entityType,
      entityId,
      entityName,
      contactName,
      phoneNumber: phoneNumber || "",
      callDirection,
      result,
      note: note.trim(),
      nextStep: nextStep.trim(),
    };
    const nextNotes = [nextRecord, ...allNotes].slice(0, 75);
    setAllNotes(nextNotes);
    setNote("");
    setNextStep("");
    try {
      await apiPut<QuotePersistenceResponse>("/api/cori/quotes/persistence", { callNotes: nextNotes });
    } finally {
      setSaving(false);
    }
  }

  return (
    <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="text-sm font-semibold text-slate-900">Call notes and relationship history</div>
          <div className="mt-1 text-sm text-slate-500">Capture what happened on the call, what was promised, and what the next relationship step should be without leaving the CRM record.</div>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-xs text-slate-600">
          <div className="font-semibold text-slate-800">Relationship history</div>
          <div className="mt-1">Recent call notes stay visible here so dispatch, sales, and follow-up work share the same broker-contact memory.</div>
        </div>
      </div>

      <div className="mt-4 grid gap-4 xl:grid-cols-[1.1fr_0.9fr]">
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <div className="grid gap-3 md:grid-cols-2">
            <label className="text-sm text-slate-600">
              <div className="mb-1 font-medium text-slate-800">Call direction</div>
              <select value={callDirection} onChange={(e) => setCallDirection(e.target.value as CallNoteRecord["callDirection"])} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2">
                <option value="OUTBOUND">Outbound</option>
                <option value="INBOUND">Inbound</option>
              </select>
            </label>
            <label className="text-sm text-slate-600">
              <div className="mb-1 font-medium text-slate-800">Call result</div>
              <select value={result} onChange={(e) => setResult(e.target.value as CallNoteRecord["result"])} className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2">
                <option value="CONNECTED">Connected</option>
                <option value="LEFT_VM">Left voicemail</option>
                <option value="NO_ANSWER">No answer</option>
                <option value="FOLLOW_UP">Needs follow-up</option>
              </select>
            </label>
          </div>
          <label className="mt-3 block text-sm text-slate-600">
            <div className="mb-1 font-medium text-slate-800">Call note</div>
            <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={4} placeholder="Summarize the conversation, commitments, objections, and next move." className="w-full rounded-2xl border border-slate-200 bg-white px-3 py-3" />
          </label>
          <label className="mt-3 block text-sm text-slate-600">
            <div className="mb-1 font-medium text-slate-800">Next step</div>
            <input value={nextStep} onChange={(e) => setNextStep(e.target.value)} placeholder="Example: send updated rate sheet by 3 PM" className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2" />
          </label>
          <div className="mt-3 flex items-center justify-between gap-3">
            <div className="text-xs text-slate-500">{contactName}{phoneNumber ? ` · ${phoneNumber}` : ""}</div>
            <button type="button" onClick={saveNote} disabled={saving || !note.trim()} className="rounded-xl bg-slate-950 px-4 py-2 text-sm font-medium text-white disabled:opacity-60">{saving ? "Saving…" : "Save call note"}</button>
          </div>
        </div>

        <div className="space-y-3">
          {notes.length ? notes.map((entry) => (
            <div key={entry.id} className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-900">{entry.callDirection === "OUTBOUND" ? "Outbound" : "Inbound"} call</div>
                  <div className="mt-1 text-xs text-slate-500">{new Date(entry.savedAt).toLocaleString()}</div>
                </div>
                <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${toneMap[entry.result]}`}>{entry.result.replace("_", " ")}</span>
              </div>
              <div className="mt-3 text-sm text-slate-700">{entry.note}</div>
              {entry.nextStep ? <div className="mt-3 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-600"><span className="font-semibold text-slate-800">Next step:</span> {entry.nextStep}</div> : null}
            </div>
          )) : <div className="rounded-2xl border border-dashed border-slate-200 bg-slate-50 px-4 py-6 text-sm text-slate-500">No call notes saved yet for this relationship. Use the form to start building a visible relationship timeline.</div>}
        </div>
      </div>
    </section>
  );
}
