'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { FiPlay, FiHeart, FiStar, FiClock } from 'react-icons/fi';
import { cn, formatDuration, formatRating, getImageUrl } from '@/lib/utils';
import { PLACEHOLDER_POSTER } from '@/lib/constants';
import { favoritesApi } from '@/lib/api';
import toast from 'react-hot-toast';
import type { Movie, Series, Channel } from '@/types';

interface ContentCardProps {
  item: Movie | Series | Channel;
  type: 'movie' | 'series' | 'channel';
  size?: 'sm' | 'md' | 'lg';
  showInfo?: boolean;
  className?: string;
}

export default function ContentCard({
  item,
  type,
  size = 'md',
  showInfo = true,
  className,
}: ContentCardProps) {
  const router = useRouter();
  const [isFav, setIsFav] = useState((item as { isFavorite?: boolean }).isFavorite || false);
  const [imgError, setImgError] = useState(false);

  const getHref = () => {
    switch (type) {
      case 'movie': return `/movies/${item.id}`;
      case 'series': return `/series/${item.id}`;
      case 'channel': return `/tv/${item.id}`;
    }
  };

  const getTitle = () => {
    if (type === 'channel') return (item as Channel).name;
    return (item as Movie | Series).title;
  };

  const getImage = () => {
    if (type === 'channel') {
      return getImageUrl((item as Channel).logoUrl, PLACEHOLDER_POSTER);
    }
    return getImageUrl((item as Movie | Series).posterUrl, PLACEHOLDER_POSTER);
  };

  const handleClick = () => {
    router.push(getHref());
  };

  const handleFavorite = async (e: React.MouseEvent) => {
    e.stopPropagation();
    try {
      await favoritesApi.toggle(type, item.id);
      setIsFav(!isFav);
      toast.success(isFav ? 'Eliminado de favoritos' : 'Agregado a favoritos');
    } catch {
      toast.error('Error al actualizar favoritos');
    }
  };

  const sizeClasses = {
    sm: 'w-[140px] md:w-[160px]',
    md: 'w-[180px] md:w-[220px]',
    lg: 'w-[220px] md:w-[280px]',
  };

  const movie = item as Movie;
  const series = item as Series;
  const channel = item as Channel;

  return (
    <motion.div
      whileHover={{ scale: 1.05, zIndex: 10 }}
      transition={{ duration: 0.3 }}
      onClick={handleClick}
      className={cn(
        'content-card card-shine group',
        sizeClasses[size],
        className
      )}
    >
      {/* Image */}
      <div className={cn(
        'relative overflow-hidden rounded-card bg-dark-200 border border-transparent transition-all duration-300 group-hover:border-primary/80 group-hover:shadow-lg group-hover:shadow-primary/30',
        type === 'channel' ? 'aspect-video' : 'aspect-[2/3]'
      )}>
        <img
          src={imgError ? PLACEHOLDER_POSTER : getImage()}
          alt={getTitle()}
          className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
          onError={() => setImgError(true)}
          loading="lazy"
        />

        {/* Gradient overlay */}
        <div className="absolute inset-0 bg-card-gradient opacity-0 group-hover:opacity-100 transition-opacity duration-300" />

        {/* Live indicator for channels */}
        {type === 'channel' && channel.isLive && (
          <div className="absolute top-2 left-2 flex items-center gap-1.5 bg-red-600/90 backdrop-blur-sm px-2 py-0.5 rounded text-xs font-semibold">
            <span className="w-1.5 h-1.5 bg-white rounded-full animate-pulse" />
            EN VIVO
          </div>
        )}

        {/* Quality badge */}
        {type === 'movie' && movie.quality && (
          <div className="absolute top-2 right-2 bg-dark/80 backdrop-blur-sm px-1.5 py-0.5 rounded text-[10px] font-bold text-accent border border-accent/30">
            {movie.quality}
          </div>
        )}

        {/* Rating */}
        {(type === 'movie' || type === 'series') && (
          <div className="absolute top-2 left-2 flex items-center gap-1 bg-dark/80 backdrop-blur-sm px-1.5 py-0.5 rounded text-xs">
            <FiStar size={10} className="text-yellow-400 fill-yellow-400" />
            <span className="text-yellow-400 font-semibold">
              {formatRating(type === 'movie' ? movie.rating : series.rating)}
            </span>
          </div>
        )}

        {/* Hover overlay with actions */}
        <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300">
          <motion.button
            whileHover={{ scale: 1.15 }}
            whileTap={{ scale: 0.9 }}
            className="w-12 h-12 rounded-full bg-primary flex items-center justify-center shadow-lg shadow-primary/40"
          >
            <FiPlay size={20} className="ml-0.5" />
          </motion.button>
        </div>

        {/* Favorite button */}
        <button
          onClick={handleFavorite}
          className={cn(
            'absolute top-2 right-2 p-1.5 rounded-full transition-all duration-300',
            'opacity-0 group-hover:opacity-100',
            isFav
              ? 'bg-primary text-white'
              : 'bg-dark/60 backdrop-blur-sm text-white/70 hover:text-white'
          )}
        >
          <FiHeart size={14} className={cn(isFav && 'fill-current')} />
        </button>
      </div>

      {/* Info */}
      {showInfo && (
        <div className="mt-2 px-0.5">
          <h3 className="text-sm font-semibold text-white line-clamp-1 group-hover:text-primary transition-colors">
            {getTitle()}
          </h3>
          <div className="flex items-center gap-2 mt-0.5">
            {type === 'movie' && (
              <>
                <span className="text-xs text-white/40">{movie.year}</span>
                <span className="text-xs text-white/20">•</span>
                <span className="text-xs text-white/40 flex items-center gap-1">
                  <FiClock size={10} />
                  {formatDuration(movie.duration)}
                </span>
              </>
            )}
            {type === 'series' && (
              <>
                <span className="text-xs text-white/40">{series.year}</span>
                <span className="text-xs text-white/20">•</span>
                <span className="text-xs text-white/40">{series.totalSeasons} temp.</span>
              </>
            )}
            {type === 'channel' && (
              <span className="text-xs text-primary font-semibold truncate block max-w-full flex items-center gap-1 select-none">
                <span className="w-1.5 h-1.5 rounded-full bg-primary animate-pulse" />
                {channel.currentProgram ? channel.currentProgram : (channel.category?.name || 'General')}
              </span>
            )}
          </div>
        </div>
      )}
    </motion.div>
  );
}
