"use client";

import React, { useCallback, useState } from "react";
import Cookies from "js-cookie";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { fetchStoriesFeed } from "@/api/fetchStories";
import StoryViewer from "@/components/stories/StoryViewer";
import { useStoryMetaForUser } from "@/hooks/useStoryMetaForUser";
import { useTranslation } from "react-i18next";

type Props = {
  userId: string;
  children: React.ReactNode;
  className?: string;
};

/** آواتار با استوری — کلیک باز کردن استوری (نه پروفایل) */
export default function StoryAvatarOpen({ userId, children, className }: Props) {
  const { t } = useTranslation("common");
  const token = Cookies.get("token") || "";
  const queryClient = useQueryClient();
  const storyMeta = useStoryMetaForUser(userId);
  const [viewerOpen, setViewerOpen] = useState(false);
  const [startIndex, setStartIndex] = useState(0);

  const { data } = useQuery({
    queryKey: ["stories-feed", token],
    queryFn: () => fetchStoriesFeed(token),
    enabled: !!token && storyMeta.hasStory,
    staleTime: 30_000,
  });

  const openStory = useCallback(
    (e: React.MouseEvent) => {
      if (!storyMeta.hasStory || !data?.feed?.length) return;
      e.preventDefault();
      e.stopPropagation();
      const idx = data.feed.findIndex((f) => f.user._id === userId);
      setStartIndex(idx >= 0 ? idx : 0);
      setViewerOpen(true);
    },
    [storyMeta.hasStory, data?.feed, userId]
  );

  const handleClose = useCallback(() => {
    setViewerOpen(false);
    queryClient.invalidateQueries({ queryKey: ["stories-feed"] });
  }, [queryClient]);

  if (!storyMeta.hasStory) {
    return <>{children}</>;
  }

  return (
    <>
      <button
        type="button"
        onClick={openStory}
        className={className ?? "inline-flex shrink-0 border-0 bg-transparent p-0"}
        aria-label={t("stories.viewStoryAria")}
      >
        {children}
      </button>
      {viewerOpen && data?.feed?.length ? (
        <StoryViewer
          feed={data.feed}
          initialUserIndex={startIndex}
          onClose={handleClose}
          token={token}
          viewerId={data.viewer_id}
        />
      ) : null}
    </>
  );
}
