"use client";

import Container from "@/components/elements/Container";
import CreateChatRoomModal from "@/components/chat/CreateChatRoomModal";
import ProfileAvatar from "@/components/main/ProfileAvatar";
import useAxios from "@/hooks/useAxios";
import { useUser } from "@/hooks/useUser";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import IOSSpinner from "@/components/ui/IOSSpinner";
import BoldIcon from "@/components/ui/BoldIcon";
import { usePageTitle } from "@/hooks/usePageTitle";
import {
  acquireChatSocket,
  joinGroupRoom,
  joinUserRoom,
  releaseChatSocket,
} from "@/lib/chat/socketClient";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";

type ChatRoomItem = {
  _id: string;
  title: string;
  description?: string;
  image?: string;
  memberCount?: number;
  onlineCount?: number;
  isMember?: boolean;
  visibility?: "public" | "private";
  province?: { id?: number; name?: string } | null;
  city?: { id?: number; name?: string } | null;
  expertise?: string | null;
  lastMessage?: { content?: string; createdAt?: string } | null;
};

export default function ChatRoomsPage() {
  const { t } = useTranslation("common");
  usePageTitle(t("chats.chatRoom"));
  const { request } = useAxios();
  const user = useUser();
  const [rooms, setRooms] = useState<ChatRoomItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreateModal, setShowCreateModal] = useState(false);

  const loadRooms = useCallback(async () => {
    try {
      const res = await request<{ rooms?: ChatRoomItem[] }>(
        "GET",
        "/chat-rooms",
        null,
        { noToast: true }
      );
      setRooms(res?.rooms ?? []);
    } finally {
      setLoading(false);
    }
  }, [request]);

  useEffect(() => {
    void loadRooms();
  }, [loadRooms]);

  useEffect(() => {
    const id = window.setInterval(() => {
      void loadRooms();
    }, 20_000);
    return () => window.clearInterval(id);
  }, [loadRooms]);

  useEffect(() => {
    const userId = user?._id ? String(user._id) : "";
    if (!userId || rooms.length === 0) return;

    acquireChatSocket();
    joinUserRoom(userId);
    for (const room of rooms) {
      joinGroupRoom(room._id, userId);
    }

    return () => {
      releaseChatSocket();
    };
  }, [rooms, user?._id]);

  return (
    <LocalePageShell>
      <Container>
        <div className="flex items-center justify-between gap-3 px-4 py-7">
          <h1 className="text-2xl font-bold text-foreground">{t("chats.chatRoom")}</h1>
          <button
            type="button"
            onClick={() => setShowCreateModal(true)}
            className="gentle-transition flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-[#0095f6] text-white shadow-md active:scale-95"
            aria-label={t("chats.aria.createRoom")}
          >
            <BoldIcon name="add" size={22} tinted className="text-white" />
          </button>
        </div>

        <div className="px-4 text-xs md:text-sm">
          {loading ? (
            <div className="flex justify-center py-16">
              <IOSSpinner size={28} />
            </div>
          ) : rooms.length === 0 ? (
            <p className="py-12 text-center text-neutral-500">
              {t("chats.roomsEmpty")}
            </p>
          ) : (
            <div className="mt-2 flex flex-col gap-1">
              {rooms.map((room) => (
                <Link
                  key={room._id}
                  href={`/settings/chats/rooms/${room._id}`}
                  className="flex items-center gap-3 py-3"
                >
                  <ProfileAvatar
                    src={room.image}
                    alt={room.title}
                    size="sm"
                    rounded="full"
                    className="h-12 w-12 shrink-0"
                  />
                  <div className="min-w-0 flex-1">
                    <p className="truncate font-semibold">{room.title}</p>
                    <p className="mt-0.5 truncate text-[11px] text-neutral-500">
                      {room.visibility === "private"
                        ? t("chats.privateRoom")
                        : [room.city?.name, room.province?.name, room.expertise]
                            .filter(Boolean)
                            .join(" · ") || t("chats.forAllUsers")}
                    </p>
                    {room.lastMessage?.content ? (
                      <p className="mt-1 truncate text-[11px] text-neutral-400">
                        {room.lastMessage.content}
                      </p>
                    ) : null}
                  </div>
                  <div className="flex shrink-0 flex-col items-end gap-1 pl-1">
                    <span className="rounded-full bg-[#22c55e]/15 px-2 py-0.5 text-[11px] font-semibold text-[#22c55e]">
                      {t("chats.onlineCount", { count: room.onlineCount ?? 0 })}
                    </span>
                    <span className="text-[10px] text-neutral-400">
                      {t("chats.memberCount", { count: room.memberCount ?? 0 })}
                    </span>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </div>

        <CreateChatRoomModal
          open={showCreateModal}
          onClose={() => setShowCreateModal(false)}
          onCreated={() => void loadRooms()}
        />
      </Container>
    </LocalePageShell>
  );
}
