import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { channelService } from '../services/channelService'
import { Channel, ChannelCategory } from '../types/channel'

interface ChannelContextType {
  channels: Channel[]
  categories: ChannelCategory[]
  currentChannel: Channel | null
  isLoading: boolean
  error: string | null
  favorites: string[]
  searchTerm: string
  selectedCategory: string
  viewerCount: number
  setCurrentChannel: (channel: Channel | null) => void
  setSearchTerm: (term: string) => void
  setSelectedCategory: (category: string) => void
  toggleFavorite: (channelId: string) => void
  refreshChannels: () => Promise<void>
}

const ChannelContext = createContext<ChannelContextType | undefined>(undefined)

export function ChannelProvider({ children }: { children: ReactNode }) {
  const [channels, setChannels] = useState<Channel[]>([])
  const [categories, setCategories] = useState<ChannelCategory[]>([])
  const [currentChannel, setCurrentChannel] = useState<Channel | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [favorites, setFavorites] = useState<string[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedCategory, setSelectedCategory] = useState('all')
  const [viewerCount, setViewerCount] = useState(0)

  useEffect(() => {
    const savedFavorites = localStorage.getItem('daddytv_favorites')
    if (savedFavorites) {
      setFavorites(JSON.parse(savedFavorites))
    }
  }, [])

  useEffect(() => {
    localStorage.setItem('daddytv_favorites', JSON.stringify(favorites))
  }, [favorites])

  const refreshChannels = async () => {
    setIsLoading(true)
    setError(null)
    try {
      const data = await channelService.getChannels()
      setChannels(data.channels)
      setCategories(data.categories)
    } catch (err) {
      setError('Error al cargar los canales. Inténtalo de nuevo.')
      console.error('Error loading channels:', err)
    } finally {
      setIsLoading(false)
    }
  }

  const toggleFavorite = (channelId: string) => {
    setFavorites(prev => 
      prev.includes(channelId) 
        ? prev.filter(id => id !== channelId)
        : [...prev, channelId]
    )
  }

  const handleSetCurrentChannel = async (channel: Channel | null) => {
    if (channel) {
      try {
        const result = await channelService.setViewing(channel.url)
        if (result.switched) {
          // Mostrar mensaje de cambio automático
          console.log('Canal cambiado automáticamente')
        }
        setViewerCount(result.viewers || 1)
      } catch (err) {
        console.error('Error setting current channel:', err)
      }
    }
    setCurrentChannel(channel)
  }

  return (
    <ChannelContext.Provider value={{
      channels,
      categories,
      currentChannel,
      isLoading,
      error,
      favorites,
      searchTerm,
      selectedCategory,
      viewerCount,
      setCurrentChannel: handleSetCurrentChannel,
      setSearchTerm,
      setSelectedCategory,
      toggleFavorite,
      refreshChannels
    }}>
      {children}
    </ChannelContext.Provider>
  )
}

export function useChannels() {
  const context = useContext(ChannelContext)
  if (context === undefined) {
    throw new Error('useChannels must be used within a ChannelProvider')
  }
  return context
}