'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { FiPlay, FiInfo, FiStar, FiClock } from 'react-icons/fi';
import Button from '@/components/ui/Button';
import { cn, truncate, formatDuration, formatRating, getImageUrl } from '@/lib/utils';
import { PLACEHOLDER_BACKDROP } from '@/lib/constants';
import type { Movie, Series } from '@/types';

interface HeroBannerProps {
  items: (Movie | Series)[];
  type: 'movie' | 'series';
}

export default function HeroBanner({ items, type }: HeroBannerProps) {
  const router = useRouter();
  const [current, setCurrent] = useState(0);

  // Automatic rotation timer
  useEffect(() => {
    if (items.length <= 1) return;
    const interval = setInterval(() => {
      setCurrent((prev) => (prev + 1) % items.length);
    }, 6000);
    return () => clearInterval(interval);
  }, [items.length]);

  if (items.length === 0) return null;

  const item = items[current];
  const movie = item as Movie;
  const series = item as Series;
  const title = type === 'movie' ? movie.title : series.title;
  const synopsis = item.synopsis;
  const year = item.year;
  const backdropUrl = getImageUrl(item.backdropUrl, PLACEHOLDER_BACKDROP);
  const rating = item.rating;

  const handlePlay = () => {
    router.push(type === 'movie' ? `/movies/${item.id}` : `/series/${item.id}`);
  };

  return (
    <div className="relative w-full h-[50vh] md:h-[65vh] lg:h-[75vh] overflow-hidden -mt-16">
      {/* Background image */}
      <AnimatePresence mode="wait">
        <motion.div
          key={current}
          initial={{ opacity: 0, scale: 1.05 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.8 }}
          className="absolute inset-0"
        >
          <img
            src={backdropUrl}
            alt={title}
            className="w-full h-full object-cover"
          />
        </motion.div>
      </AnimatePresence>

      {/* Gradient overlays */}
      <div className="absolute inset-0 bg-gradient-to-t from-dark via-dark/40 to-dark/20" />
      <div className="absolute inset-0 bg-gradient-to-r from-dark/80 via-transparent to-transparent" />

      {/* Content */}
      <div className="absolute bottom-0 left-0 right-0 p-6 md:p-12 lg:p-16">
        <AnimatePresence mode="wait">
          <motion.div
            key={current}
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            transition={{ duration: 0.5 }}
            className="max-w-2xl"
          >
            {/* Genres/tags */}
            <div className="flex items-center gap-2 mb-3">
              <span className="text-primary font-bold text-sm tracking-wider uppercase">
                {type === 'movie' ? 'Película' : 'Serie'}
              </span>
              {item.genres?.slice(0, 3).map((genre, i) => (
                <React.Fragment key={genre}>
                  <span className="text-white/30">•</span>
                  <span className="text-sm text-white/60">{genre}</span>
                </React.Fragment>
              ))}
            </div>

            {/* Title */}
            <h1 className="text-3xl md:text-5xl lg:text-6xl font-black text-white leading-tight mb-3">
              {title}
            </h1>

            {/* Meta */}
            <div className="flex items-center gap-4 mb-4">
              <div className="flex items-center gap-1">
                <FiStar size={16} className="text-yellow-400 fill-yellow-400" />
                <span className="text-yellow-400 font-bold">{formatRating(rating)}</span>
              </div>
              <span className="text-white/60">{year}</span>
              {type === 'movie' && (
                <span className="text-white/60 flex items-center gap-1">
                  <FiClock size={14} />
                  {formatDuration(movie.duration)}
                </span>
              )}
              {type === 'series' && (
                <span className="text-white/60">{series.totalSeasons} Temporadas</span>
              )}
              {type === 'movie' && movie.quality && (
                <span className="px-1.5 py-0.5 border border-accent/40 text-accent text-xs font-bold rounded">
                  {movie.quality}
                </span>
              )}
            </div>

            {/* Synopsis */}
            <p className="text-white/70 text-sm md:text-base leading-relaxed mb-6 max-w-xl">
              {truncate(synopsis, 200)}
            </p>

            {/* Actions */}
            <div className="flex items-center gap-3">
              <Button
                variant="primary"
                size="lg"
                icon={<FiPlay size={20} />}
                onClick={handlePlay}
                className="shadow-lg shadow-primary/30"
              >
                Reproducir
              </Button>
              <Button
                variant="secondary"
                size="lg"
                icon={<FiInfo size={20} />}
                onClick={handlePlay}
              >
                Más Info
              </Button>
            </div>
          </motion.div>
        </AnimatePresence>

        {/* Dots indicator */}
        {items.length > 1 && (
          <div className="flex items-center gap-2 mt-8">
            {items.slice(0, 5).map((_, i) => (
              <button
                key={i}
                onClick={() => setCurrent(i)}
                className={cn(
                  'h-1 rounded-full transition-all duration-300',
                  i === current
                    ? 'w-8 bg-primary'
                    : 'w-4 bg-white/30 hover:bg-white/50'
                )}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
