'use client';

import React, { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { motion } from 'framer-motion';
import { FiPlay, FiHeart, FiStar, FiClock, FiCalendar, FiFilm } from 'react-icons/fi';
import VideoPlayer from '@/components/player/VideoPlayer';
import Button from '@/components/ui/Button';
import Badge from '@/components/ui/Badge';
import ContentRow from '@/components/content/ContentRow';
import { formatDuration, formatRating } from '@/lib/utils';
import { moviesApi } from '@/lib/api';
import { useProfileStore } from '@/stores/profileStore';
import type { Movie } from '@/types';
import { DetailsSkeleton } from '@/components/ui/Skeleton';
import { cn } from '@/lib/utils';

export default function MovieDetailPage() {
  const params = useParams();
  const movieId = params?.id as string;
  const [movie, setMovie] = useState<Movie | null>(null);
  const [showPlayer, setShowPlayer] = useState(false);
  const { toggleFavorite, isFavorite } = useProfileStore();
  const isFav = isFavorite(movieId);
  const [relatedMovies, setRelatedMovies] = useState<Movie[]>([]);
  const [categoryMovies, setCategoryMovies] = useState<Movie[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [recentSearches, setRecentSearches] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadMovieData() {
      try {
        const response = await moviesApi.getAll(1, 100);
        const allMovies = response.data || [];
        const found = allMovies.find(m => String(m.id) === String(movieId));
        if (found) {
          setMovie(found);
          setRelatedMovies(allMovies.filter(m => String(m.id) !== String(movieId)).slice(0, 10));
        } else if (allMovies.length > 0) {
          setMovie(allMovies[0]);
          setRelatedMovies(allMovies.slice(1, 11));
        }
      } catch (err) {
        console.error('Error loading movie details:', err);
      } finally {
        setLoading(false);
      }
    }
    loadMovieData();
  }, [movieId]);

  // Load other movies in the same category for the sidebar quick-selector
  useEffect(() => {
    if (!movie) return;
    const catId = movie.categoryId;
    async function loadCategoryMovies() {
      try {
        const res = await moviesApi.getAll(1, 100, catId);
        setCategoryMovies(res.data || []);
      } catch (err) {
        console.error('Error loading category movies:', err);
      }
    }
    loadCategoryMovies();
  }, [movie]);

  // Load recent searches from localStorage
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('cat_tv_recent_movie_searches');
      if (saved) {
        try { setRecentSearches(JSON.parse(saved)); } catch (_) {}
      }
    }
  }, []);

  const saveSearchQuery = (q: string) => {
    if (!q || q.trim() === '') return;
    const clean = q.trim();
    setRecentSearches((prev) => {
      const filtered = prev.filter((item) => item.toLowerCase() !== clean.toLowerCase());
      const updated = [clean, ...filtered].slice(0, 5);
      localStorage.setItem('cat_tv_recent_movie_searches', JSON.stringify(updated));
      return updated;
    });
  };

  if (loading) {
    return <DetailsSkeleton />;
  }

  if (!movie) {
    return (
      <div className="flex h-[50vh] flex-col items-center justify-center gap-4">
        <p className="text-white/60">Película no encontrada</p>
      </div>
    );
  }

  const filteredSidebarMovies = categoryMovies.filter(m =>
    m.title.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleMovieSelect = (m: Movie) => {
    saveSearchQuery(searchQuery);
    setMovie(m);
    setShowPlayer(true);
    setSearchQuery('');
    if (typeof window !== 'undefined') {
      window.history.replaceState(null, '', `/movies/${m.id}`);
    }
  };

  // Movie Details Content element
  const renderDetails = () => (
    <div className="max-w-4xl font-sans">
      {/* Genres */}
      <div className="flex items-center gap-2 mb-3 flex-wrap">
        {movie.genres?.map(genre => (
          <Badge key={genre} variant="neutral" size="sm">{genre}</Badge>
        ))}
        {movie.quality && (
          <Badge variant="accent" size="sm">{movie.quality}</Badge>
        )}
      </div>

      {/* Title */}
      <h1 className="text-2xl md:text-4xl font-black text-white leading-tight mb-2">
        {movie.title}
      </h1>
      {movie.originalTitle && (
        <p className="text-white/40 text-sm mb-4">{movie.originalTitle}</p>
      )}

      {/* Meta */}
      <div className="flex items-center gap-4 mb-6 flex-wrap text-sm">
        <div className="flex items-center gap-1 text-yellow-400">
          <FiStar size={16} className="fill-yellow-400" />
          <span className="font-bold">{formatRating(movie.rating)}</span>
        </div>
        <span className="flex items-center gap-1 text-white/60">
          <FiCalendar size={14} /> {movie.year}
        </span>
        <span className="flex items-center gap-1 text-white/60">
          <FiClock size={14} /> {formatDuration(movie.duration)}
        </span>
        {movie.views && (
          <span className="flex items-center gap-1 text-white/60">
            <FiFilm size={14} /> {movie.views.toLocaleString()} vistas
          </span>
        )}
      </div>

      {/* Synopsis */}
      <p className="text-white/70 leading-relaxed mb-6 max-w-2xl text-sm">
        {movie.synopsis}
      </p>

      {/* Director & Cast */}
      {(movie.director || movie.cast) && (
        <div className="space-y-2 mb-6 text-xs">
          {movie.director && (
            <p className="text-white/40">
              <span className="text-white/60 font-medium">Director:</span> {movie.director}
            </p>
          )}
          {movie.cast && movie.cast.length > 0 && (
            <p className="text-white/40">
              <span className="text-white/60 font-medium">Reparto:</span> {movie.cast.join(', ')}
            </p>
          )}
        </div>
      )}

      {/* Actions */}
      <div className="flex items-center gap-3">
        {!showPlayer && (
          <Button
            variant="primary"
            size="lg"
            icon={<FiPlay size={20} />}
            onClick={() => setShowPlayer(true)}
            className="shadow-lg shadow-primary/20"
          >
            Reproducir
          </Button>
        )}
        <Button
          variant={isFav ? 'primary' : 'secondary'}
          size="lg"
          icon={<FiHeart size={20} className={isFav ? 'fill-current' : ''} />}
          onClick={() => toggleFavorite(movieId)}
        >
          {isFav ? 'En Favoritos' : 'Favoritos'}
        </Button>
      </div>
    </div>
  );

  return (
    <div className="space-y-6 max-w-7xl mx-auto px-2">
      {showPlayer ? (
        /* Cinema Mode: Player on the left, Category Sidebar on the right */
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* Player & Info */}
          <div className="lg:col-span-3 space-y-6">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="relative rounded-xl bg-black aspect-video shadow-2xl border border-white/5 group"
            >
              {/* Cinematic Ambilight Glow */}
              <div className="absolute -inset-4 bg-gradient-to-tr from-primary/35 via-accent/20 to-purple-600/30 rounded-2xl blur-3xl opacity-40 group-hover:opacity-50 transition-opacity duration-1000 pointer-events-none -z-10 animate-pulse" style={{ animationDuration: '6s' }} />

              <div className="w-full h-full rounded-xl overflow-hidden">
                <VideoPlayer
                  streamUrl={movie.streamUrl || 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8'}
                  title={movie.title}
                  autoPlay
                  contentId={String(movie.id)}
                  contentType="movie"
                  categoryId={String(movie.categoryId)}
                  poster={movie.posterUrl || movie.backdropUrl}
                />
              </div>
            </motion.div>

            {/* Movie Info */}
            <div className="px-1 pb-12">
              {renderDetails()}
            </div>
          </div>

          {/* Quick Selector Category Sidebar */}
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            className="lg:col-span-1 flex flex-col h-[400px] lg:h-[500px] xl:h-[580px] bg-neutral-900/60 backdrop-blur-md rounded-xl overflow-hidden border border-white/5 group/sidebar"
          >
            {/* Sidebar Search and Header */}
            <div className="p-4 border-b border-white/5 bg-white/5">
              <h3 className="text-xs font-bold text-white uppercase tracking-wider mb-2.5 flex items-center gap-2 select-none">
                <span className="w-2 h-2 rounded-full bg-primary animate-pulse" />
                Películas en esta sección
              </h3>
              <div className="relative">
                <input
                  type="text"
                  placeholder="Buscar película..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full bg-black/40 border border-white/10 rounded-lg py-1.5 pl-3 pr-8 text-xs text-white placeholder-white/30 focus:outline-none focus:border-primary transition-colors"
                />
                {searchQuery && (
                  <button
                    onClick={() => setSearchQuery('')}
                    className="absolute right-2.5 top-1/2 -translate-y-1/2 text-white/40 hover:text-white text-xs font-bold"
                  >
                    ✕
                  </button>
                )}
              </div>
            </div>

            {/* Recent Searches bubbles */}
            {searchQuery.trim() === '' && recentSearches.length > 0 && (
              <div className="flex items-center gap-1.5 flex-wrap px-4 py-2 border-b border-white/5 bg-white/[0.02] select-none">
                <span className="text-[9px] uppercase font-bold text-white/30 tracking-wider">Recientes:</span>
                {recentSearches.map((s, idx) => (
                  <button
                    key={idx}
                    onClick={() => setSearchQuery(s)}
                    className="px-2 py-0.5 bg-white/5 hover:bg-white/10 text-white/60 hover:text-white border border-white/5 rounded-full text-[9px] font-semibold transition-all cursor-pointer"
                  >
                    {s}
                  </button>
                ))}
              </div>
            )}

            {/* List */}
            <div className="flex-1 overflow-y-auto divide-y divide-white/5 pr-1 scrollbar-thin scrollbar-thumb-white/10">
              {filteredSidebarMovies.length === 0 ? (
                <div className="p-6 text-center text-xs text-white/30 font-sans">
                  No se encontraron películas
                </div>
              ) : (
                filteredSidebarMovies.map((m) => {
                  const isActive = String(m.id) === String(movie.id);
                  return (
                    <button
                      key={m.id}
                      onClick={() => handleMovieSelect(m)}
                      className={cn(
                        'w-full flex items-center gap-3 p-3 text-left transition-all hover:bg-white/5 border-l-2',
                        isActive ? 'bg-primary/10 border-primary' : 'border-transparent hover:border-white/10'
                      )}
                    >
                      <div className="w-8 h-12 rounded bg-black/40 flex-shrink-0 overflow-hidden flex items-center justify-center border border-white/5">
                        {m.posterUrl ? (
                          <img src={m.posterUrl} alt="" className="w-full h-full object-cover" onError={(e) => { (e.target as HTMLImageElement).src = '/logo.png' }} />
                        ) : (
                          <span className="text-[10px] text-white/20 font-bold uppercase truncate max-w-full">{m.title.slice(0, 2)}</span>
                        )}
                      </div>
                      <div className="min-w-0 flex-1">
                        <p className={cn(
                          'text-xs font-semibold truncate',
                          isActive ? 'text-primary' : 'text-white/80'
                        )}>
                          {m.title}
                        </p>
                        <p className="text-[10px] text-white/45 truncate mt-0.5">{m.year} · ⭐ {m.rating || '7.0'}</p>
                      </div>
                    </button>
                  );
                })
              )}
            </div>
          </motion.div>
        </div>
      ) : (
        /* Immersive details view */
        <div className="-m-4 lg:-m-6">
          <div className="relative w-full h-[45vh] md:h-[55vh] overflow-hidden">
            <img
              src={movie.backdropUrl || movie.posterUrl}
              alt={movie.title}
              className="absolute inset-0 w-full h-full object-cover opacity-45 blur-[1px]"
            />
            <div className="absolute inset-0 bg-gradient-to-t from-dark via-dark/60 to-dark/30" />
            <div className="absolute inset-0 bg-gradient-to-r from-dark/80 via-transparent to-transparent" />
            <div className="absolute inset-0 flex items-center justify-center">
              <motion.button
                whileHover={{ scale: 1.1 }}
                whileTap={{ scale: 0.95 }}
                onClick={() => setShowPlayer(true)}
                className="w-24 h-24 rounded-full bg-primary/80 backdrop-blur flex items-center justify-center shadow-2xl shadow-primary/40 hover:bg-primary transition-all"
              >
                <FiPlay size={40} className="ml-2 text-white" />
              </motion.button>
            </div>
          </div>

          <div className="px-4 lg:px-6 pb-12 space-y-8 -mt-24 relative z-10">
            {renderDetails()}

            <ContentRow
              title="🎬 Películas Relacionadas"
              items={relatedMovies}
              type="movie"
            />
          </div>
        </div>
      )}
    </div>
  );
}
