"use client";

import React, { useCallback, useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import Cookies from "js-cookie";
import {
  fetchStoriesFeed,
  StoryFeedUser,
} from "@/api/fetchStories";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import StoryViewer from "@/components/stories/StoryViewer";
import StoryRing, {
  STORY_AVATAR_SIZE,
  STORY_RING_OUTER_SIZE,
  verifyBadgeToTierColor,
} from "@/components/stories/StoryRing";
import BoldIcon from "@/components/ui/BoldIcon";
import { useTranslation } from "react-i18next";

function StoryAvatar({
  profileImage,
  userName,
}: {
  profileImage?: string;
  userName?: string;
}) {
  return (
    <Image
      src={profileImage ? buildStorageUrl(profileImage) : "/images/fake-avatar.png"}
      alt={userName || "user"}
      width={STORY_AVATAR_SIZE}
      height={STORY_AVATAR_SIZE}
      className="block h-full w-full object-cover"
      unoptimized
    />
  );
}

function StoryAvatarShell({ children }: { children: React.ReactNode }) {
  return (
    <div
      className="relative shrink-0 overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-800"
      style={{ width: STORY_RING_OUTER_SIZE, height: STORY_RING_OUTER_SIZE }}
    >
      {children}
    </div>
  );
}

type StoriesBarProps = {
  /** از سرور (cookies()) — برای جلوگیری از hydration mismatch */
  token?: string;
};

export default function StoriesBar({ token: serverToken = "" }: StoriesBarProps) {
  const { t } = useTranslation("common");
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);

  const clientToken = mounted ? Cookies.get("token") || "" : serverToken;
  const token = serverToken || clientToken;
  const queryClient = useQueryClient();
  const scrollRef = useRef<HTMLDivElement>(null);
  const [viewerOpen, setViewerOpen] = useState(false);
  const [viewerStartIndex, setViewerStartIndex] = useState(0);

  const { data, isLoading } = useQuery({
    queryKey: ["stories-feed", token],
    queryFn: () => fetchStoriesFeed(token),
    enabled: !!token,
    refetchInterval: 60_000,
  });

  const feed = data?.feed ?? [];
  const viewerId = data?.viewer_id;
  const myStory = data?.my_story;
  const hasMyStory = Boolean(myStory?.stories?.length);

  const openViewer = (index: number) => {
    setViewerStartIndex(index);
    setViewerOpen(true);
  };

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

  if (!token) return null;

  const showDynamicFeed = mounted;
  const showFeedLoading = !mounted || isLoading;

  return (
    <>
      <div className="bg-background pt-1">
        <div
          ref={scrollRef}
          className="flex gap-3 overflow-x-auto pb-1 scrollbar-hide"
          style={{ WebkitOverflowScrolling: "touch" }}
        >
          {/* Your story */}
          <div className="flex w-[80px] shrink-0 flex-col items-center gap-1">
            <div className="relative" style={{ width: STORY_RING_OUTER_SIZE, height: STORY_RING_OUTER_SIZE }}>
              {showDynamicFeed && hasMyStory ? (
                <button
                  type="button"
                  onClick={() => {
                    const idx = feed.findIndex((f) => f.user._id === viewerId);
                    openViewer(idx >= 0 ? idx : 0);
                  }}
                  className="block"
                >
                  <StoryRing hasStory forceGradient avatarSize={STORY_AVATAR_SIZE}>
                    <StoryAvatar
                      profileImage={myStory?.user.profile_image}
                      userName={myStory?.user.user_name}
                    />
                  </StoryRing>
                </button>
              ) : (
                <Link href="/new-post?type=story" className="block">
                  <StoryAvatarShell>
                    <StoryAvatar
                      profileImage={
                        showDynamicFeed ? myStory?.user.profile_image : undefined
                      }
                      userName={t("stories.you")}
                    />
                  </StoryAvatarShell>
                </Link>
              )}
              <Link
                href="/new-post?type=story"
                className="absolute -bottom-0.5 -right-0.5 z-20 flex h-5 w-5 items-center justify-center rounded-full border-2 border-background bg-[#0095f6] text-white shadow-sm"
                aria-label={t("stories.addStory")}
              >
                <BoldIcon name="add" size={14} tinted className="text-white" />
              </Link>
            </div>
            <span className="max-w-[80px] truncate text-center text-[11px] text-neutral-800 dark:text-neutral-200">
              {t("stories.yourStory")}
            </span>
          </div>

          {showFeedLoading &&
            [1, 2, 3, 4].map((i) => (
              <div
                key={i}
                className="h-14 w-14 shrink-0 animate-pulse rounded-full bg-neutral-200 dark:bg-neutral-800"
              />
            ))}

          {showDynamicFeed &&
            !isLoading &&
            feed
              .filter((item) => item.user._id !== viewerId)
              .map((item, index) => {
                const realIndex = feed.findIndex(
                  (f) => f.user._id === item.user._id
                );
                const displayName =
                  item.user.user_name ||
                  [item.user.first_name, item.user.last_name]
                    .filter(Boolean)
                    .join(" ");
                return (
                  <button
                    key={item.user._id}
                    type="button"
                    onClick={() => openViewer(realIndex >= 0 ? realIndex : index)}
                    className="flex w-[80px] shrink-0 flex-col items-center gap-1"
                  >
                    <StoryRing
                      hasStory
                      hasUnviewed={item.has_unviewed}
                      tierColor={verifyBadgeToTierColor(item.user.verify_badge)}
                      avatarSize={STORY_AVATAR_SIZE}
                    >
                      <StoryAvatar
                        profileImage={item.user.profile_image}
                        userName={item.user.user_name}
                      />
                    </StoryRing>
                    <span className="max-w-[80px] truncate text-center text-[11px] text-neutral-800 dark:text-neutral-200">
                      {displayName}
                    </span>
                  </button>
                );
              })}
        </div>
      </div>

      {viewerOpen && feed.length > 0 && (
        <StoryViewer
          feed={feed}
          initialUserIndex={viewerStartIndex}
          onClose={handleClose}
          token={token}
          viewerId={viewerId}
        />
      )}
    </>
  );
}
