"use client";
import React, { useState, useEffect, useCallback } from "react";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  type CarouselApi,
} from "../ui/carousel";
import IconButton from "../icon-button/icon-button";
import { ChevronLeft, ChevronRight, Play, Star, Timer } from "lucide-react";
import Autoplay from "embla-carousel-autoplay";
import { StreamingHeroHomeProps } from "../home/home.type";
import Image from "next/image";
import Link from "next/link";
import { cn } from "@/lib/utils";

const StreamingHeroHome: React.FC<StreamingHeroHomeProps> = ({ data = [] }) => {
  const [api, setApi] = useState<CarouselApi>();
  const [current, setCurrent] = useState(0);

  useEffect(() => {
    if (!api) return;

    setCurrent(api.selectedScrollSnap());
    const onSelect = () => {
      setCurrent(api.selectedScrollSnap());
    };
    api.on("select", onSelect);
    return () => {
      api.off("select", onSelect);
    };
  }, [api]);

  const scrollPrev = useCallback(() => api?.scrollPrev(), [api]);
  const scrollNext = useCallback(() => api?.scrollNext(), [api]);
  const scrollTo = useCallback((index: number) => api?.scrollTo(index), [api]);

  if (!data || data.length === 0) {
    return <div className="h-screen bg-black" />;
  }

  return (
    <div className="relative h-screen overflow-hidden">
      <Carousel
        setApi={setApi}
        plugins={[Autoplay({ delay: 5000, stopOnInteraction: true })]}
        opts={{ align: "start", loop: true }}
        className="h-full"
      >
        <CarouselContent className="h-screen">
          {data?.map((slide, index) => {
            const content = slide.episode || slide.video;
            let href = "#";
            if (slide.type === "episode" && content) {
              href = `/series/${content.series_id}?episode=${content.episode_id}`;
            } else if (slide.type === "video" && content) {
              href = `/video/${content.video_id}`;
            }
            const backgroundImage =
              content?.thumbnail_high_16x9 ||
              slide.image ||
              content?.thumbnail_high_9x16 ||
              content?.thumbnail;
            const tags = content?.series?.tags || content?.tags || [];

            if (!backgroundImage) return null;

            return (
              <CarouselItem
                key={slide.id || index}
                className="relative h-full flex items-center bg-cover bg-center"
                style={{ backgroundImage: `url(${backgroundImage})` }}
              >
                <div className="absolute inset-0 bg-gradient-to-r from-black/80 via-black/60 to-transparent" />

                <div className="container mx-auto">
                  <div className="relative z-10 max-w-1xl space-y-6 px-4 md:px-6 text-white">
                    <h1 className="text-[40px] md:text-[75px] font-bold leading-tight line-clamp-2">
                      {content?.title || "Featured Content"}
                    </h1>

                    <div className="flex items-center text-sm flex-wrap gap-y-2">
                      {tags[0] && (
                        <span className="px-2 py-1 bg-[#672BFE] rounded-[7px] text-[14px] font-semibold mr-4">
                          {tags[0]}
                        </span>
                      )}
                      <div className="flex items-center space-x-1 mr-4">
                        <Star className="w-4 h-4 fill-yellow-400 text-yellow-400" />
                        <span className="font-semibold">
                          {content?.averageRating?.toFixed(1) || "N/A"}
                        </span>
                      </div>
                      <div className="flex items-center">
                        <Timer className="mr-1 w-4 h-4" />
                        <span className="text-gray-300">
                          {content?.duration ? `${content.duration} min` : ""}
                        </span>
                      </div>
                    </div>

                    <p className="text-[16px] font-normal leading-relaxed max-w-xl line-clamp-3">
                      {content?.description}
                    </p>

                    <div className="pt-4">
                      <Link href={href}>
                        <IconButton
                          label="Play Now"
                          icon={<Play className="w-5 h-5" />}
                          size="lg"
                          className="!p-3 !px-6"
                        />
                      </Link>
                    </div>
                  </div>
                </div>
                <div
                  className="pointer-events-none absolute bottom-0 w-full h-2/5 
             bg-gradient-to-t from-[#121212] to-transparent 
             md:max-h-[200px] z-10"
                />
              </CarouselItem>
            );
          })}
        </CarouselContent>
      </Carousel>

      <div className="hidden md:block absolute top-1/2 right-4 transform -translate-y-1/2 z-20">
        <div className="bg-black/40 backdrop-blur-md p-4 rounded-2xl">
          <div className="flex items-center gap-3">
            {data.length > 1 &&
              [current, (current + 1) % data.length]?.map(
                (slideIndex, displayIndex) => {
                  const slide = data[slideIndex];
                  const content = slide.episode || slide.video;
                  const thumbnail =
                    content?.thumbnail_high_3x4 ||
                    content?.thumbnail ||
                    content?.thumbnail ||
                    slide.image;
                  const isActive = displayIndex === 0;

                  if (!thumbnail) return null;

                  return (
                    <div
                      key={slide.id}
                      className={cn(
                        "relative overflow-hidden rounded-lg cursor-pointer transition-all duration-500",
                        isActive
                          ? "w-[200px] h-[300px] scale-100 opacity-100"
                          : "w-[200px] h-[300px] scale-100 opacity-70 hover:opacity-100 self-center"
                      )}
                      // Only the smaller, non-active thumbnail is clickable
                      onClick={() => !isActive && scrollTo(slideIndex)}
                    >
                      <Image
                        width={200}
                        height={300}
                        src={thumbnail}
                        alt={content?.title || "Thumbnail"}
                        className="object-cover w-full h-full"
                        quality={100}
                      />
                    </div>
                  );
                }
              )}
          </div>

          {/* Navigation */}
          <div className="flex items-center justify-left gap-4 mt-4">
            <button
              className="p-2 bg-black/50 rounded-full hover:bg-black/70 transition-colors cursor-pointer border border-white/50 hover:bg-gradient-to-r from-[#ED3A57] via-[#ED3A57] to-[#FD521E]"
              onClick={scrollPrev}
              aria-label="Previous"
            >
              <ChevronLeft className="w-5 h-5 text-white" />
            </button>
            <button
              className="p-2 bg-black/50 rounded-full hover:bg-black/70 transition-colors cursor-pointer border border-white/50 hover:bg-gradient-to-r from-[#ED3A57] via-[#ED3A57] to-[#FD521E]"
              onClick={scrollNext}
              aria-label="Next"
            >
              <ChevronRight className="w-5 h-5 text-white" />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default StreamingHeroHome;
