import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import {
  Tv2,
  Plus,
  Search,
  Filter,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Loader2,
  Trash2,
  Eye,
  EyeOff,
  Link2,
  FolderOpen,
  Play
} from 'lucide-react'
import { useStore } from '../store/useStore'
import VideoPlayer from '../components/VideoPlayer'
import type { Channel, ChannelStatus } from '@shared/types'

// Status Badge Component
function StatusBadge({ status }: { status: ChannelStatus }) {
  const config = {
    online: { icon: CheckCircle2, text: 'Çevrimiçi', color: 'text-accent-green bg-accent-green/10' },
    offline: { icon: XCircle, text: 'Çevrimdışı', color: 'text-accent-red bg-accent-red/10' },
    error: { icon: AlertCircle, text: 'Hata', color: 'text-accent-orange bg-accent-orange/10' },
    checking: { icon: Loader2, text: 'Kontrol', color: 'text-accent-blue bg-accent-blue/10' },
    unknown: { icon: AlertCircle, text: 'Bilinmiyor', color: 'text-dark-400 bg-dark-600' },
  }

  const { icon: Icon, text, color } = config[status]

  return (
    <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium ${color}`}>
      <Icon className={`w-3 h-3 ${status === 'checking' ? 'spinner' : ''}`} />
      {text}
    </span>
  )
}

// Channel Row Component
function ChannelRow({ 
  channel, 
  onToggleMonitor,
  onWatch
}: { 
  channel: Channel
  onToggleMonitor: (id: string, monitored: boolean) => void
  onWatch: (channel: Channel) => void
}) {
  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: -10 }}
      className="bg-dark-700/50 border border-dark-600 rounded-lg p-4 hover:bg-dark-700 transition-colors"
    >
      <div className="flex items-center gap-4">
        {/* Logo/Icon */}
        <div className="w-10 h-10 rounded-lg bg-dark-600 flex items-center justify-center overflow-hidden shrink-0">
          {channel.logo ? (
            <img src={channel.logo} alt="" className="w-full h-full object-cover" />
          ) : (
            <Tv2 className="w-5 h-5 text-dark-400" />
          )}
        </div>

        {/* Info */}
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <h3 className="font-medium text-dark-100 truncate">{channel.name}</h3>
            {channel.group && (
              <span className="text-xs bg-dark-600 text-dark-300 px-2 py-0.5 rounded">
                {channel.group}
              </span>
            )}
          </div>
          <p className="text-xs text-dark-400 truncate mt-1 font-mono">{channel.url}</p>
        </div>

        {/* Status */}
        <StatusBadge status={channel.status} />

        {/* Latency */}
        {channel.latency && (
          <span className="text-xs text-dark-400 font-mono w-16 text-right">
            {channel.latency}ms
          </span>
        )}

        {/* Actions */}
        <div className="flex items-center gap-2">
          {/* Watch Button */}
          <button
            onClick={() => onWatch(channel)}
            className="p-2 rounded-lg bg-accent-green/20 text-accent-green hover:bg-accent-green/30 transition-colors"
            title="Canlı İzle"
          >
            <Play className="w-4 h-4" />
          </button>
          
          {/* Monitor Toggle */}
          <button
            onClick={() => onToggleMonitor(channel.id, !channel.isMonitored)}
            className={`p-2 rounded-lg transition-colors ${
              channel.isMonitored
                ? 'bg-accent-blue/20 text-accent-blue hover:bg-accent-blue/30'
                : 'bg-dark-600 text-dark-400 hover:bg-dark-500'
            }`}
            title={channel.isMonitored ? 'İzlemeyi durdur' : 'İzlemeye başla'}
          >
            {channel.isMonitored ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
          </button>
        </div>
      </div>

      {/* Error Message */}
      {channel.lastError && (
        <div className="mt-3 p-2 bg-accent-red/10 border border-accent-red/20 rounded-md">
          <p className="text-xs text-accent-red">{channel.lastError}</p>
        </div>
      )}
    </motion.div>
  )
}

// Add Playlist/URL Modal
function AddPlaylistModal({ 
  isOpen, 
  onClose, 
  onAdd,
  onAddSingle
}: { 
  isOpen: boolean
  onClose: () => void
  onAdd: (url: string) => void
  onAddSingle: (name: string, url: string) => void
}) {
  const [url, setUrl] = useState('')
  const [channelName, setChannelName] = useState('')
  const [loading, setLoading] = useState(false)
  const [mode, setMode] = useState<'playlist' | 'single'>('playlist')

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!url.trim()) return
    
    setLoading(true)
    if (mode === 'playlist') {
      await onAdd(url.trim())
    } else {
      await onAddSingle(channelName.trim() || 'Yeni Kanal', url.trim())
    }
    setLoading(false)
    setUrl('')
    setChannelName('')
    onClose()
  }

  if (!isOpen) return null

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.95, opacity: 0 }}
        className="bg-dark-800 border border-dark-600 rounded-xl p-6 w-full max-w-lg"
        onClick={(e) => e.stopPropagation()}
      >
        <h2 className="text-lg font-semibold text-dark-100 mb-4 flex items-center gap-2">
          <Link2 className="w-5 h-5 text-accent-blue" />
          Kanal/Playlist Ekle
        </h2>

        {/* Mode Tabs */}
        <div className="flex gap-2 mb-4">
          <button
            type="button"
            onClick={() => setMode('playlist')}
            className={`flex-1 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
              mode === 'playlist'
                ? 'bg-accent-blue text-white'
                : 'bg-dark-700 text-dark-300 hover:bg-dark-600'
            }`}
          >
            M3U8 Playlist
          </button>
          <button
            type="button"
            onClick={() => setMode('single')}
            className={`flex-1 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
              mode === 'single'
                ? 'bg-accent-blue text-white'
                : 'bg-dark-700 text-dark-300 hover:bg-dark-600'
            }`}
          >
            Tek URL
          </button>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          {mode === 'single' && (
            <div>
              <label className="block text-sm text-dark-300 mb-2">Kanal Adı</label>
              <input
                type="text"
                value={channelName}
                onChange={(e) => setChannelName(e.target.value)}
                placeholder="Örn: TRT 1 HD"
                className="w-full px-4 py-3 bg-dark-700 border border-dark-600 rounded-lg text-dark-100 placeholder-dark-500 focus:outline-none focus:border-accent-blue"
              />
            </div>
          )}
          
          <div>
            <label className="block text-sm text-dark-300 mb-2">
              {mode === 'playlist' ? 'Playlist URL' : 'Stream URL'}
            </label>
            <input
              type="url"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              placeholder={mode === 'playlist' 
                ? "https://example.com/playlist.m3u8" 
                : "http://example.com:8080/live/stream.ts"
              }
              className="w-full px-4 py-3 bg-dark-700 border border-dark-600 rounded-lg text-dark-100 placeholder-dark-500 focus:outline-none focus:border-accent-blue"
              autoFocus
            />
          </div>

          <div className="flex justify-end gap-3">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-dark-300 hover:text-dark-100 transition-colors"
            >
              İptal
            </button>
            <button
              type="submit"
              disabled={!url.trim() || loading}
              className="px-4 py-2 bg-accent-blue text-white rounded-lg hover:bg-accent-blue/80 transition-colors disabled:opacity-50 flex items-center gap-2"
            >
              {loading && <Loader2 className="w-4 h-4 spinner" />}
              {mode === 'playlist' ? 'Playlist Yükle' : 'Kanal Ekle'}
            </button>
          </div>
        </form>
      </motion.div>
    </motion.div>
  )
}

export default function Channels() {
  const { channels, setChannels, channelsLoading, setChannelsLoading } = useStore()
  const [searchQuery, setSearchQuery] = useState('')
  const [filterStatus, setFilterStatus] = useState<ChannelStatus | 'all'>('all')
  const [showMonitoredOnly, setShowMonitoredOnly] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [watchingChannel, setWatchingChannel] = useState<Channel | null>(null)

  // Load channels on mount
  useEffect(() => {
    const loadChannels = async () => {
      if (window.electron) {
        setChannelsLoading(true)
        try {
          const loadedChannels = await window.electron.getChannels()
          setChannels(loadedChannels)
        } catch (error) {
          console.error('Failed to load channels:', error)
        } finally {
          setChannelsLoading(false)
        }
      }
    }
    loadChannels()
  }, [])

  const handleAddPlaylist = async (url: string) => {
    if (window.electron) {
      setChannelsLoading(true)
      try {
        const newChannels = await window.electron.parseM3u8(url)
        setChannels([...channels, ...newChannels])
      } catch (error) {
        console.error('Failed to parse playlist:', error)
      } finally {
        setChannelsLoading(false)
      }
    } else {
      // Demo data
      const demoChannels: Channel[] = [
        { id: '1', name: 'TRT 1 HD', url: 'https://tv-trt1.medya.trt.com.tr/master.m3u8', group: 'Ulusal', isMonitored: true, status: 'online', latency: 45 },
        { id: '2', name: 'Show TV', url: 'https://ciner-live.daioncdn.net/showtv/showtv.m3u8', group: 'Ulusal', isMonitored: true, status: 'online', latency: 67 },
        { id: '3', name: 'ATV', url: 'https://trkvz-live.ercdn.net/atvhd/atvhd.m3u8', group: 'Ulusal', isMonitored: false, status: 'unknown' },
        { id: '4', name: 'TV8', url: 'https://tv8-live.ercdn.net/tv8/tv8.m3u8', group: 'Ulusal', isMonitored: true, status: 'error', lastError: 'ERR_CONNECTION_RESET' },
        { id: '5', name: 'CNN Türk', url: 'https://cnn.com/live.m3u8', group: 'Haber', isMonitored: true, status: 'offline' },
      ]
      setChannels([...channels, ...demoChannels])
    }
  }

  const handleAddSingleChannel = async (name: string, url: string) => {
    const newChannel: Channel = {
      id: Date.now().toString(),
      name,
      url,
      group: 'Manuel',
      isMonitored: true,
      status: 'unknown'
    }
    setChannels([...channels, newChannel])
  }

  const handleToggleMonitor = async (channelId: string, monitored: boolean) => {
    if (window.electron) {
      await window.electron.setChannelMonitored(channelId, monitored)
    }
    setChannels(
      channels.map((c) =>
        c.id === channelId ? { ...c, isMonitored: monitored } : c
      )
    )
  }

  const handleWatch = (channel: Channel) => {
    setWatchingChannel(channel)
  }

  // Filter channels
  const filteredChannels = channels.filter((channel) => {
    const matchesSearch = channel.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          channel.url.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesStatus = filterStatus === 'all' || channel.status === filterStatus
    const matchesMonitored = !showMonitoredOnly || channel.isMonitored
    return matchesSearch && matchesStatus && matchesMonitored
  })

  // Group channels by group
  const groupedChannels = filteredChannels.reduce((acc, channel) => {
    const group = channel.group || 'Diğer'
    if (!acc[group]) acc[group] = []
    acc[group].push(channel)
    return acc
  }, {} as Record<string, Channel[]>)

  const monitoredCount = channels.filter(c => c.isMonitored).length

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-display font-bold text-dark-100">Kanal Yönetimi</h1>
          <p className="text-dark-400 text-sm mt-1">
            {channels.length} kanal · {monitoredCount} izleniyor
          </p>
        </div>
        <button
          onClick={() => setIsModalOpen(true)}
          className="flex items-center gap-2 px-4 py-2 bg-accent-blue text-white rounded-lg hover:bg-accent-blue/80 transition-colors"
        >
          <Plus className="w-4 h-4" />
          Playlist Ekle
        </button>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-4">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-dark-400" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Kanal ara..."
            className="w-full pl-10 pr-4 py-2 bg-dark-700 border border-dark-600 rounded-lg text-dark-100 placeholder-dark-500 focus:outline-none focus:border-accent-blue"
          />
        </div>

        <select
          value={filterStatus}
          onChange={(e) => setFilterStatus(e.target.value as ChannelStatus | 'all')}
          className="px-4 py-2 bg-dark-700 border border-dark-600 rounded-lg text-dark-100 focus:outline-none focus:border-accent-blue"
        >
          <option value="all">Tüm Durumlar</option>
          <option value="online">Çevrimiçi</option>
          <option value="offline">Çevrimdışı</option>
          <option value="error">Hatalı</option>
          <option value="unknown">Bilinmiyor</option>
        </select>

        <button
          onClick={() => setShowMonitoredOnly(!showMonitoredOnly)}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg border transition-colors ${
            showMonitoredOnly
              ? 'bg-accent-blue/20 border-accent-blue/30 text-accent-blue'
              : 'bg-dark-700 border-dark-600 text-dark-300 hover:text-dark-100'
          }`}
        >
          <Eye className="w-4 h-4" />
          Sadece İzlenen
        </button>
      </div>

      {/* Channel List */}
      {channelsLoading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-8 h-8 text-accent-blue spinner" />
        </div>
      ) : filteredChannels.length === 0 ? (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="flex flex-col items-center justify-center py-20 text-dark-400"
        >
          <FolderOpen className="w-16 h-16 mb-4 text-dark-600" />
          <p className="text-lg">Henüz kanal eklenmemiş</p>
          <p className="text-sm mt-2">M3U8 playlist URL'i ekleyerek başlayın</p>
        </motion.div>
      ) : (
        <div className="space-y-6">
          {Object.entries(groupedChannels).map(([group, groupChannels]) => (
            <div key={group}>
              <h3 className="text-sm font-medium text-dark-400 mb-3 flex items-center gap-2">
                <span className="w-2 h-2 rounded-full bg-accent-purple" />
                {group}
                <span className="text-dark-500">({groupChannels.length})</span>
              </h3>
              <div className="space-y-2">
                <AnimatePresence mode="popLayout">
                  {groupChannels.map((channel) => (
                    <ChannelRow
                      key={channel.id}
                      channel={channel}
                      onToggleMonitor={handleToggleMonitor}
                      onWatch={handleWatch}
                    />
                  ))}
                </AnimatePresence>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Add Playlist Modal */}
      <AnimatePresence>
        {isModalOpen && (
          <AddPlaylistModal
            isOpen={isModalOpen}
            onClose={() => setIsModalOpen(false)}
            onAdd={handleAddPlaylist}
            onAddSingle={handleAddSingleChannel}
          />
        )}
      </AnimatePresence>

      {/* Video Player Modal */}
      <AnimatePresence>
        {watchingChannel && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50 p-8"
            onClick={() => setWatchingChannel(null)}
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="w-full max-w-5xl"
              onClick={(e) => e.stopPropagation()}
            >
              <VideoPlayer
                url={watchingChannel.url}
                title={watchingChannel.name}
                onClose={() => setWatchingChannel(null)}
                autoPlay={true}
              />
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}

