import { useEffect, useState } from 'react'
import { motion } from 'framer-motion'
import { 
  Globe, 
  MapPin, 
  Wifi, 
  Tv2, 
  AlertTriangle, 
  CheckCircle2,
  RefreshCw,
  Activity,
  Clock,
  Bell
} from 'lucide-react'
import { useStore } from '../store/useStore'
import type { IpInfo, ErrorLogEntry } from '@shared/types'

// Status Card Component
function StatCard({ 
  icon: Icon, 
  label, 
  value, 
  subValue,
  color = 'blue',
  delay = 0 
}: { 
  icon: React.ElementType
  label: string
  value: string | number
  subValue?: string
  color?: 'blue' | 'green' | 'red' | 'yellow' | 'purple'
  delay?: number
}) {
  const colorClasses = {
    blue: 'from-accent-blue/20 to-accent-blue/5 border-accent-blue/30 text-accent-blue',
    green: 'from-accent-green/20 to-accent-green/5 border-accent-green/30 text-accent-green',
    red: 'from-accent-red/20 to-accent-red/5 border-accent-red/30 text-accent-red',
    yellow: 'from-accent-yellow/20 to-accent-yellow/5 border-accent-yellow/30 text-accent-yellow',
    purple: 'from-accent-purple/20 to-accent-purple/5 border-accent-purple/30 text-accent-purple',
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, duration: 0.3 }}
      className={`bg-gradient-to-br ${colorClasses[color]} border rounded-xl p-5 card-hover`}
    >
      <div className="flex items-start justify-between">
        <div>
          <p className="text-dark-400 text-xs uppercase tracking-wider mb-1">{label}</p>
          <p className="text-2xl font-bold text-dark-100">{value}</p>
          {subValue && <p className="text-xs text-dark-400 mt-1">{subValue}</p>}
        </div>
        <div className={`p-2 rounded-lg bg-dark-800/50`}>
          <Icon className="w-5 h-5" />
        </div>
      </div>
    </motion.div>
  )
}

// IP Info Card Component
function IpInfoCard({ ipInfo, loading, onRefresh }: { 
  ipInfo: IpInfo | null
  loading: boolean
  onRefresh: () => void
}) {
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      className="bg-dark-800 border border-dark-700 rounded-xl p-6 col-span-2"
    >
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-dark-100 flex items-center gap-2">
          <Globe className="w-5 h-5 text-accent-blue" />
          IP Bilgileri
        </h2>
        <button
          onClick={onRefresh}
          disabled={loading}
          className="p-2 rounded-lg bg-dark-700 hover:bg-dark-600 transition-colors disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 text-dark-300 ${loading ? 'spinner' : ''}`} />
        </button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-8">
          <div className="w-8 h-8 border-2 border-accent-blue border-t-transparent rounded-full spinner" />
        </div>
      ) : ipInfo ? (
        <div className="grid grid-cols-2 gap-4">
          <div className="bg-dark-700/50 rounded-lg p-4">
            <div className="flex items-center gap-2 text-dark-400 text-xs mb-2">
              <Wifi className="w-4 h-4" />
              IP Adresi
            </div>
            <p className="text-xl font-mono font-bold text-accent-cyan">{ipInfo.ip}</p>
          </div>
          <div className="bg-dark-700/50 rounded-lg p-4">
            <div className="flex items-center gap-2 text-dark-400 text-xs mb-2">
              <MapPin className="w-4 h-4" />
              Konum
            </div>
            <p className="text-xl font-semibold text-dark-100">
              {ipInfo.country}
              <span className="ml-2 text-sm bg-dark-600 px-2 py-0.5 rounded">
                {ipInfo.countryCode}
              </span>
            </p>
          </div>
          {ipInfo.city && (
            <div className="bg-dark-700/50 rounded-lg p-4">
              <div className="text-dark-400 text-xs mb-2">Şehir</div>
              <p className="text-lg font-semibold text-dark-100">{ipInfo.city}</p>
            </div>
          )}
          {ipInfo.isp && (
            <div className="bg-dark-700/50 rounded-lg p-4">
              <div className="text-dark-400 text-xs mb-2">ISP</div>
              <p className="text-lg font-semibold text-dark-100 truncate">{ipInfo.isp}</p>
            </div>
          )}
        </div>
      ) : (
        <div className="text-center py-8 text-dark-400">
          IP bilgisi alınamadı
        </div>
      )}
    </motion.div>
  )
}

// Recent Errors Component
function RecentErrors({ errors }: { errors: ErrorLogEntry[] }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: 0.3 }}
      className="bg-dark-800 border border-dark-700 rounded-xl p-6"
    >
      <h2 className="text-lg font-semibold text-dark-100 flex items-center gap-2 mb-4">
        <AlertTriangle className="w-5 h-5 text-accent-red" />
        Son Hatalar
      </h2>

      {errors.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-8 text-dark-400">
          <CheckCircle2 className="w-12 h-12 mb-3 text-accent-green" />
          <p>Hata bulunamadı</p>
          <p className="text-xs mt-1">Tüm sistemler normal çalışıyor</p>
        </div>
      ) : (
        <div className="space-y-2 max-h-64 overflow-auto">
          {errors.slice(0, 5).map((error, index) => (
            <motion.div
              key={error.id}
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: index * 0.05 }}
              className="bg-dark-700/50 border border-dark-600 rounded-lg p-3"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1 min-w-0">
                  <p className="font-medium text-dark-100 truncate">{error.channelName}</p>
                  <p className="text-xs text-accent-red mt-1">{error.errorType}</p>
                  <p className="text-xs text-dark-400 truncate mt-1">{error.errorMessage}</p>
                </div>
                <div className="flex items-center gap-2 ml-3">
                  {error.notified && (
                    <Bell className="w-3 h-3 text-accent-green" />
                  )}
                  <span className="text-xs text-dark-500">
                    {new Date(error.timestamp).toLocaleTimeString('tr-TR')}
                  </span>
                </div>
              </div>
            </motion.div>
          ))}
        </div>
      )}
    </motion.div>
  )
}

export default function Dashboard() {
  const { 
    ipInfo, 
    ipLoading, 
    setIpInfo, 
    setIpLoading,
    channels,
    errorLog,
    isMonitoring
  } = useStore()

  const [lastUpdate, setLastUpdate] = useState<Date>(new Date())

  const fetchIpInfo = async () => {
    setIpLoading(true)
    try {
      if (window.electron) {
        const info = await window.electron.getIpInfo()
        setIpInfo(info)
      } else {
        // Demo data for development
        setIpInfo({
          ip: '185.123.45.67',
          country: 'Turkey',
          countryCode: 'TR',
          city: 'Istanbul',
          isp: 'Turk Telekom'
        })
      }
      setLastUpdate(new Date())
    } catch (error) {
      console.error('Failed to fetch IP info:', error)
    } finally {
      setIpLoading(false)
    }
  }

  useEffect(() => {
    fetchIpInfo()
  }, [])

  const monitoredChannels = channels.filter(c => c.isMonitored)
  const onlineChannels = channels.filter(c => c.status === 'online')
  const errorChannels = channels.filter(c => c.status === 'error' || c.status === 'offline')

  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">Dashboard</h1>
          <p className="text-dark-400 text-sm mt-1">
            Sistem durumu ve özet bilgiler
          </p>
        </div>
        <div className="flex items-center gap-2 text-xs text-dark-400">
          <Clock className="w-4 h-4" />
          Son güncelleme: {lastUpdate.toLocaleTimeString('tr-TR')}
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-4 gap-4">
        <StatCard
          icon={Tv2}
          label="Toplam Kanal"
          value={channels.length}
          subValue={`${monitoredChannels.length} izleniyor`}
          color="blue"
          delay={0}
        />
        <StatCard
          icon={CheckCircle2}
          label="Çevrimiçi"
          value={onlineChannels.length}
          subValue="Aktif yayınlar"
          color="green"
          delay={0.1}
        />
        <StatCard
          icon={AlertTriangle}
          label="Hatalı"
          value={errorChannels.length}
          subValue={`${errorLog.length} log kaydı`}
          color="red"
          delay={0.2}
        />
        <StatCard
          icon={Activity}
          label="İzleme Durumu"
          value={isMonitoring ? 'Aktif' : 'Pasif'}
          subValue={isMonitoring ? 'Otomatik kontrol' : 'Beklemede'}
          color={isMonitoring ? 'green' : 'yellow'}
          delay={0.3}
        />
      </div>

      {/* Main Content Grid */}
      <div className="grid grid-cols-3 gap-6">
        <IpInfoCard ipInfo={ipInfo} loading={ipLoading} onRefresh={fetchIpInfo} />
        <RecentErrors errors={errorLog} />
      </div>
    </div>
  )
}

