'use client';

import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { FiUsers, FiRadio, FiGrid, FiPlus, FiX } from 'react-icons/fi';
import VideoPlayer from '@/components/player/VideoPlayer';
import ContentRow from '@/components/content/ContentRow';
import Badge from '@/components/ui/Badge';
import { channelsApi } from '@/lib/api';
import type { Channel } from '@/types';
import Spinner from '@/components/ui/Spinner';
import { cn } from '@/lib/utils';
import PinVerificationModal from '@/components/auth/PinVerificationModal';

export default function ChannelPlayerPage() {
  const params = useParams();
  const router = useRouter();
  const channelId = params?.id as string;
  const [channel, setChannel] = useState<Channel | null>(null);
  const [categoryChannels, setCategoryChannels] = useState<Channel[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(true);
  const [recentSearches, setRecentSearches] = useState<string[]>([]);

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

  // Adult Channel PIN lock states
  const [isPinAuthorized, setIsPinAuthorized] = useState(() => {
    if (typeof window !== 'undefined') {
      return sessionStorage.getItem('cat_tv_adult_authorized') === 'true';
    }
    return false;
  });
  const [pendingChannel, setPendingChannel] = useState<Channel | null>(null);
  const [showPinModal, setShowPinModal] = useState(false);

  // Multiview states
  const [isMultiview, setIsMultiview] = useState(false);
  const [slots, setSlots] = useState<(Channel | null)[]>([null, null, null, null]);
  const [selectedSlotIndex, setSelectedSlotIndex] = useState(0);

  const isAdultChannel = (ch: Channel) => {
    const categoryName = ch.category?.name?.toLowerCase() || '';
    const channelName = ch.name?.toLowerCase() || '';
    return (
      categoryName.includes('adult') || 
      categoryName.includes('xxx') || 
      categoryName.includes('18+') || 
      categoryName.includes('red light') ||
      channelName.includes('xxx') ||
      channelName.includes('adult')
    );
  };

  useEffect(() => {
    async function loadChannelData() {
      try {
        const [allChannels, categories] = await Promise.all([
          channelsApi.getAll(),
          channelsApi.getCategories()
        ]);
        
        // Map category object to each channel based on categoryId
        const mappedChannels = allChannels.map(ch => {
          const category = categories.find(cat => String(cat.id) === String(ch.categoryId));
          return {
            ...ch,
            category: category || { id: ch.categoryId, name: 'General', slug: 'general' }
          };
        });

        const found = mappedChannels.find(ch => String(ch.id) === String(channelId));
        const activeCh = found || mappedChannels[0];

        if (activeCh) {
          setChannel(activeCh);
          setSlots([activeCh, null, null, null]);
          const sameCat = mappedChannels.filter(ch => String(ch.categoryId) === String(activeCh.categoryId));
          setCategoryChannels(sameCat);

          if (isAdultChannel(activeCh) && !isPinAuthorized) {
            setPendingChannel(activeCh);
            setShowPinModal(true);
          }
        }
      } catch (err) {
        console.error('Error loading channel details:', err);
      } finally {
        setLoading(false);
      }
    }
    loadChannelData();
  }, [channelId, isPinAuthorized]);

  const playChannelDirectly = (ch: Channel) => {
    if (isMultiview) {
      const newSlots = [...slots];
      newSlots[selectedSlotIndex] = ch;
      setSlots(newSlots);

      // Auto-select next empty slot
      const nextEmpty = newSlots.findIndex(s => s === null);
      if (nextEmpty !== -1) {
        setSelectedSlotIndex(nextEmpty);
      } else {
        setSelectedSlotIndex((selectedSlotIndex + 1) % 4);
      }
    } else {
      setChannel(ch);
      setSlots([ch, null, null, null]);
      if (typeof window !== 'undefined') {
        window.history.replaceState(null, '', `/tv/${ch.id}`);
      }
    }
  };

  const handleChannelSelect = (ch: Channel) => {
    saveSearchQuery(searchQuery);
    if (isAdultChannel(ch) && !isPinAuthorized) {
      setPendingChannel(ch);
      setShowPinModal(true);
      return;
    }
    playChannelDirectly(ch);
  };


  if (loading) {
    return (
      <div className="flex h-[80vh] items-center justify-center">
        <Spinner size="lg" color="primary" />
      </div>
    );
  }

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

  // Filter channels in the sidebar based on search query
  const filteredSidebarChannels = categoryChannels.filter(ch =>
    ch.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="space-y-6 max-w-7xl mx-auto px-2">
      {/* Two-Column Cinema/Player Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        
        {/* Left Column: Player & Info (3/4 width) */}
        <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">
            {!isMultiview ? (
              isAdultChannel(channel) && !isPinAuthorized ? (
                <div className="w-full h-full flex flex-col items-center justify-center bg-neutral-950 gap-4 p-4 border border-white/5 rounded-xl select-none font-sans">
                  <div className="w-16 h-16 rounded-full bg-red-500/10 border border-red-500/20 flex items-center justify-center text-red-500">
                    <span className="text-3xl">🔒</span>
                  </div>
                  <div className="text-center space-y-1">
                    <h3 className="text-sm font-bold text-white uppercase tracking-wider">Contenido Bloqueado</h3>
                    <p className="text-xs text-white/40">Este canal requiere autorización de PIN de seguridad.</p>
                  </div>
                  <button
                    onClick={() => {
                      setPendingChannel(channel);
                      setShowPinModal(true);
                    }}
                    className="px-4 py-2 bg-primary hover:bg-primary/95 text-white text-xs font-bold rounded-lg transition-all shadow-md active:scale-95 cursor-pointer"
                  >
                    Ingresar PIN de Seguridad
                  </button>
                </div>
              ) : (
                <VideoPlayer
                  streamUrl={channel.streamUrl}
                  title={channel.name}
                  autoPlay
                  contentId={String(channel.id)}
                  contentType="live"
                  categoryId={String(channel.categoryId)}
                  poster={channel.logoUrl}
                />
              )
            ) : (
              <div className="w-full h-full bg-neutral-950 p-2 grid grid-cols-2 grid-rows-2 gap-2">
                {slots.map((slot, index) => {
                  const isSelected = selectedSlotIndex === index;
                  return (
                    <div
                      key={index}
                      onClick={() => setSelectedSlotIndex(index)}
                      className={cn(
                        "relative aspect-video rounded-lg overflow-hidden border-2 bg-black/80 transition-all cursor-pointer flex flex-col justify-center items-center group/slot",
                        isSelected ? "border-primary shadow-lg shadow-primary/10" : "border-white/5 hover:border-white/20"
                      )}
                    >
                      {slot ? (
                        <>
                          <VideoPlayer
                            streamUrl={slot.streamUrl}
                            title={slot.name}
                            autoPlay
                            muted={selectedSlotIndex !== index}
                            contentId={String(slot.id)}
                            contentType="live"
                            categoryId={String(slot.categoryId)}
                            poster={slot.logoUrl}
                          />
                          
                          {/* Remove slot channel */}
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              const newSlots = [...slots];
                              newSlots[index] = null;
                              setSlots(newSlots);
                            }}
                            className="absolute top-2 right-2 p-1.5 rounded-full bg-black/60 text-white/60 hover:text-white hover:bg-primary transition-all z-20 opacity-0 group-hover/slot:opacity-100"
                            title="Quitar canal"
                          >
                            <FiX size={12} />
                          </button>
                          
                          {/* Audio indicator */}
                          {isSelected && (
                            <span className="absolute bottom-2 left-2 px-1.5 py-0.5 rounded bg-primary text-white text-[9px] font-bold tracking-wide uppercase select-none z-20 animate-pulse">
                              Audio Activo
                            </span>
                          )}
                        </>
                      ) : (
                        <div className="flex flex-col items-center gap-1.5 p-4 text-center select-none">
                          <div className="w-8 h-8 rounded-full bg-white/5 flex items-center justify-center text-white/40 group-hover/slot:bg-white/10 transition-all">
                            <FiPlus size={16} />
                          </div>
                          <span className="text-[10px] font-semibold text-white/40">Agregar Canal</span>
                          <span className="text-[8px] text-white/25 max-w-[120px] leading-tight hidden sm:inline">Selecciona esta pantalla y haz clic en un canal del menú</span>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
            </div>
          </motion.div>

          {/* Channel info */}
          <motion.div
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="glass-card p-6 rounded-xl"
          >
            <div className="flex items-start justify-between flex-wrap gap-4">
              <div className="space-y-2">
                <div className="flex items-center gap-3 flex-wrap">
                  <h1 className="text-2xl font-bold text-white truncate max-w-[300px] sm:max-w-md">
                    {isMultiview && slots[selectedSlotIndex] ? slots[selectedSlotIndex]?.name : channel.name}
                  </h1>
                  <Badge variant="success" size="md">
                    <span className="w-1.5 h-1.5 bg-green-400 rounded-full animate-pulse" />
                    EN VIVO
                  </Badge>

                  {/* Multiview Toggle Button */}
                  <button
                    onClick={() => {
                      const nextMode = !isMultiview;
                      setIsMultiview(nextMode);
                      if (nextMode) {
                        setSlots([channel, null, null, null]);
                        setSelectedSlotIndex(1);
                      } else {
                        const activeCh = slots[selectedSlotIndex] || slots[0] || channel;
                        setChannel(activeCh);
                        setSlots([activeCh, null, null, null]);
                        if (activeCh && typeof window !== 'undefined') {
                          window.history.replaceState(null, '', `/tv/${activeCh.id}`);
                        }
                      }
                    }}
                    className={cn(
                      "flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold transition-all border select-none ml-2",
                      isMultiview 
                        ? "bg-primary/20 text-primary border-primary/30" 
                        : "bg-white/5 text-white/70 border-white/10 hover:bg-white/10 hover:text-white"
                    )}
                  >
                    <FiGrid size={13} />
                    {isMultiview ? "Desactivar Multipantalla" : "Multipantalla (2-4 Canales)"}
                  </button>
                </div>
                
                {isMultiview && (
                  <p className="text-[11px] text-white/50 bg-white/5 px-2.5 py-1 rounded-lg border border-white/5 inline-block">
                    💡 <span className="font-semibold text-white/70">Tip Multipantalla:</span> Haz clic en cualquiera de las 4 pantallas (borde iluminado) y luego selecciona un canal de la lista lateral para reproducirlo. El sonido proviene del canal activo seleccionado.
                  </p>
                )}

                {(!isMultiview && channel.currentProgram) && (
                  <p className="text-white/60 text-sm flex items-center gap-2">
                    <FiRadio size={14} className="text-primary" />
                    Ahora: <span className="text-white/80 font-medium">{channel.currentProgram}</span>
                  </p>
                )}
                {(!isMultiview && channel.description) && (
                  <p className="text-white/40 text-sm mt-2 max-w-xl">{channel.description}</p>
                )}
              </div>
              <div className="flex items-center gap-4 text-white/40 text-sm">
                {channel.category && (
                  <Badge variant="neutral">{channel.category.name}</Badge>
                )}
              </div>
            </div>
          </motion.div>
        </div>

        {/* Right Column: Sidebar Quick Selector (1/4 width) */}
        <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] glass-card rounded-xl overflow-hidden border border-white/5"
        >
          {/* 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" />
              Canales en esta sección
            </h3>
            {/* Search Input */}
            <div className="relative">
              <input
                type="text"
                placeholder="Buscar canal..."
                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">
            {filteredSidebarChannels.length === 0 ? (
              <div className="p-6 text-center text-xs text-white/30">
                No se encontraron canales
              </div>
            ) : (
              filteredSidebarChannels.map((ch) => {
                const isActive = isMultiview 
                  ? slots.some(s => s && String(s.id) === String(ch.id))
                  : String(ch.id) === String(channel.id);
                return (
                  <button
                    key={ch.id}
                    onClick={() => handleChannelSelect(ch)}
                    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'
                    )}
                  >
                    {/* Logo */}
                    <div className="w-10 h-10 rounded bg-black/40 flex-shrink-0 overflow-hidden flex items-center justify-center border border-white/5">
                      {ch.logoUrl ? (
                        <img src={ch.logoUrl} alt="" className="w-full h-full object-contain" onError={(e) => { (e.target as HTMLImageElement).src = 'https://placehold.co/100x100/1e1e24/fff?text=TV' }} />
                      ) : (
                        <span className="text-[10px] text-white/20 font-bold uppercase">{ch.name.slice(0, 2)}</span>
                      )}
                    </div>

                    {/* Text info */}
                    <div className="min-w-0 flex-1">
                      <p className={cn(
                        'text-xs font-semibold truncate',
                        isActive ? 'text-primary' : 'text-white/80'
                      )}>
                        {ch.name}
                      </p>
                      {ch.currentProgram && (
                        <p className="text-[10px] text-white/40 truncate mt-0.5">{ch.currentProgram}</p>
                      )}
                    </div>
                  </button>
                );
              })
            )}
          </div>
        </motion.div>

      </div>

      {/* Adult PIN Verification Lock Modal */}
      {showPinModal && (
        <PinVerificationModal
          onSuccess={() => {
            setIsPinAuthorized(true);
            if (typeof window !== 'undefined') {
              sessionStorage.setItem('cat_tv_adult_authorized', 'true');
            }
            setShowPinModal(false);
            if (pendingChannel) {
              playChannelDirectly(pendingChannel);
              setPendingChannel(null);
            }
          }}
          onClose={() => {
            setShowPinModal(false);
            setPendingChannel(null);
            if (!channel) {
              router.push('/tv'); // Redirect back to TV list if initial load was cancelled
            }
          }}
        />
      )}
    </div>
  );
}
