"use client";

import { useCallback, useEffect, useState } from "react";
import { VideoCard } from "@/components/media/VideoCard";

import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchCategories } from "@/store/slices/categorySlice";
import { fetchVideoList } from "@/store/slices/videoListSlice";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";

/* ── Inline skeletons (reused from same pattern as HomePage) ─────────────── */

function VideoCardSkeleton() {
  return (
    <div className="rounded-xl overflow-hidden animate-pulse" style={{ background: "var(--card)" }}>
      <div className="aspect-video" style={{ background: "var(--deep)" }} />
      <div className="p-2.5 flex gap-2.5">
        <div className="w-7 h-7 rounded-full shrink-0 mt-0.5" style={{ background: "var(--deep)" }} />
        <div className="flex-1 flex flex-col gap-2 pt-0.5">
          <div className="h-3 rounded-full" style={{ background: "var(--deep)", width: "92%" }} />
          <div className="h-2.5 rounded-full" style={{ background: "var(--deep)", width: "60%" }} />
          <div className="h-2 rounded-full" style={{ background: "var(--deep)", width: "40%" }} />
        </div>
      </div>
    </div>
  );
}

function VideoGridSkeleton({ count = 8 }: { count?: number }) {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
      {Array.from({ length: count }).map((_, i) => <VideoCardSkeleton key={i} />)}
    </div>
  );
}

/* ── VideosPage ───────────────────────────────────────────────────────────── */

export default function VideosPage() {
  const dispatch = useAppDispatch();

  const { categories, isLoading: catsLoading } = useAppSelector(
    (s) => s.category,
  );
  const {
    videos: allItems,
    isLoading: videosLoading,
    isLoadingMore,
    hasMore,
    currentPage,
    activeCategoryId,
    error: videosError,
  } = useAppSelector((s) => s.videoList);

  const [activeChip, setActiveChip] = useState("All");

  /* Only show pure video items — filter out shorts and music */
  const videos = allItems.filter((v) => v.type === "video");

  const tabs = [
    { id: 0, name: "All" },
    ...categories.map((c) => ({ id: c.id, name: c.name })),
  ];

  useEffect(() => {
    dispatch(fetchCategories());
    dispatch(fetchVideoList({ categoryId: 0, pageNo: 1 }));
  }, [dispatch]);

  const handleLoadMore = useCallback(() => {
    dispatch(fetchVideoList({ categoryId: activeCategoryId, pageNo: currentPage + 1 }));
  }, [dispatch, activeCategoryId, currentPage]);

  const sentinelRef = useInfiniteScroll({
    hasMore,
    isLoading: videosLoading || isLoadingMore,
    onLoadMore: handleLoadMore,
  });

  const handleTabClick = (id: number, name: string) => {
    setActiveChip(name);
    dispatch(fetchVideoList({ categoryId: id, pageNo: 1 }));
  };

  const isAllTab = activeChip === "All";

  /* Banner: top 5 video items on "All" tab */
  const bannerItems =
    isAllTab && !videosLoading && videos.length > 0 ? videos.slice(0, 5) : [];

  return (
    <>
      {/* ── Category tabs ─────────────────────────────────────────────────── */}
      <div
        className="sticky z-20 border-b py-3"
        style={{
          top: "56px",
          background: "var(--bg)",
          borderColor: "var(--border-soft)",
        }}
      >
        <div className="relative">
          <div
            className="absolute left-0 top-0 bottom-0 w-9 pointer-events-none z-10"
            style={{
              background: "linear-gradient(90deg, var(--bg) 30%, transparent)",
            }}
          />
          <div className="flex gap-2 overflow-x-auto scrollbar-hide px-5">
            {catsLoading
              ? Array.from({ length: 7 }).map((_, i) => (
                  <div
                    key={i}
                    className="shrink-0 h-[30px] rounded-2xl animate-pulse"
                    style={{
                      width: i % 3 === 0 ? 72 : i % 3 === 1 ? 88 : 64,
                      background: "var(--card)",
                    }}
                  />
                ))
              : tabs.map((tab) => (
                  <button
                    key={tab.id}
                    onClick={() => handleTabClick(tab.id, tab.name)}
                    className="shrink-0 h-[30px] px-3 rounded-2xl text-xs font-medium whitespace-nowrap transition-all duration-150 border"
                    style={{
                      background:
                        activeChip === tab.name
                          ? "var(--accent)"
                          : "var(--card)",
                      color: activeChip === tab.name ? "#fff" : "#999",
                      borderColor:
                        activeChip === tab.name
                          ? "transparent"
                          : "var(--border)",
                      fontWeight: activeChip === tab.name ? 600 : 500,
                    }}
                  >
                    {tab.name}
                  </button>
                ))}
          </div>
          <div
            className="absolute right-0 top-0 bottom-0 w-9 pointer-events-none z-10"
            style={{
              background: "linear-gradient(270deg, var(--bg) 30%, transparent)",
            }}
          />
        </div>
      </div>

      {/* ── Video grid ────────────────────────────────────────────────────── */}
      <div className="flex flex-col gap-8 px-5 py-5 pb-16">
        <section>
          {videosLoading ? (
            <VideoGridSkeleton count={8} />
          ) : videosError ? (
            <div className="flex flex-col items-center justify-center py-16 gap-3">
              <svg
                width="36"
                height="36"
                viewBox="0 0 24 24"
                fill="none"
                stroke="#555"
                strokeWidth="1.2"
              >
                <circle cx="12" cy="12" r="10" />
                <line x1="12" y1="8" x2="12" y2="12" />
                <line x1="12" y1="16" x2="12.01" y2="16" />
              </svg>
              <p className="text-sm" style={{ color: "#888" }}>
                {videosError}
              </p>
            </div>
          ) : videos.length === 0 && !videosLoading ? (
            <div className="flex flex-col items-center justify-center py-16 gap-3">
              <svg
                width="40"
                height="40"
                viewBox="0 0 24 24"
                fill="none"
                stroke="#555"
                strokeWidth="1.2"
              >
                <rect x="2" y="7" width="20" height="15" rx="2" />
                <polyline points="17 2 12 7 7 2" />
              </svg>
              <p className="text-sm" style={{ color: "#888" }}>
                No videos in this category yet
              </p>
            </div>
          ) : (
            <>
              <div className="flex items-center justify-between mb-3.5">
                <h2
                  className="text-sm font-semibold tracking-tight flex items-center gap-2"
                  style={{ color: "var(--text-primary)", letterSpacing: "-0.005em" }}
                >
                  {isAllTab && (
                    <span
                      className="text-[10px] font-bold uppercase tracking-[0.16em]"
                      style={{ color: "var(--accent)" }}
                    >
                      🔥
                    </span>
                  )}
                  {isAllTab ? "Videos" : activeChip}
                </h2>
                <span
                  className="text-[10px] font-semibold"
                  style={{ color: "#555" }}
                >
                  {videos.length} video{videos.length !== 1 ? "s" : ""}
                </span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                {videos.map((v, i) => (
                  <VideoCard key={v.id} video={v} priority={i < 4} />
                ))}
              </div>
            </>
          )}
        </section>

        {/* Infinite scroll sentinel */}
        <div ref={sentinelRef} className="h-1" />

        {/* Loading more */}
        {isLoadingMore && (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {Array.from({ length: 4 }).map((_, i) => (
              <VideoCardSkeleton key={i} />
            ))}
          </div>
        )}

        {/* End of list */}
        {!hasMore && videos.length > 0 && !videosLoading && !isLoadingMore && (
          <p className="text-center text-xs py-4" style={{ color: "#555" }}>
            You&apos;ve reached the end
          </p>
        )}
      </div>
    </>
  );
}
