"use client";

import { useEffect, useRef, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { localeLabels, type AppLocale } from "@/i18n/routing";
import type { ChatMessage } from "@/lib/chat";

function labelFor(locale: string) {
  return localeLabels[locale] ?? locale;
}

function BubbleText({
  item,
  viewer,
}: {
  item: ChatMessage;
  viewer: "admin" | "member";
}) {
  const t = useTranslations("chat");
  const original = item.body;
  const translated =
    item.translatedBody && item.translatedBody !== original ? item.translatedBody : null;

  if (viewer === "admin") {
    if (item.sourceLocale === "ar") {
      return (
        <>
          <p className="whitespace-pre-wrap break-words" dir="rtl">
            {original}
          </p>
          {translated ? (
            <p className="mt-2 border-t border-line/70 pt-2 text-xs text-muted" dir="auto">
              {t("translation")} ({labelFor(item.translatedLocale ?? "en")}): {translated}
            </p>
          ) : null}
        </>
      );
    }
    return (
      <>
        <p className="whitespace-pre-wrap break-words" dir="rtl">
          {translated ?? original}
        </p>
        {translated ? (
          <p className="mt-2 border-t border-line/70 pt-2 text-xs text-muted" dir="auto">
            {t("original")} ({labelFor(item.sourceLocale)}): {original}
          </p>
        ) : null}
      </>
    );
  }

  if (item.senderRole === "USER") {
    return <p className="whitespace-pre-wrap break-words">{original}</p>;
  }

  const local = translated ?? original;
  return (
    <>
      <p className="whitespace-pre-wrap break-words">{local}</p>
      {local !== original ? (
        <p className="mt-2 border-t border-line/70 pt-2 text-xs text-muted" dir="rtl">
          {t("inArabic")}: {original}
        </p>
      ) : null}
    </>
  );
}

export function ChatRoom({
  endpoint,
  pollEndpoint,
  viewer,
}: {
  endpoint: string;
  pollEndpoint: string;
  viewer: "admin" | "member";
}) {
  const t = useTranslations("chat");
  const locale = useLocale() as AppLocale;
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [body, setBody] = useState("");
  const [error, setError] = useState("");
  const [sending, setSending] = useState(false);
  const bottom = useRef<HTMLDivElement>(null);

  async function load() {
    const url =
      viewer === "member"
        ? `${pollEndpoint}${pollEndpoint.includes("?") ? "&" : "?"}locale=${locale}`
        : pollEndpoint;
    const res = await fetch(url, { cache: "no-store" });
    if (!res.ok) return;
    const data = (await res.json()) as { messages?: ChatMessage[] };
    if (data.messages) setMessages(data.messages);
  }

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

  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, locale: viewer === "admin" ? "ar" : locale }),
    });
    setSending(false);
    if (res.status === 429) {
      setError(t("tooFast"));
      return;
    }
    if (!res.ok) {
      setError(t("failed"));
      return;
    }
    setBody("");
    await load();
  }

  return (
    <div className="flex h-full 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("empty")}</p> : null}
        {messages.map((item) => (
          <div
            key={item.id}
            className={`max-w-[85%] rounded-2xl px-3 py-2 text-sm ${
              item.senderRole === "ADMIN" ? "bg-brand/10" : "ms-auto bg-background"
            }`}
          >
            <p className="text-xs font-medium text-muted">
              {item.senderRole === "ADMIN" ? t("admin") : t("you")}
            </p>
            <div className="mt-1">
              <BubbleText item={item} viewer={viewer} />
            </div>
          </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={viewer === "admin" ? t("placeholderAdmin") : t("placeholder")}
          className="field flex-1"
          dir={viewer === "admin" ? "rtl" : "auto"}
        />
        <button className="btn-primary shrink-0 text-sm" disabled={sending}>
          {sending ? t("translating") : t("send")}
        </button>
      </form>
      {error ? <p className="px-3 pb-3 text-sm text-red-700">{error}</p> : null}
    </div>
  );
}
