"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { VideoCard } from "@/components/media/VideoCard";
import { ReelCard } from "@/components/media/ReelCard";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchCategories } from "@/store/slices/categorySlice";
import { fetchVideoList } from "@/store/slices/videoListSlice";
import { fetchReelsList } from "@/store/slices/reelsListSlice";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
import { useTranslation } from "@/i18n";
import { MotionSection, MotionItem } from "@/components/motion/MotionSection";

const REELS_INJECT_AT = 8;

/* ── skeleton atoms ──────────────────────────────────────────────────────── */

function SectionHeadSkeleton() {
  return (
    <div className="flex items-center justify-between mb-3.5">
      <div
        className="h-4 w-28 rounded-full animate-pulse"
        style={{ background: "var(--card)" }}
      />
      <div
        className="h-3 w-12 rounded-full animate-pulse"
        style={{ background: "var(--card)" }}
      />
    </div>
  );
}

function VideoCardSkeleton() {
  return (
    <div
      className="rounded-xl overflow-hidden animate-pulse"
      style={{ background: "var(--card)" }}
    >
      {/* Thumbnail */}
      <div className="aspect-video" style={{ background: "var(--deep)" }} />
      {/* Meta row */}
      <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>
  );
}

function ReelCardSkeleton() {
  return (
    <div
      className="shrink-0 flex flex-col gap-2 animate-pulse"
      style={{ width: 160 }}
    >
      <div
        className="rounded-[10px]"
        style={{ width: 160, height: 284, background: "var(--card)" }}
      />
      <div
        className="h-2.5 rounded-full"
        style={{ background: "var(--card)", width: "85%" }}
      />
      <div
        className="h-2 rounded-full"
        style={{ background: "var(--card)", width: "55%" }}
      />
    </div>
  );
}

function ReelsShelfSkeleton() {
  return (
    <div className="flex gap-2.5 overflow-hidden">
      {Array.from({ length: 5 }).map((_, i) => (
        <ReelCardSkeleton key={i} />
      ))}
    </div>
  );
}

/* ── layout helpers ──────────────────────────────────────────────────────── */

function SectionHead({
  title,
  kicker,
}: {
  title: string;
  kicker?: React.ReactNode;
}) {
  return (
    <div className="flex items-center justify-between mb-3.5">
      <h2
        className="text-sm font-semibold  tracking-tight flex items-center gap-2 whitespace-nowrap"
        style={{ letterSpacing: "-0.005em", color: "var(--text-muted)" }}
      >
        {kicker}
        {title}
      </h2>
    </div>
  );
}

function Shelf({
  children,
  innerRef,
}: {
  children: React.ReactNode;
  innerRef?: React.RefObject<HTMLDivElement>;
}) {
  return (
    <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
        ref={innerRef}
        className="flex gap-2.5 overflow-x-auto scrollbar-hide pb-1"
      >
        {children}
      </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>
  );
}

/* ── main component ──────────────────────────────────────────────────────── */

export default function HomePage() {
  const dispatch = useAppDispatch();
  const { t } = useTranslation();

  const { categories, isLoading: catsLoading } = useAppSelector(
    (s) => s.category,
  );
  const {
    videos,
    isLoading: videosLoading,
    isLoadingMore,
    hasMore,
    currentPage,
    activeCategoryId,
    error: videosError,
  } = useAppSelector((s) => s.videoList);
  const {
    reels,
    isLoading: reelsLoading,
    isLoadingMore: reelsLoadingMore,
    hasMore: reelsHasMore,
    currentPage: reelsPage,
  } = useAppSelector((s) => s.reelsList);

  const [activeChip, setActiveChip] = useState("All");
  /* reels shelf horizontal infinite scroll */
  const reelsShelfRef = useRef<HTMLDivElement>(null);

  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(fetchReelsList(1));
  }, [dispatch]);

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

  const handleLoadMoreReels = useCallback(() => {
    dispatch(fetchReelsList(reelsPage + 1));
  }, [dispatch, reelsPage]);

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

  const reelsSentinelRef = useInfiniteScroll({
    hasMore: reelsHasMore,
    isLoading: reelsLoadingMore,
    onLoadMore: handleLoadMoreReels,
    rootRef: reelsShelfRef,
  });

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

  const isAllTab = activeChip === "All";
  const videosAbove = videos.slice(0, REELS_INJECT_AT);
  const videosBelow = videos.slice(REELS_INJECT_AT);

  return (
    <>
      {/* ── Category tabs ─────────────────────────────────────────────────── */}
      <div
        className="sticky z-20 border-b py-3"
        style={{
          top: "0px",
          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>

      {/* ── Page content ──────────────────────────────────────────────────── */}
      <div className="flex flex-col gap-8 px-5 py-5 pb-16">
        {/* Music shelf — All tab only (static, no skeleton needed) */}
        {/* {isAllTab && (
          <>
            <section>
              <SectionHead title="Music" />
              <Shelf>{MUSIC.map((m) => <MusicCard key={m.id} {...m} />)}</Shelf>
            </section>
            <section>
              <SectionHead title="Podcasts" />
              <Shelf>{PODCASTS.map((p) => <PodcastCard key={p.id} {...p} />)}</Shelf>
            </section>
          </>
        )} */}

        {/* ── Video row 1 ──────────────────────────────────────────────────── */}
        <section>
          {videosLoading ? (
            <>
              <SectionHeadSkeleton />
              <VideoGridSkeleton count={REELS_INJECT_AT} />
            </>
          ) : 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 ?? t("state_error")}
              </p>
            </div>
          ) : videos.length === 0 ? (
            <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" }}>
                {t("home_noVideos")}
              </p>
            </div>
          ) : (
            <>
              <SectionHead
                title={isAllTab ? t("home_videos") : activeChip}
                kicker={
                  isAllTab ? (
                    <span
                      className="text-[10px] font-bold uppercase tracking-[0.16em] mr-1"
                      style={{ color: "var(--accent)" }}
                    >
                      🔥
                    </span>
                  ) : undefined
                }
              />
              <MotionSection className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                {videosAbove.map((v, i) => (
                  <MotionItem key={v.id}>
                    <VideoCard video={v} priority={i < 4} />
                  </MotionItem>
                ))}
              </MotionSection>
            </>
          )}
        </section>

        {/* ── Reels shelf (between row 1 and row 2) ──────────────────────── */}
        {isAllTab && (
          <section>
            {reelsLoading ? (
              <>
                <SectionHeadSkeleton />
                <ReelsShelfSkeleton />
              </>
            ) : reels.length === 0 ? null : (
              <>
                <SectionHead
                  title={t("home_reels")}
                  kicker={
                    <span
                      className="text-[10px] font-bold uppercase tracking-[0.16em] mr-1"
                      style={{ color: "var(--accent)" }}
                    >
                      ▶
                    </span>
                  }
                />
                <Shelf innerRef={reelsShelfRef}>
                  {reels.map((r) => (
                    <ReelCard
                      key={r.id}
                      id={r.id}
                      caption={r.caption}
                      likes={r.likes}
                      image={r.image}
                      hue={r.hue}
                    />
                  ))}
                  {/* sentinel triggers next page load when scrolled into view */}
                  <div ref={reelsSentinelRef} className="shrink-0 w-1" />
                  {reelsLoadingMore && (
                    <>
                      <ReelCardSkeleton />
                      <ReelCardSkeleton />
                    </>
                  )}
                </Shelf>
              </>
            )}
          </section>
        )}
        {/* ── Video row 2+ ─────────────────────────────────────────────────── */}
        {videosLoading ? (
          <section>
            <VideoGridSkeleton count={4} />
          </section>
        ) : videosBelow.length > 0 ? (
          <section>
            <MotionSection className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
              {videosBelow.map((v) => (
                <MotionItem key={v.id}>
                  <VideoCard video={v} />
                </MotionItem>
              ))}
            </MotionSection>
          </section>
        ) : null}

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

        {/* Loading more — show skeleton cards while next page loads */}
        {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" }}>
            {t("home_reachedEnd")}
          </p>
        )}
      </div>
    </>
  );
}
