import Stories from "react-insta-stories";
import { useAppDispatch, useAppSelector } from "../../../../utils/hooks";
import { RxCross1 } from "react-icons/rx";
import { HiOutlineEye } from "react-icons/hi";
import { updateViewState } from "../../../../store/Slices/ViewManagerSlice";
import StatusViewes from "./StatusViewes";
import { useState } from "react";
import { useStatusList } from "../../../../store/api/useStatusList";
import { MyStory } from "../../../../types/StatusTypes";
import { formatRelative } from "date-fns";

export default function MyStatusViewer() {
  const dispatch = useAppDispatch();
  const [statusMediaIndex, setStatusMediaIndex] = useState(0);
  const { data } = useStatusList();
  const userData = useAppSelector((state) => state.userData);

  const myUser = {
    name: "My Stories",
    profilePic: userData.profile_pic,
  };

  const myStories = data?.data.my_stories.map((story: MyStory) => {
    const isVideo =
      story.story_type === "video" || story.media.endsWith(".mp4");
    return {
      url: story.media,
      type: isVideo ? ("video" as const) : ("image" as const),
      header: {
        heading: myUser.name,
        subheading: formatRelative(new Date(story.updatedAt), new Date()),
        profileImage: myUser.profilePic,
      },
      duration: isVideo ? undefined : 5000,
      views: story.views,
      statusId: story.story_id,
      user_id: story.user_id,
      status_text: story.caption,
    };
  });


  return (
    <div className="relative z-50 flex max-h-[100vh] w-fit max-w-xl justify-center overflow-hidden rounded-xl bg-black">
      {/* Close Button */}
      <button
        className="absolute right-5 top-5 z-[9999] rounded-full bg-black/50 p-2 text-white"
        onClick={() => dispatch(updateViewState({ showMyStatusModal: false }))}
      >
        <RxCross1 className="text-xl" />
      </button>

      {/* Story Viewer */}
      <Stories
        width="100%"
        height="83dvh"
        stories={myStories!}
        onStoryStart={(index: number) => {
          setStatusMediaIndex(index);
          dispatch(updateViewState({ currentStatusId: myStories?.[index].statusId, who_viewed_status: myStories?.[index].views }))
        }}
        onAllStoriesEnd={() => {
          dispatch(updateViewState({ showMyStatusModal: false }));
        }}
      />

      {/* 👁 Eye Button */}
      <div
        onClick={() => dispatch(updateViewState({ showStatusViews: true }))}
        className="absolute bottom-7 left-1/2 z-[9999] flex -translate-x-1/2 cursor-pointer items-center justify-center space-x-1 text-white"
      >
        <HiOutlineEye />
        <span>{myStories?.[statusMediaIndex].views.length}</span>
      </div>
      <button
        className="absolute bottom-10 z-50 -translate-y-1/2 p-2 text-white"
      >
        {myStories?.[statusMediaIndex].status_text}
      </button>
      {/* Views Bottom Sheet */}
      <StatusViewes />
    </div>
  );
}
