"use client";
import React, { useState, useMemo } from "react";
import { useGetMyAllFollowingQuery } from "@/app/store/api/GetMyFollowing";
import Cookies from "js-cookie";
import Image from "next/image";
import { useRouter } from "next/navigation";
import NoPostGif from "../../../../public/assets/NoPost.png";
import { hideModal } from "@/app/store/Slice/modalSlice";
import { useAppDispatch, useAppSelector } from "@/app/hooks/hooks";
import useApiPost from "@/app/hooks/postData";
// import {User} from '../../types/SearchUserType'
import toast from "react-hot-toast";
import { ClipLoader } from "react-spinners";
import {
  incrementShareCount,
  setShareCount,
} from "@/app/store/Slice/PostIdSlice";
import { setUserId } from "@/app/store/Slice/SetUserIdForChatOpen";
import { useGetAllUsersQuery } from "@/app/store/api/AllUsersList";
import TextTranslate from "@/app/utils/TextTranslate";
import { useTranslateText } from "@/app/hooks/useTranslate";
import { X } from "lucide-react";
import { showSuccessToast } from "@/app/components/Toast/SuccessToast";

function SharePostUsersList({
  onShareSuccess,
}: {
  onShareSuccess: () => void;
}) {
  const [searchTerm, setSearchTerm] = useState("");
  const token = Cookies.get("Snapta_auth_token");
  // const {
  //   data: MyFollowingData,
  //   refetch,
  //   error: followingError,
  //   isLoading,
  // } = useGetMyAllFollowingQuery({ token: token || "" });

  const {
    data: UsersData,
    refetch,
    isLoading,
  } = useGetAllUsersQuery({ token: token || "" }); //All User data
  console.log("Following @#23", UsersData);
  const router = useRouter();
  const [selectedUserId, setSelectedUserId] = useState("");
  const dispatch = useAppDispatch();
  const isSharePostOpen = useAppSelector((state) => state.modals.SharePost);
  const translate = useTranslateText();

 const handleUsernameClick = (username: string) => {
  router.push(`/Profile/${username}`);
  dispatch(hideModal("SharePost"));
};

  function onClose() {
    dispatch(hideModal("SharePost"));
  }

  // To share story
  const { postData, loading, error } = useApiPost();
  const { id: PostId, post_type: PostType } = useAppSelector(
    (state) => state.PostId
  );

  const handleSharePost = (toUser: string) => {
    onClose();
    showSuccessToast("Post Shared Successfully!", "You can check your chats to view the shared post.");

    const payload = {
      to_user: toUser,
      type: PostType === "reel" ? "reel" : "post",
      event_name: "message",
      ...(PostType === "reel" ? { reel_id: PostId } : { post_id: PostId }),
    };

    postData("/new_chat_api", payload)
      .then(() => {
        dispatch(incrementShareCount());
        onShareSuccess();
      })
      .catch((error) => {
        console.error("Error sharing content:", error);
      });
  };

  if (!isSharePostOpen) return null;

  const users: any[] = Array.isArray(UsersData?.tag_users)
    ? UsersData?.tag_users
    : [];
  const filteredUsers = useMemo(() => {
    return users.filter(
      (user) =>
        (user?.first_name + " " + user?.last_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        user?.username?.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [users, searchTerm]);

  const userId = UsersData?.tag_users?.map((user: any) => user?.user_id);
  console.log("Users Id @#415", userId);

  return (
    <>
      {isSharePostOpen && (
        <div className="fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm z-[9999] p-4">
          <div className="relative bg-[var(--modal-color)] rounded-3xl shadow-2xl w-full max-w-[420px] md:max-w-[500px] overflow-hidden pb-6 animate-in fade-in zoom-in duration-200 flex flex-col max-h-[65vh] text-center border border-[var(--border-color)]">
            <div className="relative flex items-center justify-center px-4 py-4 border-b border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)] ">
              <button onClick={onClose} className="absolute left-6 text-[var(--text-primary)] hover:text-[var(--text-primary)] transition-colors">
                <X size={24} />
              </button>
              <h2 className="text-[var(--text-primary)] font-semibold text-[16px] translate-y-0.5">
                <TextTranslate text="Share Post" />
              </h2>
            </div>

            <div className="flex flex-col  px-4 border-b border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)]">
              <div className="relative">

                <div className="absolute left-0 top-1/2 transform -translate-y-1/2 p-2 flex items-center">
                  <span className="text-[var(--text-primary)] font-bold text-[15px] mr-2">To:</span>

                  <img
                    src="/assets/follower_search.png"
                    alt="Search"
                    className="w-4 h-4 opacity-50 img-theme"
                  />
                </div>

                <input
                  type="text"
                  className="bg-transparent  rounded-xl w-full py-2.5 pl-14 placeholder:text-sm placeholder:text-[var(--text-secondary)] text-[var(--text-primary)] focus:outline-none "
                  placeholder={translate("Search Here")}
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            </div>

            {isLoading ? (
              <div className="flex justify-center items-center py-20 flex-1">
                <ClipLoader
                  loading={isLoading}
                  size={25}
                  color="var(--text-primary)"
                />
              </div>
            ) : (
              <div className="flex-1 overflow-y-auto theme-scrollbar min-h-[300px] ">
               {users.length > 0 ? (
                  <div className="flex flex-col">
                    {(searchTerm ? filteredUsers : users).length > 0 ? (
                      (searchTerm ? filteredUsers : users).map((user) => (
                        <div
                          key={user.user_id}
                          className="flex items-center justify-between px-4 py-3 hover:bg-[color-mix(in_srgb,var(--text-primary),transparent_95%)] group transition-colors"
                        >
                          <div className="flex items-center gap-3">
                            <img
                              src={user.profile_pic || "/assets/default_user.png"}
                              alt={user.first_name}
                              className="w-12 h-12 rounded-full object-cover border border-[var(--border-color)]"
                            />
                            <div className="flex flex-col text-left">
                              <button
                                onClick={() => handleUsernameClick(user?.user_id || user?.follow_user_id)}
                                className="text-left"
                              >
                                <p className="font-gilroy_semibold text-[var(--text-primary)] text-[14px] font-bold">
                                  {user.first_name} {user.last_name}
                                </p>
                                <p className="text-[var(--text-secondary)] font-gilroy_md text-[13px]">
                                  @{user.username}
                                </p>
                              </button>
                            </div>
                          </div>
                          <button
                            className="rounded-xl border border-transparent bg-gradient-custom text-white font-gilroy_semibold text-[13px] px-5 py-1.5 hover:opacity-90 active:scale-95 transition-all"
                            onClick={() => handleSharePost(user?.user_id)}
                          >
                            <TextTranslate text="Send" />
                          </button>
                        </div>
                      ))
                    ) : (
                      <div className="py-20 text-center">
                        <p className="text-[var(--text-secondary)] font-gilroy_md text-[14px]">
                          <TextTranslate text="No users found" />
                        </p>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="flex flex-col justify-center items-center py-20 gap-3">
                    <Image
                      src={NoPostGif}
                      alt="No users found"
                      className="w-16 h-16 opacity-40 grayscale"
                    />
                    <span className="text-[var(--text-secondary)] font-gilroy_md text-[14px]">
                      <TextTranslate text="No users found" />
                    </span>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}
    </>
  );
}

export default SharePostUsersList;