import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import {
  Activity,
  Play,
  Pause,
  RefreshCw,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Clock,
  Wifi,
  Bell,
  BellOff,
  Loader2,
  Signal,
  TrendingUp,
  Tv2,
  X
} from 'lucide-react'
import { useStore } from '../store/useStore'
import VideoPlayer from '../components/VideoPlayer'
import type { Channel, MonitoringResult } from '@shared/types'

// Live Status Indicator
function LiveIndicator({ isLive }: { isLive: boolean }) {
  return (
    <div className={`flex items-center gap-2 px-3 py-1 rounded-full text-xs font-medium ${
      isLive ? 'bg-accent-green/20 text-accent-green' : 'bg-dark-600 text-dark-400'
    }`}>
      <span className={`w-2 h-2 rounded-full ${isLive ? 'bg-accent-green status-online' : 'bg-dark-500'}`} />
      {isLive ? 'Canlı İzleme' : 'Durduruldu'}
    </div>
  )
}

// Channel Status Card
function ChannelStatusCard({ 
  channel, 
  result,
  onManualNotify,
  onWatch
}: { 
  channel: Channel
  result?: MonitoringResult
  onManualNotify: (channel: Channel) => void
  onWatch: (channel: Channel) => void
}) {
  const statusConfig = {
    online: { icon: CheckCircle2, color: 'text-accent-green', bg: 'bg-accent-green/10 border-accent-green/20' },
    offline: { icon: XCircle, color: 'text-accent-red', bg: 'bg-accent-red/10 border-accent-red/20' },
    error: { icon: AlertTriangle, color: 'text-accent-orange', bg: 'bg-accent-orange/10 border-accent-orange/20' },
    checking: { icon: Loader2, color: 'text-accent-blue', bg: 'bg-accent-blue/10 border-accent-blue/20' },
    unknown: { icon: Signal, color: 'text-dark-400', bg: 'bg-dark-700 border-dark-600' },
  }

  const status = result?.status || channel.status
  const config = statusConfig[status]
  const Icon = config.icon

  return (
    <motion.div
      layout
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.95 }}
      className={`border rounded-xl p-4 ${config.bg} card-hover`}
    >
      <div className="flex items-start justify-between">
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg bg-dark-800/50`}>
            <Icon className={`w-5 h-5 ${config.color} ${status === 'checking' ? 'spinner' : ''}`} />
          </div>
          <div>
            <h3 className="font-medium text-dark-100">{channel.name}</h3>
            <p className="text-xs text-dark-400 mt-0.5">{channel.group || 'Genel'}</p>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex items-center gap-2">
          {/* Watch Button */}
          <button
            onClick={() => onWatch(channel)}
            className="p-2 rounded-lg bg-accent-blue/20 hover:bg-accent-blue/30 transition-colors"
            title="Canlı İzle"
          >
            <Tv2 className="w-4 h-4 text-accent-blue" />
          </button>
          
          {/* Manual Notify Button */}
          {(status === 'error' || status === 'offline') && (
            <button
              onClick={() => onManualNotify(channel)}
              className="p-2 rounded-lg bg-dark-800/50 hover:bg-dark-700 transition-colors"
              title="Manuel Bildirim Gönder"
            >
              <Bell className="w-4 h-4 text-accent-yellow" />
            </button>
          )}
        </div>
      </div>

      {/* Stats */}
      <div className="mt-4 grid grid-cols-2 gap-3">
        <div className="bg-dark-800/30 rounded-lg p-2">
          <div className="text-xs text-dark-400 flex items-center gap-1">
            <Clock className="w-3 h-3" />
            Gecikme
          </div>
          <p className="text-sm font-mono text-dark-100 mt-1">
            {result?.latency ? `${result.latency}ms` : channel.latency ? `${channel.latency}ms` : '---'}
          </p>
        </div>
        <div className="bg-dark-800/30 rounded-lg p-2">
          <div className="text-xs text-dark-400 flex items-center gap-1">
            <Wifi className="w-3 h-3" />
            HTTP
          </div>
          <p className={`text-sm font-mono mt-1 ${
            result?.httpStatus === 200 ? 'text-accent-green' : 
            result?.httpStatus ? 'text-accent-red' : 'text-dark-400'
          }`}>
            {result?.httpStatus || '---'}
          </p>
        </div>
      </div>

      {/* Error Message */}
      {result?.error && (
        <div className="mt-3 p-2 bg-dark-800/50 rounded-lg border border-dark-600">
          <p className="text-xs text-accent-red font-mono">{result.errorType}</p>
          <p className="text-xs text-dark-400 mt-1 truncate">{result.error}</p>
        </div>
      )}

      {/* Last Check Time */}
      <div className="mt-3 flex items-center justify-between text-xs text-dark-500">
        <span>Son kontrol:</span>
        <span>
          {result?.timestamp 
            ? new Date(result.timestamp).toLocaleTimeString('tr-TR')
            : channel.lastCheck 
              ? new Date(channel.lastCheck).toLocaleTimeString('tr-TR')
              : '---'
          }
        </span>
      </div>
    </motion.div>
  )
}

// Stats Overview
function StatsOverview({ 
  total, 
  online, 
  offline, 
  errors 
}: { 
  total: number
  online: number
  offline: number
  errors: number
}) {
  return (
    <div className="grid grid-cols-4 gap-4">
      <div className="bg-dark-800 border border-dark-700 rounded-xl p-4">
        <div className="flex items-center gap-2 text-dark-400 text-xs">
          <Signal className="w-4 h-4" />
          Toplam İzlenen
        </div>
        <p className="text-2xl font-bold text-dark-100 mt-2">{total}</p>
      </div>
      <div className="bg-accent-green/10 border border-accent-green/20 rounded-xl p-4">
        <div className="flex items-center gap-2 text-accent-green text-xs">
          <CheckCircle2 className="w-4 h-4" />
          Çevrimiçi
        </div>
        <p className="text-2xl font-bold text-accent-green mt-2">{online}</p>
      </div>
      <div className="bg-accent-red/10 border border-accent-red/20 rounded-xl p-4">
        <div className="flex items-center gap-2 text-accent-red text-xs">
          <XCircle className="w-4 h-4" />
          Çevrimdışı
        </div>
        <p className="text-2xl font-bold text-accent-red mt-2">{offline}</p>
      </div>
      <div className="bg-accent-orange/10 border border-accent-orange/20 rounded-xl p-4">
        <div className="flex items-center gap-2 text-accent-orange text-xs">
          <AlertTriangle className="w-4 h-4" />
          Hata
        </div>
        <p className="text-2xl font-bold text-accent-orange mt-2">{errors}</p>
      </div>
    </div>
  )
}

export default function Monitoring() {
  const { 
    channels, 
    isMonitoring, 
    setIsMonitoring,
    monitoringResults,
    updateMonitoringResult,
    settings
  } = useStore()

  const [lastRefresh, setLastRefresh] = useState<Date>(new Date())
  const [watchingChannel, setWatchingChannel] = useState<Channel | null>(null)

  const monitoredChannels = channels.filter(c => c.isMonitored)

  // Subscribe to monitoring updates
  useEffect(() => {
    if (window.electron) {
      const unsubscribe = window.electron.onMonitoringUpdate((result) => {
        updateMonitoringResult(result)
        setLastRefresh(new Date())
      })
      return () => unsubscribe()
    }
  }, [])

  const handleToggleMonitoring = async () => {
    if (window.electron) {
      if (isMonitoring) {
        await window.electron.stopMonitoring()
      } else {
        await window.electron.startMonitoring()
      }
    }
    setIsMonitoring(!isMonitoring)
  }

  const handleManualRefresh = async () => {
    // Trigger immediate check of all channels
    if (window.electron && isMonitoring) {
      // This would trigger a manual check cycle
    }
    setLastRefresh(new Date())
  }

  const handleManualNotify = async (channel: Channel) => {
    if (window.electron) {
      const result = monitoringResults.get(channel.id)
      await window.electron.sendNotification(
        `🔴 ${channel.name} - Yayın Hatası`,
        result?.error || channel.lastError || 'Yayın erişilemez durumda'
      )
    }
  }

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

  // Calculate stats
  const stats = {
    total: monitoredChannels.length,
    online: monitoredChannels.filter(c => {
      const result = monitoringResults.get(c.id)
      return (result?.status || c.status) === 'online'
    }).length,
    offline: monitoredChannels.filter(c => {
      const result = monitoringResults.get(c.id)
      return (result?.status || c.status) === 'offline'
    }).length,
    errors: monitoredChannels.filter(c => {
      const result = monitoringResults.get(c.id)
      return (result?.status || c.status) === 'error'
    }).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 flex items-center gap-3">
            <Activity className="w-7 h-7 text-accent-purple" />
            Canlı İzleme
          </h1>
          <p className="text-dark-400 text-sm mt-1">
            Son güncelleme: {lastRefresh.toLocaleTimeString('tr-TR')}
          </p>
        </div>

        <div className="flex items-center gap-3">
          <LiveIndicator isLive={isMonitoring} />
          
          <button
            onClick={handleManualRefresh}
            disabled={!isMonitoring}
            className="p-2 rounded-lg bg-dark-700 hover:bg-dark-600 disabled:opacity-50 transition-colors"
            title="Yenile"
          >
            <RefreshCw className="w-5 h-5 text-dark-300" />
          </button>

          <button
            onClick={handleToggleMonitoring}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
              isMonitoring
                ? 'bg-accent-red/20 text-accent-red hover:bg-accent-red/30'
                : 'bg-accent-green text-white hover:bg-accent-green/80'
            }`}
          >
            {isMonitoring ? (
              <>
                <Pause className="w-4 h-4" />
                Durdur
              </>
            ) : (
              <>
                <Play className="w-4 h-4" />
                Başlat
              </>
            )}
          </button>
        </div>
      </div>

      {/* Stats Overview */}
      <StatsOverview {...stats} />

      {/* Auto Notification Status */}
      <div className="flex items-center justify-between bg-dark-800 border border-dark-700 rounded-xl p-4">
        <div className="flex items-center gap-3">
          {settings?.notifications.autoNotify ? (
            <Bell className="w-5 h-5 text-accent-green" />
          ) : (
            <BellOff className="w-5 h-5 text-dark-400" />
          )}
          <div>
            <p className="font-medium text-dark-100">Otomatik Bildirimler</p>
            <p className="text-xs text-dark-400 mt-0.5">
              {settings?.notifications.autoNotify 
                ? 'Hata durumunda otomatik bildirim gönderilecek'
                : 'Otomatik bildirimler kapalı - Ayarlardan etkinleştirin'
              }
            </p>
          </div>
        </div>
        <TrendingUp className={`w-5 h-5 ${settings?.notifications.autoNotify ? 'text-accent-green' : 'text-dark-500'}`} />
      </div>

      {/* Monitored Channels Grid */}
      {monitoredChannels.length === 0 ? (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="flex flex-col items-center justify-center py-20 text-dark-400"
        >
          <Activity className="w-16 h-16 mb-4 text-dark-600" />
          <p className="text-lg">Henüz izlenen kanal yok</p>
          <p className="text-sm mt-2">Kanallar sayfasından izlemek istediğiniz kanalları seçin</p>
        </motion.div>
      ) : (
        <div className="grid grid-cols-3 gap-4">
          <AnimatePresence mode="popLayout">
            {monitoredChannels.map((channel) => (
              <ChannelStatusCard
                key={channel.id}
                channel={channel}
                result={monitoringResults.get(channel.id)}
                onManualNotify={handleManualNotify}
                onWatch={handleWatch}
              />
            ))}
          </AnimatePresence>
        </div>
      )}

      {/* 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>
  )
}

