import { useEffect, useState } from 'react'
import { Clock, Activity, AlertCircle, CheckCircle, Disc } from 'lucide-react'
import { api } from '../lib/api'
import { useDarkMode } from '../context/ThemeContext'
import DeviceDiscovery from '../components/DeviceDiscovery'
import LiveLogSection from '../components/LiveLogSection'

interface Job {
  id: string
  type: 'cd' | 'dvd' | 'bluray'
  status: 'pending' | 'processing' | 'transcoding' | 'canceling' | 'completed' | 'failed'
  device: string
  startTime: string
  endTime?: string
  progress: number
  title?: string
}

async function fetchJobs(): Promise<Job[]> {
  try {
    const response = await api.get('/jobs')
    return response.data
  } catch {
    return []
  }
}

function StatusBadge({ status }: { status: string }) {
  const { theme } = useDarkMode()
  const styles = theme === 'dark'
    ? {
        pending: 'bg-amber-900/30 text-amber-400 ring-amber-700/20',
        processing: 'bg-blue-900/30 text-blue-400 ring-blue-700/20',
        transcoding: 'bg-purple-900/30 text-purple-400 ring-purple-700/20',
        canceling: 'bg-orange-900/30 text-orange-400 ring-orange-700/20',
        completed: 'bg-emerald-900/30 text-emerald-400 ring-emerald-700/20',
        failed: 'bg-rose-900/30 text-rose-400 ring-rose-700/20',
      }
    : {
        pending: 'bg-amber-100 text-amber-700 ring-amber-600/20',
        processing: 'bg-blue-100 text-blue-700 ring-blue-600/20',
        transcoding: 'bg-purple-100 text-purple-700 ring-purple-600/20',
        canceling: 'bg-orange-100 text-orange-700 ring-orange-600/20',
        completed: 'bg-emerald-100 text-emerald-700 ring-emerald-600/20',
        failed: 'bg-rose-100 text-rose-700 ring-rose-600/20',
      }

  const labels = {
    pending: 'Wartend',
    processing: 'Rippen',
    transcoding: 'Komprimieren',
    canceling: 'Wird abgebrochen…',
    completed: 'Fertig',
    failed: 'Fehler',
  }
  
  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ring-1 ring-inset ${styles[status as keyof typeof styles] || 'bg-gray-100 text-gray-700 ring-gray-600/10'}`}>
      {labels[status as keyof typeof labels] || status}
    </span>
  )
}

function TypeBadge({ type }: { type: string }) {
  const { theme } = useDarkMode()
  const colors = theme === 'dark'
    ? 'bg-slate-800 text-slate-300'
    : 'bg-slate-100 text-slate-700'
  
  const icons = {
    cd: Disc,
    dvd: Disc,
    bluray: Disc,
  }
  const Icon = icons[type as keyof typeof icons] || Disc
  return (
    <span className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-medium ${colors}`}>
      <Icon size={14} />
      {type.toUpperCase()}
    </span>
  )
}

function ProgressBar({ progress }: { progress: number }) {
  const { theme } = useDarkMode()
  const bgColors = theme === 'dark'
    ? {
        empty: 'bg-slate-700',
        indicator: 'bg-gradient-to-r from-indigo-500 to-purple-600',
        done: 'bg-emerald-500',
      }
    : {
        empty: 'bg-slate-200',
        indicator: 'bg-gradient-to-r from-indigo-500 to-purple-600',
        done: 'bg-emerald-500',
      }
  
  const textColors = theme === 'dark'
    ? {
        label: 'text-slate-400',
        value: 'text-slate-200',
      }
    : {
        label: 'text-slate-500',
        value: 'text-slate-900',
      }
  
  return (
    <div className="w-32">
      <div className="flex items-center justify-between mb-1">
        <span className={`text-xs font-medium ${textColors.label}`}>Fortschritt</span>
        <span className={`text-xs font-medium ${textColors.value}`}>{progress}%</span>
      </div>
      <div className={`w-full ${bgColors.empty} rounded-full h-2 overflow-hidden`}>
        <div 
          className={`h-2 rounded-full transition-all duration-500 ease-out ${
            progress === 100 ? bgColors.done : bgColors.indicator
          }`}
          style={{ width: `${progress}%` }}
        />
      </div>
    </div>
  )
}

interface WorkerInfo {
  name: string
  encoders: string[]
}

const ENCODER_KURZ: Record<string, string> = {
  'cpu-x264': 'H.264 (CPU)',
  'cpu-x265': 'H.265 (CPU)',
  'vaapi': 'VAAPI ⚡',
  'nvenc': 'NVENC ⚡',
}

export default function Dashboard() {
  const [jobs, setJobs] = useState<Job[]>([])
  const [workers, setWorkers] = useState<WorkerInfo[]>([])
  const [loading, setLoading] = useState(true)
  const { theme } = useDarkMode()

  useEffect(() => {
    const loadData = async () => {
      try {
        setJobs(await fetchJobs())
      } finally {
        setLoading(false)
      }
    }

    loadData()
    api.get('/capabilities').then(r => setWorkers(r.data.workers || [])).catch(() => {})
    const interval = setInterval(loadData, 5000)
    return () => clearInterval(interval)
  }, [])

  const aktiverJob = jobs.find(j => j.status === 'processing' || j.status === 'transcoding')

  const stats = {
    pending: jobs.filter(j => j.status === 'pending').length,
    processing: jobs.filter(j => j.status === 'processing').length,
    completed: jobs.filter(j => j.status === 'completed').length,
    failed: jobs.filter(j => j.status === 'failed').length,
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    )
  }

  return (
    <div className="space-y-8 transition-colors duration-300">
      {/* Header */}
      <div className="flex flex-col gap-2 transition-colors duration-300">
        <h1 className="text-3xl font-bold dark:text-slate-100 text-slate-900">Dashboard</h1>
        <p className={`text-sm ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Übersicht über alle Ripping-Jobs und Geräte</p>
      </div>

      {/* System-Leiste: Encoder + aktiver Job auf einen Blick */}
      <div className={`flex flex-wrap items-center gap-x-6 gap-y-2 rounded-xl border px-5 py-3 text-sm ${theme === 'dark' ? 'bg-slate-800 border-slate-700' : 'bg-white border-slate-200'}`}>
        <div className="flex items-center gap-2">
          <Activity size={16} className="text-indigo-500" />
          <span className={theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}>Encoder:</span>
          {workers.length === 0 ? (
            <span className={theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}>kein Worker</span>
          ) : (
            workers.flatMap(w => w.encoders).filter((e, i, a) => a.indexOf(e) === i).map(e => (
              <span key={e} className={`text-xs px-2 py-0.5 rounded ${e.startsWith('cpu') ? (theme === 'dark' ? 'bg-slate-700 text-slate-300' : 'bg-slate-100 text-slate-600') : 'bg-emerald-600/20 text-emerald-500 font-medium'}`}>
                {ENCODER_KURZ[e] || e}
              </span>
            ))
          )}
        </div>
        <div className="flex items-center gap-2">
          <Clock size={16} className="text-indigo-500" />
          <span className={theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}>Aktiv:</span>
          {aktiverJob ? (
            <span className={theme === 'dark' ? 'text-slate-200' : 'text-slate-700'}>
              {aktiverJob.status === 'transcoding' ? 'Komprimieren' : 'Rippen'} · {aktiverJob.progress} %
            </span>
          ) : (
            <span className={theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}>kein Job</span>
          )}
        </div>
      </div>

      {/* Laufwerke + erkannte Disc */}
      <DeviceDiscovery />

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 transition-colors duration-300">
        <StatCard 
          icon={Clock} 
          label="Warteschlange" 
          value={stats.pending.toString()} 
          color="amber" 
          darkMode={theme === 'dark'}
        />
        <StatCard 
          icon={Activity} 
          label="Bearbeitung" 
          value={stats.processing.toString()} 
          color="blue" 
          darkMode={theme === 'dark'}
        />
        <StatCard 
          icon={CheckCircle} 
          label="Fertig" 
          value={stats.completed.toString()} 
          color="emerald" 
          darkMode={theme === 'dark'}
        />
        <StatCard 
          icon={AlertCircle} 
          label="Fehler" 
          value={stats.failed.toString()} 
          color="rose" 
          darkMode={theme === 'dark'}
        />
      </div>

      {/* Recent Jobs */}
      {/* Schnellaktionen + doppelte Geräte-Sektion sind raus (23.07.): alle
          vier Knöpfe und der zweite Details-Button waren funktionslos —
          die echte Geräte-Steuerung lebt in DeviceDiscovery oben. */}
      <div className={`rounded-xl shadow-sm border overflow-hidden transition-colors duration-300 ${theme === 'dark' ? 'bg-slate-800 border-slate-700' : 'bg-white border-slate-200'}`}>
        <div className={`px-6 py-4 border-b transition-colors duration-300 ${theme === 'dark' ? 'border-slate-700' : 'border-slate-200'} flex items-center justify-between`}>
          <h2 className={`text-lg font-semibold ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>Neueste Jobs</h2>
          <span className={`text-sm ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>{jobs.length} Jobs insgesamt</span>
        </div>
        <div className="overflow-x-auto transition-colors duration-300">
          <table className="w-full transition-colors duration-300">
            <thead className={theme === 'dark' ? 'bg-slate-900' : 'bg-slate-50'}>
              <tr>
                <th className={`px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Typ</th>
                <th className={`px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Titel</th>
                <th className={`px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Status</th>
                <th className={`px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Gerät</th>
                <th className={`px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Fortschritt</th>
                <th className={`px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Startzeit</th>
                <th className={`px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Aktion</th>
              </tr>
            </thead>
            <tbody className={`divide-y ${theme === 'dark' ? 'divide-slate-700' : 'divide-slate-200'}`}>
              {jobs.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-6 py-12 text-center transition-colors duration-300">
                    <div className={`mb-2 ${theme === 'dark' ? 'text-slate-400' : 'text-slate-400'}`}>Noch keine Jobs</div>
                    <p className={`text-sm ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Füge eine CD, DVD oder Blu-ray hinzu, um zu starten</p>
                  </td>
                </tr>
              ) : (
                jobs.slice(0, 10).map(job => (
                  <tr key={job.id} className={`transition-colors duration-300 ${theme === 'dark' ? 'hover:bg-slate-700/40' : 'hover:bg-slate-50'}`}>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <TypeBadge type={job.type} />
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className={`text-sm font-medium ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>
                        {job.title || 'Unbekannt'}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <StatusBadge status={job.status} />
                    </td>
                    <td className={`px-6 py-4 whitespace-nowrap text-sm ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>
                      {job.device}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <ProgressBar progress={job.progress} />
                    </td>
                    <td className={`px-6 py-4 whitespace-nowrap text-sm ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>
                      {new Date(job.startTime).toLocaleString('de-DE')}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {job.status === 'failed' && (
                        <button
                          onClick={() => api.post(`/jobs/${job.id}/retry-transcode`).catch(() => {})}
                          title="Kompression neu anstoßen (Rohdatei bleibt nach Fehlschlägen erhalten)"
                          className={`text-xs font-medium px-3 py-1.5 rounded-lg transition-colors ${theme === 'dark' ? 'bg-slate-700 text-indigo-300 hover:bg-slate-600' : 'bg-slate-100 text-indigo-700 hover:bg-slate-200'}`}
                        >
                          Neu komprimieren
                        </button>
                      )}
                      {(job.status === 'pending' || job.status === 'processing' || job.status === 'transcoding') && (
                        <button
                          onClick={() => api.post(`/jobs/${job.id}/cancel`).catch(() => {})}
                          title="Job abbrechen (Rohdaten bleiben erhalten)"
                          className={`text-xs font-medium px-3 py-1.5 rounded-lg transition-colors ${theme === 'dark' ? 'bg-slate-700 text-rose-300 hover:bg-slate-600' : 'bg-slate-100 text-rose-700 hover:bg-slate-200'}`}
                        >
                          Abbrechen
                        </button>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Live-Log ganz unten — Detail-Ansicht, nicht Haupt-Info */}
      <LiveLogSection />
    </div>
  )
}

function StatCard({ icon: Icon, label, value, color, darkMode }: { icon: any, label: string, value: string, color: string, darkMode: boolean }) {
  const { theme } = useDarkMode()
  const bgColors = darkMode
    ? {
        card: 'bg-slate-800 border-slate-700',
        iconBg: {
          amber: 'bg-amber-700',
          blue: 'bg-blue-700',
          emerald: 'bg-emerald-700',
          rose: 'bg-rose-700',
        },
        iconText: {
          amber: 'text-amber-300',
          blue: 'text-blue-300',
          emerald: 'text-emerald-300',
          rose: 'text-rose-300',
        },
        textLabel: 'text-slate-400',
        textValue: 'text-slate-200',
      }
    : {
        card: 'bg-white border-slate-200',
        iconBg: {
          amber: 'bg-amber-500',
          blue: 'bg-blue-500',
          emerald: 'bg-emerald-500',
          rose: 'bg-rose-500',
        },
        iconText: {
          amber: 'text-amber-600',
          blue: 'text-blue-600',
          emerald: 'text-emerald-600',
          rose: 'text-rose-600',
        },
        textLabel: 'text-slate-500',
        textValue: 'text-slate-900',
      }
  
  return (
    <div className={`${bgColors.card} rounded-xl shadow-sm border p-6 hover:shadow-md transition-shadow`}>
      <div className="flex items-center gap-4">
        <div className={`${bgColors.iconBg[color as keyof typeof bgColors.iconBg]} p-3 rounded-lg`}>
          <Icon className={`${bgColors.iconText[color as keyof typeof bgColors.iconText]} w-6 h-6`} />
        </div>
        <div>
          <p className={`text-sm font-medium ${bgColors.textLabel}`}>{label}</p>
          <p className={`text-3xl font-bold ${bgColors.textValue}`}>{value}</p>
        </div>
      </div>
    </div>
  )
}
