"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 BoldIcon from "@/components/ui/BoldIcon";

function StoryRing({
  hasUnviewed,
  children,
}: {
  hasUnviewed: boolean;
  children: React.ReactNode;
}) {
  if (hasUnviewed) {
    return (
      <div className="rounded-full bg-gradient-to-tr from-[#feda75] via-[#d62976] to-[#962fbf] p-[2.5px]">
        <div className="rounded-full bg-background p-[2px]">{children}</div>
      </div>
    );
  }
  return (
    <div className="rounded-full border-2 border-neutral-300 dark:border-neutral-600 p-[1px]">
      {children}
    </div>
  );
}

function StoryAvatar({
  profileImage,
  userName,
  size = 56,
}: {
  profileImage?: string;
  userName?: string;
  size?: number;
}) {
  return (
    <div
      className="relative shrink-0 overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-800"
      style={{ width: size, height: size }}
    >
      <Image
        src={profileImage ? buildStorageUrl(profileImage) : "/images/fake-avatar.png"}
        alt={userName || "user"}
        fill
        className="object-cover"
        unoptimized
      />
    </div>
  );
}

export default function StoriesBar() {
  const token = Cookies.get("token") || "";
  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;

  return (
    <>
      <div className="border-b border-neutral-200/80 bg-background py-3 dark:border-neutral-800">
        <div
          ref={scrollRef}
          className="flex gap-3 overflow-x-auto px-3 pb-1 scrollbar-hide"
          style={{ WebkitOverflowScrolling: "touch" }}
        >
          {/* Your story */}
          <div className="flex w-[72px] shrink-0 flex-col items-center gap-1">
            <div className="relative">
              {hasMyStory ? (
                <button
                  type="button"
                  onClick={() => {
                    const idx = feed.findIndex((f) => f.user._id === viewerId);
                    openViewer(idx >= 0 ? idx : 0);
                  }}
                  className="block"
                >
                  <StoryRing hasUnviewed={false}>
                    <StoryAvatar
                      profileImage={myStory?.user.profile_image}
                      userName={myStory?.user.user_name}
                    />
                  </StoryRing>
                </button>
              ) : (
                <Link href="/new-post?type=story" className="block">
                  <StoryRing hasUnviewed={false}>
                    <StoryAvatar profileImage={undefined} userName="شما" />
                  </StoryRing>
                </Link>
              )}
              <Link
                href="/new-post?type=story"
                className="absolute -bottom-0.5 -right-0.5 flex h-5 w-5 items-center justify-center rounded-full border-2 border-background bg-[#0095f6] text-white"
                aria-label="افزودن استوری"
              >
                <BoldIcon name="add" size={14} tinted className="text-white" />
              </Link>
            </div>
            <span className="max-w-[72px] truncate text-[11px] text-neutral-800 dark:text-neutral-200">
              استوری شما
            </span>
          </div>

          {isLoading &&
            [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"
              />
            ))}

          {!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-[72px] shrink-0 flex-col items-center gap-1"
                  >
                    <StoryRing hasUnviewed={item.has_unviewed}>
                      <StoryAvatar
                        profileImage={item.user.profile_image}
                        userName={item.user.user_name}
                      />
                    </StoryRing>
                    <span className="max-w-[72px] truncate 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}
        />
      )}
    </>
  );
}
