"use client";

import { SeriesItem } from "@/components/home/home.type";
import { useHomeSeriesCarousalData } from "@/state/home/home.action";
import { formatTitle } from "@/lib/common-function";
import { useSettingsStore } from "@/state/store/settings.store";
import { ChevronLeft, ChevronRight, Play } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import React, { useEffect, useRef, useState } from "react";
import { ImageConstant } from "../../../constant/ImageConstant";

const resolvePoster = (item: SeriesItem) => {
  const src =
    item?.thumbnail_high_3x4 ??
    item?.thumbnail_high_9x16 ??
    item?.series_thumbnail ??
    item?.thumbnail_high_1x1;

  if (!src) return ImageConstant.imagePlaceHolder;
  return src.startsWith("http")
    ? src
    : `${process.env.NEXT_PUBLIC_IMAGE_BASE_URL}/${src}`;
};

const RailCard: React.FC<{ item: SeriesItem }> = ({ item }) => {
  const [imgSrc, setImgSrc] = useState(resolvePoster(item));
  const tag = item?.content_tag?.name?.trim();
  const isHot = ["HOT", "TRENDING"].includes((tag ?? "").toUpperCase());

  return (
    <Link
      href={
        item?.series_id
          ? `/series/${item.series_id}`
          : `/video/${item?.video_id}`
      }
      className="group relative w-36 shrink-0 snap-start overflow-hidden rounded-lg border border-white/10 bg-[#141014] transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_16px_32px_-12px_rgba(0,0,0,0.7)] sm:w-40 lg:w-44"
    >
      <div className="relative aspect-[2/3] overflow-hidden bg-[#1c1418]">
        <Image
          src={imgSrc}
          alt={`Poster for ${item?.title ?? "series"}`}
          fill
          sizes="176px"
          onError={() => setImgSrc(ImageConstant.imagePlaceHolder)}
          className="object-cover transition-transform duration-500 ease-out group-hover:scale-105"
        />

        {tag && (
          <span
            className={`absolute left-2.5 top-2.5 rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ${
              isHot ? "text-white" : "bg-[#2A2124] text-white/80"
            }`}
            style={
              isHot
                ? {
                    background: item?.content_tag?.color || "#ED3A57",
                    color: item?.content_tag?.text_color || "#FFFFFF",
                  }
                : undefined
            }
          >
            {tag}
          </span>
        )}

        <div
          aria-hidden="true"
          className="absolute inset-x-0 bottom-0 h-3/5"
          style={{
            background:
              "linear-gradient(180deg, rgba(10,7,9,0) 0%, rgba(10,7,9,0.55) 45%, rgba(10,7,9,0.95) 100%)",
          }}
        />

        <div className="absolute inset-x-0 bottom-0 p-3">
          <h4 className="line-clamp-2 text-[12px] font-semibold leading-snug text-white">
            {item?.title}
          </h4>
          <p className="mt-0.5 text-[11px] tabular-nums text-white/60">
            {item?.total_episodes ? `${item.total_episodes} eps` : "Feature"}
          </p>
        </div>

        <div className="pointer-events-none absolute inset-0 flex items-center justify-center opacity-0 transition-all duration-300 group-hover:opacity-100">
          <span className="flex h-12 w-12 scale-75 items-center justify-center rounded-full bg-[#ED3A57] text-white shadow-[0_8px_24px_rgba(0,0,0,0.6)] transition-transform duration-300 group-hover:scale-100">
            <Play className="ml-0.5 h-5 w-5 fill-current" aria-hidden="true" />
          </span>
        </div>
      </div>
    </Link>
  );
};

const RailCardSkeleton = () => (
  <div className="aspect-[2/3] w-36 shrink-0 animate-pulse rounded-lg bg-gray-800 sm:w-40 lg:w-44" />
);

const useInView = <T extends HTMLElement>() => {
  const ref = useRef<T>(null);
  const [inView, setInView] = useState(false);

  useEffect(() => {
    const node = ref.current;
    if (!node || inView) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0]?.isIntersecting) {
          setInView(true);
          observer.disconnect();
        }
      },
      { rootMargin: "300px 0px" }
    );

    observer.observe(node);
    return () => observer.disconnect();
  }, [inView]);

  return { ref, inView };
};

const CategoryRail: React.FC<{
  label: string;
  items: SeriesItem[];
  isLoading?: boolean;
}> = ({ label, items, isLoading }) => {
  const trackRef = useRef<HTMLDivElement>(null);
  const { ref: sectionRef, inView } = useInView<HTMLElement>();

  const scrollBy = (direction: number) =>
    trackRef.current?.scrollBy({ left: direction * 480, behavior: "smooth" });

  if (!isLoading && items.length === 0) return null;

  return (
    <section ref={sectionRef} aria-label={`${label} shows`}>
      <div className="flex items-end justify-between gap-4">
        <h3 className="text-[20px] md:text-[24px] font-extrabold uppercase tracking-wide text-white">
          {label}
        </h3>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => scrollBy(-1)}
            aria-label={`Scroll ${label} left`}
            className="hidden h-9 w-9 cursor-pointer items-center justify-center rounded-full border border-white/15 bg-[#141014] text-gray-400 transition-colors hover:border-[#ED3A57]/50 hover:text-[#ED3A57] sm:flex"
          >
            <ChevronLeft className="h-4 w-4" aria-hidden="true" />
          </button>
          <button
            type="button"
            onClick={() => scrollBy(1)}
            aria-label={`Scroll ${label} right`}
            className="hidden h-9 w-9 cursor-pointer items-center justify-center rounded-full border border-white/15 bg-[#141014] text-gray-400 transition-colors hover:border-[#ED3A57]/50 hover:text-[#ED3A57] sm:flex"
          >
            <ChevronRight className="h-4 w-4" aria-hidden="true" />
          </button>
        </div>
      </div>

      <div
        ref={trackRef}
        className="no-scrollbar mt-5 flex snap-x snap-mandatory gap-4 overflow-x-auto pb-2"
      >
        {isLoading || !inView
          ? Array.from({ length: 6 })?.map((_, index) => (
              <RailCardSkeleton key={index} />
            ))
          : items?.map((item, index) => (
              <RailCard key={item?.series_id ?? index} item={item} />
            ))}
      </div>
    </section>
  );
};

const CategoryRails = () => {
  const { language, country, hasHydrated } = useSettingsStore();

  const { data: carousalData, isLoading } = useHomeSeriesCarousalData(
    {
      language: language?.language_id,
      country: country?.country_id,
    },
    // Not just hydration: on a first visit nothing is stored, and the header
    // only picks a default once the language list loads. Firing before that
    // costs a full duplicate of this response.
    { enabled: hasHydrated && !!language?.language_id }
  );

  const shelves = Object.keys(carousalData ?? {}).filter(
    (key) => (carousalData?.[key]?.length ?? 0) > 0
  );

  if (!isLoading && shelves.length === 0) return null;

  return (
    <section
      id="categories"
      className="scroll-mt-24 border-y border-white/10 bg-[#100a0d] py-24 md:py-32"
    >
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <p className="text-xs font-bold uppercase tracking-[0.24em] text-[#ED3A57]">
          Categories
        </p>
        <div className="mt-3 flex flex-wrap items-end justify-between gap-4">
          <h2 className="max-w-xl text-[36px] md:text-[48px] font-extrabold leading-[1.1] tracking-tight text-white">
            Pick your shelf
          </h2>
          <p className="max-w-sm text-[14px] leading-relaxed text-gray-400">
            Separate rails for every mood — exactly like a streaming theater,
            sized for your pocket.
          </p>
        </div>

        <div className="mt-14 space-y-14">
          {isLoading
            ? Array.from({ length: 3 })?.map((_, index) => (
                <CategoryRail
                  key={index}
                  label=""
                  items={[]}
                  isLoading
                />
              ))
            : shelves?.map((key) => (
                <CategoryRail
                  key={key}
                  label={formatTitle(key)}
                  items={carousalData?.[key] ?? []}
                />
              ))}
        </div>
      </div>
    </section>
  );
};

export default CategoryRails;
