"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 Link from "next/link";
import Image from "next/image";
import HeroFramePlayer from "./hero-frame-player";

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]);

  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: 3500, 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 ||
              "/continuebanner.png";
            const tags = content?.series?.tags || content?.tags || [];

            return (
              <CarouselItem
                key={slide.id || index}
                className="relative h-full flex items-center"
              >
                <SlideBackground src={backgroundImage} eager={index === 0} />

                <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-10 lg:right-16 xl:right-24 transform -translate-y-1/2 z-20">
        <div className="relative">
          <div
            aria-hidden="true"
            className="pointer-events-none absolute -inset-8 rounded-[3rem] bg-[#ED3A57]/10 blur-3xl"
          />
          <div className="relative flex items-center gap-3">
            {(() => {
              const slide = data[current];
              const content = slide?.episode || slide?.video;
              const poster =
                slide?.image ||
                content?.thumbnail_high_9x16 ||
                content?.thumbnail_high_3x4 ||
                content?.thumbnail ||
                content?.thumbnail_high_16x9 ||
                undefined;

              const epNum = (content as unknown as Record<string, unknown>)?.episode_number || (current + 1);
              const duration = content?.duration ? `${content.duration}s` : "89s";
              const titleText = content?.title;

              return (
                <div className="relative w-[270px] h-[480px] overflow-hidden rounded-2xl ring-1 ring-white/15 shadow-2xl">
                  <HeroFramePlayer
                    poster={poster}
                    title={titleText}
                    autoQueuedText="Next episode auto-queued"
                    episodeBadgeText={`EP ${epNum} · NOW PLAYING`}
                    durationBadgeText={`${duration} · episode complete`}
                  />
                </div>
              );
            })()}
          </div>

          {/* Navigation */}
          <div className="relative 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>
  );
};

const FALLBACK_BACKGROUND = "/continuebanner.png";

/**
 * The slide backdrop is the page's LCP element. It goes through next/image so
 * it is served resized and in a modern format, and the first slide is marked
 * eager so the browser preloads it instead of waiting for hydration.
 */
const SlideBackground: React.FC<{ src: string; eager: boolean }> = ({
  src,
  eager,
}) => {
  const [failed, setFailed] = useState(false);

  return (
    <Image
      src={failed ? FALLBACK_BACKGROUND : src}
      alt=""
      aria-hidden
      fill
      sizes="100vw"
      className="object-cover object-center"
      priority={eager}
      loading={eager ? undefined : "lazy"}
      onError={() => setFailed(true)}
    />
  );
};

export default StreamingHeroHome;
