"use client";
import React, { useRef, useEffect, useState } from "react";
import Image from "next/image";
import "./StoryCarousel.css";
import { useGetAllStoryQuery } from "@/app/store/api/GetStoryByUser";
import Cookies from "js-cookie";
import { HiOutlinePlusSm } from "react-icons/hi";
import { useAppDispatch, useAppSelector } from "@/app/hooks/hooks";
import { showModal } from "@/app/store/Slice/modalSlice";
import { useGetUserProfileDetailsQuery } from "@/app/store/api/GetUserProfileDetails";
import toast from "react-hot-toast";
import useApiPost from "@/app/hooks/postData";
import StoryViewer from "./ViewUserStory";
import RoundedShimmer from "@/app/components/RoundedShimmer";
import TextTranslate from "@/app/utils/TextTranslate";
import { FiChevronLeft, FiChevronRight } from "react-icons/fi";

function AllStoriesHeader() {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [scrollPosition, setScrollPosition] = useState(0);
  const [maxScroll, setMaxScroll] = useState(0);
  const [containerWidth, setContainerWidth] = useState(0);

  const token = Cookies.get("Snapta_auth_token");
  const {
    data: AllUsersStory,
    refetch,
    isLoading: storiesLoading,
  } = useGetAllStoryQuery({
    token: token || "",
  });
  const storyData = AllUsersStory?.story || [];
  const myStoryData = AllUsersStory?.my_post;
  const isStoryUploaded = AllUsersStory?.my_post?.length;

  const dispatch = useAppDispatch();
  const isViewOtherUserStoryModalVisible = useAppSelector(
    (state) => state.modals.ViewOtherUsersStory
  );

  const [userIndex, setUserIndex] = useState(0);
  const [storyIndex, setStoryIndex] = useState(0);

  useEffect(() => {
    const updateScrollMetrics = () => {
      if (scrollRef.current) {
        setScrollPosition(scrollRef.current.scrollLeft);
        setMaxScroll(scrollRef.current.scrollWidth);
        setContainerWidth(scrollRef.current.clientWidth);
      }
    };

    updateScrollMetrics();
    window.addEventListener("resize", updateScrollMetrics);
    return () => window.removeEventListener("resize", updateScrollMetrics);
  }, [storyData]);

  const handleScroll = () => {
    if (scrollRef.current) {
      setScrollPosition(scrollRef.current.scrollLeft);
    }
  };

  const scrollLeft = () => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({ left: -200, behavior: "smooth" });
    }
  };

  const scrollRight = () => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({ left: 200, behavior: "smooth" });
    }
  };

  const openAddStoryViewStoryPopup = () => {
    if (isStoryUploaded) dispatch(showModal("Story"));
    else dispatch(showModal("AddStory"));
  };

  const { data: UserData, isLoading } = useGetUserProfileDetailsQuery({
    token: token || "",
  });
  const ProfileData = UserData?.user_data;

  const openStoryViewer = (uIndex: number, sIndex: number) => {
    setUserIndex(uIndex);
    setStoryIndex(sIndex);
  };

  const { postData } = useApiPost();
  const handleViewStory = async (storyId: number) => {
    try {
      await postData("/view_story", { story_id: storyId });
    } catch (error: any) {
      console.error(error);
    }
    refetch();
  };

  function openOtherUserStoryModal() {
    dispatch(showModal("ViewOtherUsersStory"));
  }

  // Navigation logic for the Modal
  const goNextStory = () => {
    if (userIndex < storyData.length - 1) {
      setUserIndex((prev) => prev + 1);
    }
  };

  const goPrevStory = () => {
    if (userIndex > 0) {
      setUserIndex((prev) => prev - 1);
    }
  };

  return (
    <>
      <div className="relative w-full overflow-hidden group">


        {/* Scrollable container */}
        <div
          ref={scrollRef}
          className="flex overflow-x-auto scrollbar-hide scroll-smooth space-x-4 py-4 px-2"
          onScroll={handleScroll}
        >
          {/* Your Story Section */}
          <div className="mx-2 w-[90px] flex-shrink-0 cursor-pointer">
            <div className="flex justify-center items-center w-full">
              <div className="relative w-20 h-20 flex justify-center items-center rounded-full">
                {isStoryUploaded &&
                  myStoryData?.[0]?.story_image &&
                  myStoryData?.[0]?.story_image?.length > 0 && (
                    <svg
                      width="80"
                      height="80"
                      viewBox="0 0 80 80"
                      className="absolute inset-0"
                    >
                      <circle
                        cx="40"
                        cy="40"
                        r="38"
                        fill="none"
                        stroke={
                          myStoryData[0].story_image.some(
                            (img) => img.is_seen === 0
                          )
                            ? "#452B7A"
                            : "#D3D3D3"
                        }
                        strokeWidth={2}
                        strokeDasharray={
                          myStoryData[0].story_image.length === 1
                            ? undefined
                            : (() => {
                              const count = myStoryData[0].story_image.length;
                              const c = 2 * Math.PI * 38;
                              const totalGapSpace = count * 4;
                              const dash = (c - totalGapSpace) / count;
                              const gap = 4;

                              return Array(count)
                                .fill(`${dash} ${gap}`)
                                .join(" ");
                            })()
                        }
                        transform="rotate(-90 40 40)"
                      />
                    </svg>
                  )}

                {isLoading ? (
                  <div className="h-[68px] w-[68px] rounded-full">
                    <RoundedShimmer />
                  </div>
                ) : (
                  <img
                    src={ProfileData?.profile_pic || "/assets/default_user.png"}
                    alt="User"
                    className="absolute inset-0 m-auto rounded-full h-[68px] w-[68px] object-cover border border-[var(--border-color)]"
                    onClick={openAddStoryViewStoryPopup}
                  />
                )}

                <button
                  className="absolute bottom-2 right-0 bg-[#452B7A] rounded-full p-1 border border-[var(--border-color)] z-10"
                  onClick={openAddStoryViewStoryPopup}
                >
                  <HiOutlinePlusSm className="text-white text-sm" />
                </button>
              </div>
            </div>
            <p className="text-center text-[var(--text-secondary)] text-[12px] font-gilroy_md pt-2 truncate w-full px-1">
              <TextTranslate text="Your Story" />
            </p>
          </div>

          {/* User Stories List */}
          {storyData.map((story, uIndex) => {
            const hasUnseen = story.story_image.some(
              (img) => img.is_seen === 0
            );
            const count = story.story_image.length;

            return (
              <div
                key={uIndex}
                className="mx-2 w-[90px] flex-shrink-0 cursor-pointer"
                onClick={() => {
                  story.story_image.forEach((img) =>
                    handleViewStory(img.story_id)
                  );
                  openStoryViewer(uIndex, 0);
                  openOtherUserStoryModal();
                }}
              >
                <div className="flex justify-center items-center w-full">
                  <div className="relative w-20 h-20 flex items-center justify-center rounded-full">
                    {count > 0 && (
                      <svg
                        width="80"
                        height="80"
                        viewBox="0 0 80 80"
                        className="absolute inset-0"
                      >
                        <circle
                          cx="40"
                          cy="40"
                          r="38"
                          fill="none"
                          stroke={hasUnseen ? "#452B7A" : "#D3D3D3"}
                          strokeWidth={2}
                          strokeDasharray={
                            count === 1
                              ? undefined
                              : (() => {
                                const c = 2 * Math.PI * 38;
                                const totalGapSpace = count * 4;
                                const dash = (c - totalGapSpace) / count;
                                const gap = 4;

                                return Array(count)
                                  .fill(`${dash} ${gap}`)
                                  .join(" ");
                              })()
                          }
                          transform="rotate(-90 40 40)"
                        />
                      </svg>
                    )}
                    {storiesLoading ? (
                      <div className="h-[68px] w-[68px] rounded-full">
                        <RoundedShimmer />
                      </div>
                    ) : (
                      <img
                        src={story?.profile_pic || "/assets/default_user.png"}
                        alt="User"
                        className="rounded-full h-[68px] w-[68px] object-cover border border-[var(--bg-primary)]"
                      />
                    )}
                  </div>
                </div>
                <p className="text-center text-[var(--text-secondary)] text-[12px] font-gilroy_md pt-2 truncate w-full px-1">
                  {story.username}
                </p>
              </div>
            );
          })}
        </div>

        {scrollPosition < maxScroll - containerWidth && (
          <button
            onClick={scrollRight}
            className="absolute right-2 top-1/2 -translate-y-1/2 z-[20] bg-white/90 dark:bg-[var(--bg-secondary)] rounded-full shadow-lg p-2 hover:scale-110 transition-all text-[var(--text-primary)]"
          >
            <FiChevronRight size={20} />
          </button>
        )}
      </div>

      {/* Story Viewer Modal Overlay */}
      {isViewOtherUserStoryModalVisible && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/70 backdrop-blur-sm">
          {/* LEFT BUTTON: Visible if there's a previous user */}
          {/* {userIndex > 0 && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                goPrevStory();
              }}
              className="absolute left-6 top-1/2 -translate-y-1/2 z-[110] bg-white/20 hover:bg-white/30 text-white p-4 rounded-full transition-all active:scale-95"
            >
              <FiChevronLeft size={35} />
            </button>
          )} */}

          <div className="w-full h-full flex items-center justify-center" onClick={(e) => e.stopPropagation()}>
            <StoryViewer
              initialUserIndex={userIndex}
              initialStoryIndex={storyIndex}
            />
          </div>


        </div>
      )}
    </>
  );
}

export default AllStoriesHeader;