'use client';

import React, { useState, useEffect, useRef } from 'react';
import { motion } from 'framer-motion';
import { useRouter } from 'next/navigation';
import { FiTv, FiClock, FiPlay, FiChevronLeft, FiChevronRight, FiCalendar } from 'react-icons/fi';
import { channelsApi } from '@/lib/api';
import type { Channel } from '@/types';
import Spinner from '@/components/ui/Spinner';
import Badge from '@/components/ui/Badge';

interface EpgProgram {
  title: string;
  description?: string;
  startTimestamp: number;
  endTimestamp: number;
}

export default function TVGuidePage() {
  const router = useRouter();
  const [channels, setChannels] = useState<Channel[]>([]);
  const [epgData, setEpgData] = useState<Record<string, EpgProgram[]>>({});
  const [loading, setLoading] = useState(true);
  const timelineScrollRef = useRef<HTMLDivElement>(null);
  
  // Hours timeline starting from 2 hours ago to 10 hours ahead
  const [timeSlots, setTimeSlots] = useState<Date[]>([]);
  const HOUR_WIDTH_PX = 200; // width per hour in timeline

  useEffect(() => {
    // Generate timeline time slots (intervals of 30 minutes)
    const slots: Date[] = [];
    const start = new Date();
    start.setHours(start.getHours() - 2, 0, 0, 0); // start 2 hours ago
    for (let i = 0; i < 24; i++) {
      const time = new Date(start.getTime() + i * 30 * 60 * 1000);
      slots.push(time);
    }
    setTimeSlots(slots);
  }, []);

  const getMockEpg = (channelName: string) => {
    const now = new Date();
    const startHour = now.getHours() - 3;
    const list: EpgProgram[] = [];
    const programs = [
      'Noticiero RTV', 'Cine de Acción', 'Deportes del Día', 'Show de Variedades',
      'Documental Histórico', 'Telenovela Estelar', 'Comedia Nocturna', 'Debate Político',
      'Fútbol en Vivo', 'Película del Mes', 'Música en la Red', 'Entrevistas RTV'
    ];

    for (let i = 0; i < 12; i++) {
      const start = new Date(now);
      start.setHours(startHour + i, 0, 0, 0);
      const end = new Date(now);
      end.setHours(startHour + i + 1, 0, 0, 0);

      list.push({
        title: programs[(i + channelName.length) % programs.length],
        description: `Un programa espectacular transmitido por el canal ${channelName}.`,
        startTimestamp: Math.floor(start.getTime() / 1000),
        endTimestamp: Math.floor(end.getTime() / 1000)
      });
    }
    return list;
  };

  useEffect(() => {
    async function loadGuide() {
      try {
        const allChannels = await channelsApi.getAll();
        setChannels(allChannels);

        // Fetch EPG data in parallel for the first 15 channels, fallback to mock for the rest
        const dataMap: Record<string, EpgProgram[]> = {};
        const fetchPromises = allChannels.slice(0, 15).map(async (ch) => {
          try {
            const list = await channelsApi.getEpg(ch.id);
            dataMap[ch.id] = list.length > 0 ? list : getMockEpg(ch.name);
          } catch {
            dataMap[ch.id] = getMockEpg(ch.name);
          }
        });

        await Promise.all(fetchPromises);
        
        // Fill remaining channels with mock data immediately
        allChannels.slice(15).forEach((ch) => {
          dataMap[ch.id] = getMockEpg(ch.name);
        });

        setEpgData(dataMap);
      } catch (err) {
        console.error('Error loading TV Guide data:', err);
      } finally {
        setLoading(false);
      }
    }
    loadGuide();
  }, []);

  const handleScroll = (direction: 'left' | 'right') => {
    if (timelineScrollRef.current) {
      const amount = timelineScrollRef.current.clientWidth * 0.5;
      timelineScrollRef.current.scrollBy({
        left: direction === 'left' ? -amount : amount,
        behavior: 'smooth'
      });
    }
  };

  if (loading || timeSlots.length === 0) {
    return (
      <div className="flex h-[70vh] flex-col items-center justify-center gap-4">
        <Spinner size="lg" color="primary" />
        <p className="text-white/40 text-sm">Cargando guía de programación...</p>
      </div>
    );
  }

  // Calculate coordinates for red "NOW" indicator line
  const startTimeMs = timeSlots[0].getTime();
  const endTimeMs = timeSlots[timeSlots.length - 1].getTime() + 30 * 60 * 1000;
  const nowTimeMs = Date.now();
  const isNowInTimeline = nowTimeMs >= startTimeMs && nowTimeMs <= endTimeMs;
  
  // 1 hour is 200px wide, so 1 minute is (200 / 60) px
  const getPositionFromTime = (timestampSec: number) => {
    const timeMs = timestampSec * 1000;
    const diffMs = timeMs - startTimeMs;
    const diffMinutes = diffMs / 1000 / 60;
    return (diffMinutes * (HOUR_WIDTH_PX / 60));
  };

  const getWidthFromDuration = (startSec: number, endSec: number) => {
    const durationMin = (endSec - startSec) / 60;
    return (durationMin * (HOUR_WIDTH_PX / 60));
  };

  const nowLineLeft = isNowInTimeline ? getPositionFromTime(Math.floor(nowTimeMs / 1000)) : 0;

  return (
    <div className="space-y-6">
      {/* Title */}
      <div className="flex items-center justify-between select-none">
        <div>
          <h1 className="text-2xl md:text-3xl font-bold text-white flex items-center gap-2">
            <FiTv className="text-primary" />
            Guía de Programación TV (EPG)
          </h1>
          <p className="text-white/40 text-sm mt-1">Navega y reproduce canales directamente desde la cartelera horaria</p>
        </div>

        {/* Scroll Controls */}
        <div className="flex items-center gap-2">
          <button
            onClick={() => handleScroll('left')}
            className="p-2 rounded-lg bg-white/5 text-white/80 hover:text-white hover:bg-white/10 transition-all border-0 cursor-pointer"
          >
            <FiChevronLeft size={18} />
          </button>
          <button
            onClick={() => handleScroll('right')}
            className="p-2 rounded-lg bg-white/5 text-white/80 hover:text-white hover:bg-white/10 transition-all border-0 cursor-pointer"
          >
            <FiChevronRight size={18} />
          </button>
        </div>
      </div>

      {/* Guide Main Box */}
      <div className="glass-card border border-white/5 rounded-2xl overflow-hidden flex flex-col h-[650px] relative">
        
        {/* Horizontal scroll container */}
        <div 
          ref={timelineScrollRef}
          className="flex-1 overflow-x-auto overflow-y-auto scroll-smooth relative"
        >
          {/* Scrollable grid area width matches duration timeslots */}
          <div 
            className="relative"
            style={{ width: `${(timeSlots.length / 2) * HOUR_WIDTH_PX + 200}px` }} // slots are 30 min, so length/2 = hours
          >
            {/* Red "NOW" indicator line */}
            {isNowInTimeline && (
              <div 
                className="absolute top-0 bottom-0 w-0.5 bg-red-500 z-30 pointer-events-none"
                style={{ left: `${nowLineLeft + 200}px` }} // +200px offset because of left fixed channel col
              >
                <div className="absolute top-0 -left-1.5 w-3.5 h-3.5 rounded-full bg-red-500 border border-black flex items-center justify-center">
                  <div className="w-1.5 h-1.5 rounded-full bg-white animate-pulse" />
                </div>
              </div>
            )}

            {/* HEADER TIMELINE ROW */}
            <div className="sticky top-0 z-40 bg-dark-200 border-b border-white/10 flex h-12 items-center text-white/50 text-xs font-bold uppercase tracking-wider">
              {/* Corner spacer */}
              <div className="sticky left-0 w-[200px] h-full bg-dark-200 border-r border-white/10 z-50 flex items-center px-4 shrink-0 text-white font-black select-none">
                Canales
              </div>

              {/* Time headers */}
              <div className="flex select-none h-full items-center">
                {timeSlots.map((time, idx) => (
                  <div
                    key={idx}
                    className="h-full border-r border-white/5 flex items-center px-3 justify-center shrink-0"
                    style={{ width: `${HOUR_WIDTH_PX / 2}px` }} // 30-min slot is 100px
                  >
                    <FiClock size={12} className="mr-1.5 text-white/30" />
                    {time.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' })}
                  </div>
                ))}
              </div>
            </div>

            {/* CHANNEL EPG ROWS */}
            <div className="divide-y divide-white/5">
              {channels.map((ch) => {
                const programs = epgData[ch.id] || [];
                return (
                  <div key={ch.id} className="flex h-20 items-center hover:bg-white/[0.01] transition-colors relative">
                    
                    {/* Fixed Channel Sidebar Column */}
                    <div 
                      onClick={() => router.push(`/tv/${ch.id}`)}
                      className="sticky left-0 w-[200px] h-full bg-dark/95 border-r border-white/10 hover:bg-dark-100/90 z-20 flex items-center px-4 gap-3 shrink-0 cursor-pointer select-none group border-b border-white/5"
                    >
                      <div className="w-10 h-10 rounded bg-black/40 border border-white/5 overflow-hidden flex items-center justify-center shrink-0">
                        {ch.logoUrl ? (
                          <img src={ch.logoUrl} alt="" className="w-full h-full object-contain" />
                        ) : (
                          <span className="text-[10px] text-white/20 font-bold uppercase">{ch.name.slice(0, 2)}</span>
                        )}
                      </div>
                      <div className="min-w-0">
                        <p className="text-xs font-bold text-white group-hover:text-primary transition-colors truncate">
                          {ch.name}
                        </p>
                        {ch.category && (
                          <span className="text-[9px] text-white/40 block uppercase font-bold tracking-wide mt-0.5">
                            {ch.category.name}
                          </span>
                        )}
                      </div>
                    </div>

                    {/* Timeline Programs blocks */}
                    <div className="flex h-full items-center relative py-1.5">
                      {programs.map((prog, idx) => {
                        const startLeft = getPositionFromTime(prog.startTimestamp);
                        const blockWidth = getWidthFromDuration(prog.startTimestamp, prog.endTimestamp);
                        
                        const progStartMs = prog.startTimestamp * 1000;
                        const progEndMs = prog.endTimestamp * 1000;
                        const isNowPlaying = nowTimeMs >= progStartMs && nowTimeMs < progEndMs;

                        return (
                          <div
                            key={idx}
                            className={`absolute top-2 bottom-2 border border-white/5 rounded-xl px-3 py-2 flex flex-col justify-between overflow-hidden group/prog hover:border-white/20 transition-all select-none ${
                              isNowPlaying 
                                ? 'bg-primary/10 border-primary/30 shadow shadow-primary/5' 
                                : 'bg-white/5 hover:bg-white/[0.08]'
                            }`}
                            style={{ 
                              left: `${startLeft}px`,
                              width: `${Math.max(blockWidth - 4, 120)}px` // -4px margin spacing
                            }}
                          >
                            <div className="min-w-0">
                              <div className="flex items-center gap-1.5 justify-between">
                                <p className={`text-[11px] font-bold truncate ${isNowPlaying ? 'text-primary' : 'text-white'}`}>
                                  {prog.title}
                                </p>
                                {isNowPlaying && (
                                  <span className="w-1.5 h-1.5 rounded-full bg-primary animate-pulse shrink-0" />
                                )}
                              </div>
                              <p className="text-[9px] text-white/40 truncate mt-0.5">
                                {new Date(progStartMs).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' })} - {new Date(progEndMs).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' })}
                              </p>
                            </div>
                            
                            {/* Hover click to play button overlay */}
                            <button
                              onClick={() => router.push(`/tv/${ch.id}`)}
                              className="absolute inset-0 bg-black/60 opacity-0 group-hover/prog:opacity-100 transition-opacity flex items-center justify-center gap-1 text-[9px] font-bold text-white cursor-pointer z-10 rounded-xl"
                            >
                              <FiPlay size={10} className="fill-white" />
                              Ver Canal
                            </button>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </div>

          </div>
        </div>
      </div>
    </div>
  );
}
