"use client";

import Container from "@/components/elements/Container";
import RoundedInput from "@/components/elements/RoundedInput";
import { IMAGE_BASE_URL, SOCKET_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import VerificationBadge from "@/components/main/VerificationBadge";
import PageTitle from "@/components/settings/PageTitle";
import UserDetails from "@/components/settings/UserDetails";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { useUser } from "@/hooks/useUser";
import Image from "next/image";
import Link from "next/link";
import React, { useEffect, useState } from "react";
import { ChatListSkeleton } from "@/components/ui/ChatSkeletons";
import { io } from "socket.io-client";
import { useQueryClient } from "@tanstack/react-query";

export interface IMessage {
  first_name: string;
  last_name: string;
  user_name: string;
  is_verified: string;
  profile_image?: string;
  last_online?: string;
  _id: string;
  unread_messages_count?: number;
  is_blocked: boolean | null;
  blocked_you: boolean | null;
  last_message_date?: string | null;
}

function Chats() {
  const [searchText, setSearchText] = useState("");
  const [search, setSearch] = useState("");
  const user = useUser();
  const queryClient = useQueryClient();

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

  useEffect(() => {
    if (!user?._id) return;
    const socket = io(SOCKET_URL);
    socket.emit("joinUser", { userId: user._id });

    socket.on("chatListUpdate", () => {
      queryClient.invalidateQueries({ queryKey: ["messages"] });
    });

    socket.on("newMessage", () => {
      queryClient.invalidateQueries({ queryKey: ["messages"] });
    });

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

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

  return (
    <Container>
      <PageTitle>پیام ها</PageTitle>
      <div className="px-4 text-xs md:text-sm">
        <UserDetails />
        <div className="relative mt-5 w-full">
          <RoundedInput
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            placeholder="جستجو"
            className="w-full"
          />
          <button
            type="button"
            className="gentle-transition absolute left-3 top-[7px] active:scale-90"
            onClick={() => setSearch(searchText)}
            aria-label="جستجو"
          >
            <Image
              width={25}
              height={25}
              alt="جستجو"
              src="/images/icons/search-normal.svg"
            />
          </button>
        </div>

        <div className="mt-5 w-full">
          {isLoading ? (
            <ChatListSkeleton count={7} />
          ) : isEmpty ? (
            <p className="py-8 text-center text-neutral-500">
              هنوز مکالمه‌ای ندارید.
            </p>
          ) : (
            data?.pages?.map((page, pageIndex) => (
              <React.Fragment key={pageIndex}>
                {page?.filteredUsersData?.map((item: IMessage) => (
                  <Link
                    href={`/settings/chats/${item?.user_name}/${item?._id}`}
                    key={item?._id}
                    className="gentle-transition mb-2 block w-full rounded-2xl border-b border-border-primary-light p-4 font-semibold hover:bg-black/[0.03] active:scale-[0.99] dark:hover:bg-white/[0.04]"
                  >
                    <div className="flex w-full items-center justify-between">
                      <div className="flex items-center gap-3">
                        {item?.profile_image ? (
                          <Image
                            width={56}
                            height={56}
                            alt={item?.user_name}
                            src={buildStorageUrl(item?.profile_image)}
                            className="h-14 w-14 rounded-full object-cover"
                          />
                        ) : (
                          <div className="h-14 w-14 rounded-full bg-neutral-200 dark:bg-neutral-700" />
                        )}
                        <div>
                          <span className="text-sm">
                            {item.first_name} {item.last_name}
                          </span>
                          <div className="mt-1 flex items-center gap-1 text-neutral-500">
                            <span className="inline-flex items-center gap-1">
                              @{item?.user_name}
                              <VerificationBadge isVerified={item?.is_verified} />
                            </span>
                          </div>
                        </div>
                      </div>
                      <div className="flex flex-col items-end gap-2">
                        <span className="text-[10px] text-neutral-400">
                          {item?.last_online}
                        </span>
                        {item?.unread_messages_count ? (
                          <span className="flex h-5 min-w-[20px] items-center justify-center rounded-full bg-[#2aabee] px-1.5 text-[10px] text-white">
                            {item.unread_messages_count}
                          </span>
                        ) : null}
                      </div>
                    </div>
                  </Link>
                ))}
              </React.Fragment>
            ))
          )}
        </div>
      </div>
    </Container>
  );
}

export default Chats;
