"use client";

import { useEffect, useRef, useState } from "react";

type Msg = {
  id?: string;
  role: "user" | "assistant";
  content: string;
  citations?: { source_path: string; title?: string }[] | null;
};

export function ChatPane({
  caseId,
  messages,
  onUpdated,
  disabled,
}: {
  caseId: string | null;
  messages: Msg[];
  onUpdated: (data: unknown) => void;
  disabled?: boolean;
}) {
  const [text, setText] = useState("");
  const [busy, setBusy] = useState(false);
  const [pending, setPending] = useState<Msg | null>(null);
  const sending = useRef(false);
  const bottom = useRef<HTMLDivElement>(null);
  const shown = pending ? [...messages, pending] : messages;

  useEffect(() => {
    bottom.current?.scrollIntoView({ behavior: "smooth" });
  }, [shown.length]);

  async function send() {
    if (!caseId || !text.trim() || busy || sending.current) return;
    const content = text.trim();
    sending.current = true;
    setBusy(true);
    setPending({ id: "pending-user", role: "user", content });
    setText("");
    try {
      const res = await fetch("/api/mortgage/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ caseId, message: content }),
      });
      const data = await res.json();
      onUpdated(data);
    } finally {
      setPending(null);
      sending.current = false;
      setBusy(false);
    }
  }

  return (
    <section className="flex min-h-0 flex-1 flex-col bg-[#0b1220]">
      <div className="min-h-0 flex-1 overflow-y-auto p-4 space-y-3">
        {shown.map((m, i) => (
          <div key={m.id || i} className={m.role === "user" ? "ml-8" : "mr-8"}>
            <div
              className={`rounded-xl px-3 py-2 text-sm ${
                m.role === "user" ? "bg-sky-500/20 text-sky-50" : "bg-[#152033] text-slate-100"
              }`}
            >
              {m.content}
            </div>
            {m.role === "assistant" && Array.isArray(m.citations) && m.citations.length > 0 && (
              <p className="mt-1 text-[11px] text-slate-500">
                Playbook:{" "}
                {m.citations
                  .filter((c) => !c.source_path.includes(".html"))
                  .map((c) => c.source_path.split(/[/\\]/).pop())
                  .filter(Boolean)
                  .slice(0, 3)
                  .join(" · ")}
              </p>
            )}
          </div>
        ))}
        <div ref={bottom} />
      </div>
      <form
        className="flex gap-2 border-t border-slate-700 p-3"
        onSubmit={(e) => {
          e.preventDefault();
          void send();
        }}
      >
        <input
          aria-label="Chat message"
          className="flex-1 rounded-lg border border-slate-600 bg-[#152033] px-3 py-2 text-sm text-white outline-none focus:border-sky-400"
          value={text}
          disabled={!caseId || busy || disabled}
          onChange={(e) => setText(e.target.value)}
          placeholder="Type a message…"
        />
        <button
          type="submit"
          disabled={!caseId || busy || disabled}
          className="rounded-lg bg-sky-400 px-4 py-2 text-sm font-medium text-slate-900 disabled:opacity-40"
        >
          Send
        </button>
      </form>
    </section>
  );
}
