"use client";

import { useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";

type Item = {
  id: string;
  senderId: string;
  senderName: string;
  body: string;
  createdAt: string;
};

export function EscrowChat({
  dealId,
  viewerId,
}: {
  dealId: string;
  viewerId: string;
}) {
  const t = useTranslations("escrow");
  const [messages, setMessages] = useState<Item[]>([]);
  const [body, setBody] = useState("");
  const [error, setError] = useState("");
  const [sending, setSending] = useState(false);
  const bottom = useRef<HTMLDivElement>(null);
  const endpoint = `/api/escrow/${dealId}/messages`;

  async function load() {
    const res = await fetch(endpoint, { cache: "no-store" });
    if (!res.ok) return;
    const data = (await res.json()) as { messages?: Item[] };
    if (data.messages) setMessages(data.messages);
  }

  useEffect(() => {
    void load();
    const id = setInterval(() => void load(), 4000);
    return () => clearInterval(id);
  }, [endpoint]);

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

  async function send(event: React.FormEvent) {
    event.preventDefault();
    const text = body.trim();
    if (!text || sending) return;
    setSending(true);
    setError("");
    const res = await fetch(endpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ body: text }),
    });
    setSending(false);
    if (res.status === 429) {
      setError(t("chatFast"));
      return;
    }
    if (!res.ok) {
      setError(t("chatFail"));
      return;
    }
    setBody("");
    await load();
  }

  return (
    <section className="card overflow-hidden">
      <div className="border-b border-line p-4">
        <h2 className="font-semibold">{t("chatTitle")}</h2>
        <p className="mt-1 text-sm text-muted">{t("chatHint")}</p>
      </div>
      <div className="flex min-h-[22rem] flex-col">
        <div className="flex-1 space-y-3 overflow-y-auto p-4">
          {messages.length === 0 ? <p className="text-sm text-muted">{t("chatEmpty")}</p> : null}
          {messages.map((item) => {
            const mine = item.senderId === viewerId;
            return (
              <div
                key={item.id}
                className={`max-w-[85%] rounded-2xl px-3 py-2 text-sm ${
                  mine ? "ms-auto bg-brand/10" : "bg-background"
                }`}
              >
                <p className="text-xs font-medium text-muted">{mine ? t("chatYou") : item.senderName}</p>
                <p className="mt-1 whitespace-pre-wrap break-words" dir="auto">
                  {item.body}
                </p>
              </div>
            );
          })}
          <div ref={bottom} />
        </div>
        <form onSubmit={send} className="flex flex-col gap-2 border-t border-line p-3 sm:flex-row">
          <input
            value={body}
            onChange={(e) => setBody(e.target.value)}
            maxLength={2000}
            placeholder={t("chatPlaceholder")}
            className="field flex-1"
            dir="auto"
          />
          <button className="btn-primary shrink-0 text-sm" disabled={sending}>
            {t("chatSend")}
          </button>
        </form>
        {error ? <p className="px-3 pb-3 text-sm text-red-700">{error}</p> : null}
      </div>
    </section>
  );
}
