"use client";

import Container from "@/components/elements/Container";
import RoundedInput from "@/components/elements/RoundedInput";
import ProfileAvatar from "@/components/main/ProfileAvatar";
import VerificationBadge from "@/components/main/VerificationBadge";
import PageTitle from "@/components/settings/PageTitle";
import UserDetails from "@/components/settings/UserDetails";
import StoryRing, { verifyBadgeToTierColor } from "@/components/stories/StoryRing";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { useUser } from "@/hooks/useUser";
import Link from "next/link";
import React, { useEffect, useMemo, useState } from "react";
import Image from "next/image";
import { ChatListSkeleton } from "@/components/ui/ChatSkeletons";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { fetchStoriesFeed } from "@/api/fetchStories";
import Cookies from "js-cookie";
import { getChatSocket } from "@/lib/chat/socketClient";
import BoldIcon from "@/components/ui/BoldIcon";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import { isUserOnline } from "@/lib/chat/onlineStatus";
import { staticIconUrl } from "@/components/main/BaseUrl";
import { E2EE_LOCKED_PREVIEW } from "@/lib/e2ee";

export interface IMessage {
  first_name: string;
  last_name: string;
  user_name: string;
  is_verified: string;
  verify_badge?: string;
  profile_image?: string;
  last_online?: string;
  _id: string;
  unread_messages_count?: number;
  is_blocked: boolean | null;
  blocked_you: boolean | null;
  display_name?: string;
  account_deactivated?: boolean;
  chat_type?: "user" | "shop";
  shop_id?: string;
  buyer_id?: string;
}

function Chats() {
  const { t } = useTranslation("common");
  const [searchText, setSearchText] = useState("");
  const [search, setSearch] = useState("");
  const user = useUser();
  const queryClient = useQueryClient();
  const token = Cookies.get("token") || "";

  const { data, isFetchingNextPage, isLoading, refetch } = useInfiniteScroll({
    endpoint: "/messages",
    queryKey: ["messages", search],
    params: { search: search },
  });

  useEffect(() => {
    // بلافاصله بعد از ورود به لیست، بدون نیاز به رفرش دستی
    void refetch();
    const id = window.setInterval(() => {
      void refetch();
    }, 30_000);
    return () => window.clearInterval(id);
  }, [refetch]);

  const { data: storiesData } = useQuery({
    queryKey: ["stories-feed", token],
    queryFn: () => fetchStoriesFeed(token),
    enabled: Boolean(token),
    staleTime: 60_000,
  });

  const storyByUserId = useMemo(() => {
    const map = new Map<string, { hasStory: boolean; hasUnviewed: boolean }>();
    const add = (key: string | undefined, meta: { hasStory: boolean; hasUnviewed: boolean }) => {
      if (!key) return;
      map.set(String(key), meta);
    };
    for (const item of storiesData?.feed ?? []) {
      if (!item.stories.length) continue;
      const meta = {
        hasStory: true,
        hasUnviewed: item.has_unviewed,
      };
      add(item.user._id, meta);
      add(item.user.user_name, meta);
    }
    return map;
  }, [storiesData]);

  useEffect(() => {
    const socket = getChatSocket();
    if (!socket || !user?._id) return;

    const invalidate = () => {
      queryClient.invalidateQueries({ queryKey: ["messages"] });
    };

    socket.on("chatListUpdate", invalidate);
    socket.on("newMessage", invalidate);

    return () => {
      socket.off("chatListUpdate", invalidate);
      socket.off("newMessage", invalidate);
    };
  }, [user?._id, queryClient]);

  const isEmpty =
    !isLoading &&
    (data?.pages.length === 0 ||
      (data?.pages[0]?.filteredUsersData?.length === 0 && !isFetchingNextPage));

  const onlineLabel = t("chats.online");
  const offlineLabel = t("chats.offline");

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("chats.title")}</PageTitle>
        <div className="text-xs md:text-sm">
          <UserDetails />
          <div className="relative mt-5 w-full">
            <RoundedInput
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") setSearch(searchText);
              }}
              placeholder={t("chats.searchPlaceholder")}
            />
          </div>
          {isLoading ? (
            <ChatListSkeleton />
          ) : (
            <div className="mt-5 flex flex-col gap-1">
              <Link
                href="/settings/chats/rooms"
                className="flex items-center justify-between py-3"
              >
                <div className="flex min-w-0 flex-1 items-center gap-3">
                  <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-[#0095f6]/15">
                    <BoldIcon name="messages-2" size={24} className="text-[#0095f6]" tinted />
                  </div>
                  <div className="min-w-0 flex flex-col gap-1">
                    <span className="truncate font-semibold">{t("chats.chatRoom")}</span>
                    <span className="truncate text-[11px] text-neutral-500">
                      {t("chats.chatRoomDesc")}
                    </span>
                  </div>
                </div>
              </Link>

              <Link
                href="/settings/chats/nearby"
                className="flex items-center justify-between py-3"
              >
                <div className="flex min-w-0 flex-1 items-center gap-3">
                  <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-[#22c55e]/15">
                    <Image
                      src={staticIconUrl("/images/icons/radar.png")}
                      alt=""
                      width={26}
                      height={26}
                      className="dark:invert"
                    />
                  </div>
                  <div className="min-w-0 flex flex-col gap-1">
                    <span className="truncate font-semibold">
                      {t("nearbyFriends.title")}
                    </span>
                    <span className="truncate text-[11px] text-neutral-500">
                      {t("nearbyFriends.desc")}
                    </span>
                  </div>
                </div>
              </Link>

              {isEmpty ? (
                <p className="py-8 text-center text-neutral-500">
                  {t("chats.empty")}
                </p>
              ) : (
                data?.pages.map((page) =>
                  page.filteredUsersData?.map((item: IMessage) => {
                  if (item.chat_type === "shop") {
                    return (
                      <Link
                        key={`shop-${item.shop_id}-${item.buyer_id}`}
                        href={`/settings/chats/shop/${item.shop_id}/${item.buyer_id}`}
                        className="flex items-center justify-between py-3"
                      >
                        <div className="flex min-w-0 flex-1 items-center gap-3">
                          <ProfileAvatar
                            src={item.profile_image}
                            alt={item.display_name}
                            size="sm"
                            rounded="full"
                            className="!h-12 !w-12"
                          />
                          <div className="min-w-0 flex flex-col gap-0.5">
                            <span className="truncate font-semibold">
                              {item.display_name}
                            </span>
                            <span className="truncate text-[11px] text-neutral-400 dark:text-neutral-500">
                              {t("chats.shopChatSubtitle")}
                            </span>
                          </div>
                        </div>
                        <div className="flex shrink-0 flex-col items-end gap-1 pr-2">
                          {item.unread_messages_count ? (
                            <span className="rounded-full bg-[#387E65] px-2 py-0.5 text-xs text-white">
                              {item.unread_messages_count}
                            </span>
                          ) : null}
                        </div>
                      </Link>
                    );
                  }

                  const isOnline = isUserOnline(item.last_online, onlineLabel);
                  const storyMeta =
                    storyByUserId.get(String(item._id)) ??
                    storyByUserId.get(item.user_name);

                  return (
                    <Link
                      key={item._id}
                      href={`/settings/chats/${item?.user_name}/${item?._id}`}
                      className="flex items-center justify-between py-3"
                    >
                      <div className="flex min-w-0 flex-1 items-center gap-3">
                        <div className="relative shrink-0">
                          <StoryRing
                            hasStory={Boolean(storyMeta?.hasStory)}
                            hasUnviewed={Boolean(storyMeta?.hasUnviewed)}
                            tierColor={verifyBadgeToTierColor(item.verify_badge)}
                            avatarSize={48}
                          >
                            <ProfileAvatar
                              src={item.profile_image}
                              alt={item.user_name}
                              size="sm"
                              rounded="full"
                              className="!h-12 !w-12"
                            />
                          </StoryRing>
                          <span
                            className={cn(
                              "absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-white dark:border-neutral-900",
                              isOnline ? "bg-[#22c55e]" : "bg-neutral-400"
                            )}
                            title={
                              isOnline
                                ? onlineLabel
                                : item.last_online || offlineLabel
                            }
                            aria-hidden
                          />
                        </div>
                        <div className="min-w-0 flex flex-col gap-1">
                          <span className="truncate font-semibold">
                            {item.display_name ||
                              `${item.first_name} ${item.last_name}`.trim()}
                          </span>
                          <span className="flex min-w-0 items-center gap-1 truncate text-neutral-500">
                            <span dir="ltr" className="truncate">
                              {item.user_name}
                            </span>
                            <VerificationBadge verifyBadge={item.verify_badge} />
                          </span>
                        </div>
                      </div>
                      <div className="flex shrink-0 flex-col items-end gap-1 pr-2">
                        <span className="truncate text-[11px] text-neutral-400 dark:text-neutral-500">
                          {isOnline ? onlineLabel : item.last_online || offlineLabel}
                        </span>
                        <span className="truncate text-[11px] text-neutral-400 dark:text-neutral-500">
                          {E2EE_LOCKED_PREVIEW}
                        </span>
                        {item.unread_messages_count ? (
                          <span className="rounded-full bg-[#387E65] px-2 py-0.5 text-xs text-white">
                            {item.unread_messages_count}
                          </span>
                        ) : null}
                      </div>
                    </Link>
                  );
                })
              )
              )}
            </div>
          )}
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default Chats;
