'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useParams } from 'next/navigation';
import { motion } from 'framer-motion';
import { FiPlay, FiHeart, FiStar, 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 Dropdown from '@/components/ui/Dropdown';
import EpisodeList from '@/components/content/EpisodeList';
import ContentRow from '@/components/content/ContentRow';
import { formatRating } from '@/lib/utils';
import { seriesApi } from '@/lib/api';
import { useProfileStore } from '@/stores/profileStore';
import type { Series, Episode } from '@/types';
import { DetailsSkeleton } from '@/components/ui/Skeleton';
import { cn } from '@/lib/utils';

export default function SeriesDetailPage() {
  const params = useParams();
  const seriesId = params?.id as string;
  const [series, setSeries] = useState<Series | null>(null);
  const [selectedSeason, setSelectedSeason] = useState('1');
  const [showPlayer, setShowPlayer] = useState(false);
  const [currentEpisode, setCurrentEpisode] = useState<Episode | null>(null);
  const { toggleFavorite, isFavorite, watchProgress, activeProfile } = useProfileStore();
  const isFav = isFavorite(seriesId);
  const [relatedSeries, setRelatedSeries] = useState<Series[]>([]);
  const [categorySeries, setCategorySeries] = useState<Series[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [recentSearches, setRecentSearches] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingDetails, setLoadingDetails] = useState(false);
  const hasAutoResumedRef = useRef(false);

  useEffect(() => {
    hasAutoResumedRef.current = false;
  }, [seriesId]);

  useEffect(() => {
    async function loadSeriesData() {
      try {
        const [detail, allSeriesRes] = await Promise.all([
          seriesApi.getById(seriesId),
          seriesApi.getAll(1, 50).catch(() => ({ data: [] as Series[] }))
        ]);

        setSeries(detail);

        if (detail.seasons && detail.seasons.length > 0) {
          setSelectedSeason(String(detail.seasons[0].number));
          if (detail.seasons[0].episodes && detail.seasons[0].episodes.length > 0) {
            setCurrentEpisode(detail.seasons[0].episodes[0]);
          }
        }

        const allSeriesList = allSeriesRes.data || [];
        setRelatedSeries(allSeriesList.filter(s => String(s.id) !== String(seriesId)).slice(0, 10));
      } catch (err) {
        console.error('Error loading series details:', err);
      } finally {
        setLoading(false);
      }
    }
    loadSeriesData();
  }, [seriesId]);

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

  // Premium Auto-Resume: Detect last watched episode and pre-select it
  useEffect(() => {
    if (loading || !series || !activeProfile || hasAutoResumedRef.current) return;

    const profileProgress = watchProgress[activeProfile.id] || [];
    // Find all watch progress records belonging to this series
    const seriesWatchItems = profileProgress.filter(p => p.seriesId === String(series.id));

    if (seriesWatchItems.length > 0) {
      // Sort to find the latest updated record
      const latestItem = seriesWatchItems.reduce((prev, curr) => 
        new Date(prev.updatedAt).getTime() > new Date(curr.updatedAt).getTime() ? prev : curr
      );

      // Find the season and episode object
      let foundEpisode: Episode | null = null;
      let foundSeasonNumber = '1';

      if (series.seasons) {
        for (const season of series.seasons) {
          const ep = season.episodes?.find(e => String(e.id) === String(latestItem.contentId));
          if (ep) {
            foundEpisode = ep;
            foundSeasonNumber = String(season.number);
            break;
          }
        }
      }

      if (foundEpisode) {
        setSelectedSeason(foundSeasonNumber);
        setCurrentEpisode(foundEpisode);
        hasAutoResumedRef.current = true;
        console.log('📌 Auto-Resume pre-selected last watched episode:', foundEpisode.title, 'Season:', foundSeasonNumber);
      }
    }
  }, [loading, series, activeProfile, watchProgress]);

  // Load recent searches from localStorage
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('cat_tv_recent_series_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_series_searches', JSON.stringify(updated));
      return updated;
    });
  };

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

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

  const currentSeasonObj = series.seasons?.find(s => String(s.number) === selectedSeason);
  const rawEpisodes = currentSeasonObj?.episodes || [];

  // Map progress and watched stats dynamically to the episodes list
  const profileProgress = activeProfile ? watchProgress[activeProfile.id] || [] : [];
  const episodes = rawEpisodes.map(episode => {
    const progressItem = profileProgress.find(p => String(p.contentId) === String(episode.id));
    if (progressItem) {
      const progressPercent = (progressItem.currentTime / progressItem.duration) * 100;
      const watched = progressPercent > 90;
      return {
        ...episode,
        progress: progressPercent,
        watched
      };
    }
    return episode;
  });

  const seasonOptions = series.seasons?.map(s => ({
    value: String(s.number),
    label: `Temporada ${s.number}`,
  })) || [];

  const statusMap: Record<string, { label: string; variant: 'success' | 'warning' | 'danger' }> = {
    ongoing: { label: 'En emisión', variant: 'success' },
    ended: { label: 'Finalizada', variant: 'neutral' as never },
    cancelled: { label: 'Cancelada', variant: 'danger' },
  };
  const statusInfo = statusMap[series.status] || statusMap.ongoing;

  const handlePlayEpisode = (episode: Episode) => {
    hasAutoResumedRef.current = true;
    setCurrentEpisode(episode);
    setShowPlayer(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const filteredSidebarSeries = categorySeries.filter(s =>
    s.title.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleSeriesSelect = async (s: Series) => {
    hasAutoResumedRef.current = false;
    saveSearchQuery(searchQuery);
    setLoadingDetails(true);
    setSearchQuery('');
    try {
      const detail = await seriesApi.getById(s.id);
      setSeries(detail);
      if (detail.seasons && detail.seasons.length > 0) {
        setSelectedSeason(String(detail.seasons[0].number));
        const firstEpisode = detail.seasons[0].episodes?.[0] || null;
        setCurrentEpisode(firstEpisode);
        setShowPlayer(false); // Let user see new series details first
      } else {
        setCurrentEpisode(null);
        setShowPlayer(false);
      }
      if (typeof window !== 'undefined') {
        window.history.replaceState(null, '', `/series/${s.id}`);
      }
    } catch (err) {
      console.error('Error switching series:', err);
    } finally {
      setLoadingDetails(false);
    }
  };

  // Render info details
  const renderDetails = () => (
    <div className="max-w-4xl font-sans">
      <div className="flex items-center gap-2 mb-3 flex-wrap">
        {series.genres?.map(g => (
          <Badge key={g} variant="neutral" size="sm">{g}</Badge>
        ))}
        <Badge variant={statusInfo.variant} size="sm">{statusInfo.label}</Badge>
      </div>

      <h1 className="text-2xl md:text-4xl font-black text-white leading-tight mb-4">
        {series.title}
      </h1>

      <div className="flex items-center gap-4 mb-4 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(series.rating)}</span>
        </div>
        <span className="flex items-center gap-1 text-white/60">
          <FiCalendar size={14} />
          {series.year}{series.endYear ? `–${series.endYear}` : ''}
        </span>
        <span className="text-white/60 font-semibold">{series.totalSeasons} Temporadas</span>
        <span className="text-white/60 font-semibold">{series.totalEpisodes} Episodios</span>
      </div>

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

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

      <div className="flex items-center gap-3">
        <Button
          variant="primary"
          size="lg"
          icon={<FiPlay size={20} />}
          onClick={() => {
            if (currentEpisode) {
              handlePlayEpisode(currentEpisode);
            } else if (rawEpisodes.length > 0) {
              handlePlayEpisode(rawEpisodes[0]);
            }
          }}
          className="shadow-lg shadow-primary/20"
        >
          {currentEpisode && profileProgress.some(p => String(p.contentId) === String(currentEpisode.id))
            ? 'Reanudar Episodio'
            : 'Reproducir'}
        </Button>
        <Button
          variant={isFav ? 'primary' : 'secondary'}
          size="lg"
          icon={<FiHeart size={20} className={isFav ? 'fill-current' : ''} />}
          onClick={() => toggleFavorite(seriesId)}
        >
          {isFav ? 'En Favoritos' : 'Favoritos'}
        </Button>
      </div>
    </div>
  );

  return (
    <div className="space-y-6 max-w-7xl mx-auto px-2">
      {showPlayer && currentEpisode ? (
        /* Cinema Mode: Player on the left, Category Selector Sidebar on the right */
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          
          {/* Player, Info & Episodes */}
          <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={currentEpisode.streamUrl}
                  title={`${series.title} — T${selectedSeason} E${currentEpisode.number}: ${currentEpisode.title}`}
                  autoPlay
                  contentId={String(currentEpisode.id)}
                  contentType="series"
                  categoryId={String(series.categoryId)}
                  seriesId={String(series.id)}
                  poster={currentEpisode.thumbnailUrl || series.posterUrl || series.backdropUrl}
                />
              </div>
            </motion.div>

            {/* Info details */}
            <div className="px-1 space-y-8">
              {renderDetails()}

              {/* Season Selector & Episodes List */}
              {seasonOptions.length > 0 && (
                <div className="bg-neutral-900/40 p-6 rounded-xl border border-white/5">
                  <div className="flex items-center justify-between mb-6">
                    <h2 className="text-xl font-bold text-white font-sans">Episodios</h2>
                    <Dropdown
                      options={seasonOptions}
                      value={selectedSeason}
                      onChange={setSelectedSeason}
                      size="sm"
                      className="w-48"
                    />
                  </div>
                  <EpisodeList
                    episodes={episodes}
                    onPlay={handlePlayEpisode}
                    currentEpisodeId={currentEpisode?.id}
                  />
                </div>
              )}
            </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"
          >
            <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" />
                Series en esta sección
              </h3>
              <div className="relative">
                <input
                  type="text"
                  placeholder="Buscar serie..."
                  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>
            )}

            <div className="flex-1 overflow-y-auto divide-y divide-white/5 pr-1 scrollbar-thin scrollbar-thumb-white/10 font-sans">
              {filteredSidebarSeries.length === 0 ? (
                <div className="p-6 text-center text-xs text-white/30">
                  No se encontraron series
                </div>
              ) : (
                filteredSidebarSeries.map((s) => {
                  const isActive = String(s.id) === String(series.id);
                  return (
                    <button
                      key={s.id}
                      onClick={() => handleSeriesSelect(s)}
                      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">
                        {s.posterUrl ? (
                          <img src={s.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">{s.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'
                        )}>
                          {s.title}
                        </p>
                        <p className="text-[10px] text-white/45 truncate mt-0.5">{s.year} · {s.totalSeasons} Temp</p>
                      </div>
                    </button>
                  );
                })
              )}
            </div>
          </motion.div>

        </div>
      ) : (
        /* Original Single Column Backdrop View */
        <div className="-m-4 lg:-m-6">
          <div className="relative w-full h-[40vh] md:h-[50vh] overflow-hidden">
            <img
              src={series.backdropUrl || series.posterUrl}
              alt={series.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>

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

            {seasonOptions.length > 0 && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.2 }}
                className="glass-card p-6 rounded-xl border border-white/5 bg-neutral-900/40"
              >
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-bold text-white font-sans">Episodios</h2>
                  <Dropdown
                    options={seasonOptions}
                    value={selectedSeason}
                    onChange={setSelectedSeason}
                    size="sm"
                    className="w-48"
                  />
                </div>
                <EpisodeList
                  episodes={episodes}
                  onPlay={handlePlayEpisode}
                  currentEpisodeId={currentEpisode?.id}
                />
              </motion.div>
            )}

            {relatedSeries.length > 0 && (
              <ContentRow
                title="📺 Series Similares"
                items={relatedSeries}
                type="series"
              />
            )}
          </div>
        </div>
      )}
    </div>
  );
}
