"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { Link, usePathname } from "@/i18n/navigation";
import { ChatRoom } from "@/components/chat-room";

export function ChatDock({ isAdmin }: { isAdmin: boolean }) {
  const t = useTranslations("chat");
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  const [unread, setUnread] = useState(0);
  const onChatPage = pathname.includes("/chat");

  useEffect(() => {
    let stop = false;
    async function tick() {
      const res = await fetch("/api/chat/unread", { cache: "no-store" });
      if (!res.ok || stop) return;
      const data = (await res.json()) as { unread?: number };
      setUnread(Number(data.unread ?? 0));
    }
    void tick();
    const id = setInterval(() => void tick(), 8000);
    return () => {
      stop = true;
      clearInterval(id);
    };
  }, [pathname]);

  if (onChatPage) return null;

  const tabClass =
    "fixed end-0 top-[42%] z-40 flex items-center gap-2 rounded-s-2xl bg-brand px-2.5 py-4 text-sm font-semibold text-white shadow-lg";

  const badge =
    unread > 0 ? (
      <span className="rounded-full bg-white px-1.5 text-xs text-brand">{unread}</span>
    ) : null;

  if (isAdmin) {
    return (
      <Link href="/admin/chat" className={tabClass}>
        {t("title")}
        {badge}
      </Link>
    );
  }

  return (
    <>
      <button type="button" onClick={() => setOpen(true)} className={tabClass}>
        {t("title")}
        {badge}
      </button>
      {open ? (
        <div className="fixed inset-0 z-50 flex justify-end bg-black/25">
          <button className="h-full flex-1" aria-label={t("close")} onClick={() => setOpen(false)} />
          <div className="flex h-full w-full max-w-md flex-col bg-card shadow-2xl">
            <div className="flex items-center justify-between border-b border-line p-4">
              <div>
                <h2 className="font-bold">{t("title")}</h2>
                <p className="text-xs text-muted">{t("withAdmin")}</p>
              </div>
              <div className="flex items-center gap-3 text-sm">
                <Link href="/dashboard/chat" className="text-brand" onClick={() => setOpen(false)}>
                  {t("open")}
                </Link>
                <button type="button" onClick={() => setOpen(false)} className="text-muted">
                  {t("close")}
                </button>
              </div>
            </div>
            <div className="min-h-0 flex-1 overflow-hidden">
              <ChatRoom endpoint="/api/chat" pollEndpoint="/api/chat" viewer="member" />
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
