import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import {
  Activity,
  Server,
  Database,
  Cpu,
  HardDrive,
  Clock,
  AlertCircle,
  CheckCircle,
  AlertTriangle,
  XCircle,
  Package,
  RefreshCw,
  Wifi,
  Image as ImageIcon,
  Zap,
  Play,
  HeartPulse,
} from 'lucide-react'
import { api, wsClient, getErrorMessage } from '../lib/api'
import { formatBytes, formatRelativeTime } from '../lib/utils'
import { notificationManager } from '../lib/notificationManager'

function StatusBadge({ status }: { status: 'healthy' | 'warning' | 'error' | 'unknown' }) {
  const styles = {
    healthy: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400',
    warning: 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-400',
    error: 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400',
    unknown: 'bg-slate-100 text-slate-700 dark:bg-slate-500/20 dark:text-slate-400',
  }

  const icons = {
    healthy: CheckCircle,
    warning: AlertTriangle,
    error: XCircle,
    unknown: AlertCircle,
  }

  const Icon = icons[status]

  return (
    <span className={`inline-flex items-center space-x-1 px-3 py-1 text-xs font-medium rounded-full ${styles[status]}`}>
      <Icon className="w-3 h-3" />
      <span className="capitalize">{status}</span>
    </span>
  )
}

function MetricCard({
  title,
  value,
  unit,
  status,
  icon: Icon,
  subtitle,
  color = 'blue',
}: {
  title: string
  value: number | string
  unit?: string
  status: 'healthy' | 'warning' | 'error' | 'unknown'
  icon: any
  subtitle?: string
  color?: 'blue' | 'green' | 'purple' | 'orange' | 'cyan'
}) {
  const statusColors = {
    healthy: 'text-emerald-600 dark:text-emerald-400',
    warning: 'text-amber-600 dark:text-amber-400',
    error: 'text-red-600 dark:text-red-400',
    unknown: 'text-slate-600 dark:text-slate-400',
  }

  const colorStyles: Record<string, { card: string; icon: string }> = {
    blue: {
      card: 'stat-card-blue shadow-blue-glow',
      icon: 'bg-blue-500/20 text-blue-600 dark:text-blue-400',
    },
    green: {
      card: 'stat-card-green shadow-green-glow',
      icon: 'bg-emerald-500/20 text-emerald-600 dark:text-emerald-400',
    },
    purple: {
      card: 'stat-card-purple shadow-purple-glow',
      icon: 'bg-violet-500/20 text-violet-600 dark:text-violet-400',
    },
    orange: {
      card: 'stat-card-orange shadow-orange-glow',
      icon: 'bg-amber-500/20 text-amber-600 dark:text-amber-400',
    },
    cyan: {
      card: 'stat-card-cyan',
      icon: 'bg-cyan-500/20 text-cyan-600 dark:text-cyan-400',
    },
  }

  const styles = colorStyles[color]

  return (
    <div className={`card-glass-hover rounded-xl p-6 border ${styles.card}`}>
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center space-x-3">
          <div className={`p-2 rounded-xl ${styles.icon} ${statusColors[status]}`}>
            <Icon className="w-5 h-5" />
          </div>
          <h3 className="font-medium text-foreground">{title}</h3>
        </div>
        <StatusBadge status={status} />
      </div>
      <div className="mt-2">
        <div className="flex items-baseline space-x-2">
          <span className="text-3xl font-semibold text-foreground">{value}</span>
          {unit && <span className="text-sm text-muted-foreground">{unit}</span>}
        </div>
        {subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
      </div>
    </div>
  )
}

export default function Health() {
  useBreadcrumb(breadcrumbConfig['/health'])
  const queryClient = useQueryClient()
  const [checkingDeps, setCheckingDeps] = useState(false)
  const [runningCleanup, setRunningCleanup] = useState(false)
  const [cleanupResult, setCleanupResult] = useState<any>(null)

  const { data: healthData, refetch: refetchHealth, error: healthError, isError: isHealthError } = useQuery({
    queryKey: ['system-health'],
    queryFn: () => api.getSystemHealth(),
    refetchInterval: 5000,
  })

  const { data: depsStatus } = useQuery({
    queryKey: ['dependencies-status'],
    queryFn: () => api.getDependenciesStatus(),
    refetchInterval: 60000, // Refresh every minute
  })

  const checkDepsMutation = useMutation({
    mutationFn: () => api.checkDependencies(),
    onMutate: () => {
      setCheckingDeps(true)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['dependencies-status'] })
      setTimeout(() => setCheckingDeps(false), 2000)
    },
    onError: () => {
      setCheckingDeps(false)
    },
  })

  const triggerCacheMutation = useMutation({
    mutationFn: () => api.triggerCacheBuilder(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['system-health'] })
    },
  })

  // Handle Database Cleanup
  const handleDatabaseCleanup = async (dryRun: boolean = true) => {
    try {
      setRunningCleanup(true)
      setCleanupResult(null)

      // Start the cleanup
      await api.post('/maintenance/cleanup/missing-files', { dry_run: dryRun })

      // Poll for status
      const pollStatus = async () => {
        const response: any = await api.get('/maintenance/cleanup/status')

        if (response.status === 'running') {
          setTimeout(pollStatus, 2000) // Check again in 2 seconds
        } else if (response.status === 'completed') {
          setCleanupResult(response)
          setRunningCleanup(false)
          notificationManager.success(
            'Database Cleanup Complete',
            dryRun
              ? `Found ${response.total_missing} missing files that would be removed`
              : `Removed ${response.total_removed} missing file references`
          )
        } else if (response.status === 'failed') {
          setRunningCleanup(false)
          notificationManager.error('Cleanup Failed', response.error || 'Unknown error')
        }
      }

      setTimeout(pollStatus, 1000)

    } catch (error: unknown) {
      console.error('Failed to run cleanup:', error)
      notificationManager.error('Cleanup Failed', getErrorMessage(error))
      setRunningCleanup(false)
    }
  }

  // Listen for WebSocket updates
  useEffect(() => {
    const unsubscribe = wsClient.on('*', () => {
      refetchHealth()
    })
    return unsubscribe
  }, [refetchHealth])

  // Display error if query fails
  if (isHealthError) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3 mb-2">
            <HeartPulse className="w-8 h-8 text-pink-500" />
            System Health
          </h1>
          <p className="text-slate-600 dark:text-slate-400">Monitor system status and service health</p>
        </div>
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6">
          <h3 className="text-lg font-semibold text-red-900 dark:text-red-100 mb-2">Error Loading Health Data</h3>
          <p className="text-red-700 dark:text-red-300 mb-4">{healthError instanceof Error ? healthError.message : String(healthError)}</p>
          <button
            onClick={() => refetchHealth()}
            className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded transition-colors"
          >
            Retry
          </button>
        </div>
      </div>
    )
  }

  const getStatusFromValue = (value: number, warningThreshold: number, errorThreshold: number): 'healthy' | 'warning' | 'error' => {
    if (value >= errorThreshold) return 'error'
    if (value >= warningThreshold) return 'warning'
    return 'healthy'
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
          <HeartPulse className="w-8 h-8 text-pink-500" />
          System Health
        </h1>
        <p className="text-slate-600 dark:text-slate-400 mt-1">
          Monitor system status and service health
        </p>
      </div>

      {/* Overall Status */}
      <div className="card-glass-hover rounded-xl p-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <div className="p-3 rounded-xl bg-emerald-500/10">
              <Activity className="w-8 h-8 text-emerald-600 dark:text-emerald-400" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-foreground">System Status</h3>
              <p className="text-sm text-muted-foreground">
                Last updated: {healthData?.timestamp ? formatRelativeTime(healthData.timestamp) : 'Never'}
              </p>
            </div>
          </div>
          <StatusBadge status={healthData?.overall_status || 'unknown'} />
        </div>
      </div>

      {/* Service Status */}
      <div>
        <h3 className="text-lg font-semibold text-foreground mb-4">Services</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div className="card-glass-hover rounded-xl p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center space-x-2">
                <Server className="w-4 h-4 text-muted-foreground" />
                <span className="font-medium text-foreground">API Server</span>
              </div>
              <StatusBadge status={healthData?.services?.api || 'unknown'} />
            </div>
            <p className="text-sm text-muted-foreground">FastAPI backend</p>
          </div>

          <div className="card-glass-hover rounded-xl p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center space-x-2">
                <Database className="w-4 h-4 text-muted-foreground" />
                <span className="font-medium text-foreground">Database</span>
              </div>
              <StatusBadge status={healthData?.services?.database || 'unknown'} />
            </div>
            <p className="text-sm text-muted-foreground">
              {healthData?.db_performance?.query_time_ms ? `Query: ${healthData.db_performance.query_time_ms}ms` : 'SQLite connection'}
            </p>
          </div>

          <div className="card-glass-hover rounded-xl p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center space-x-2">
                <Clock className="w-4 h-4 text-muted-foreground" />
                <span className="font-medium text-foreground">Scheduler</span>
              </div>
              <StatusBadge status={healthData?.services?.scheduler || 'unknown'} />
            </div>
            <p className="text-sm text-muted-foreground">
              {healthData?.scheduler_info?.active_tasks || 0} active tasks
            </p>
          </div>

          <div className="card-glass-hover rounded-xl p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center space-x-2">
                <Wifi className="w-4 h-4 text-muted-foreground" />
                <span className="font-medium text-foreground">WebSocket</span>
              </div>
              <StatusBadge status={healthData?.services?.websocket || 'unknown'} />
            </div>
            <p className="text-sm text-muted-foreground">
              {healthData?.websocket_info?.active_connections || 0} active connections
            </p>
          </div>

          <div className="card-glass-hover rounded-xl p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center space-x-2">
                <ImageIcon className="w-4 h-4 text-muted-foreground" />
                <span className="font-medium text-foreground">Cache Builder</span>
              </div>
              <StatusBadge status={healthData?.services?.cache_builder || 'unknown'} />
            </div>
            <div className="flex items-center justify-between">
              <p className="text-sm text-muted-foreground">
                {healthData?.cache_info?.files_cached || 0} files cached
              </p>
              <button
                onClick={() => triggerCacheMutation.mutate()}
                disabled={triggerCacheMutation.isPending}
                className="p-1 text-primary hover:text-primary/80 disabled:opacity-50"
                title="Trigger cache rebuild"
              >
                <Play className={`w-4 h-4 ${triggerCacheMutation.isPending ? 'animate-pulse' : ''}`} />
              </button>
            </div>
          </div>

          <div className="card-glass-hover rounded-xl p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center space-x-2">
                <Zap className="w-4 h-4 text-muted-foreground" />
                <span className="font-medium text-foreground">Process</span>
              </div>
              <span className="text-xs px-2 py-1 bg-secondary rounded-lg text-muted-foreground">
                {healthData?.process_info?.threads || 0} threads
              </span>
            </div>
            <p className="text-sm text-muted-foreground">
              {healthData?.process_info?.open_files || 0} open files
            </p>
          </div>
        </div>
      </div>

      {/* System Metrics */}
      <div>
        <h3 className="text-lg font-semibold text-foreground mb-4">System Resources</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <MetricCard
            title="CPU Usage"
            value={healthData?.system?.cpu_percent?.toFixed(1) || '0'}
            unit="%"
            status={getStatusFromValue(healthData?.system?.cpu_percent || 0, 70, 90)}
            icon={Cpu}
            subtitle={`${healthData?.system?.cpu_count || 0} cores`}
            color="blue"
          />
          <MetricCard
            title="Memory Usage"
            value={healthData?.system?.memory_percent?.toFixed(1) || '0'}
            unit="%"
            status={getStatusFromValue(healthData?.system?.memory_percent || 0, 80, 95)}
            icon={Activity}
            subtitle={`${formatBytes(healthData?.system?.memory_used || 0)} / ${formatBytes(healthData?.system?.memory_total || 0)}`}
            color="purple"
          />
          <MetricCard
            title="Disk Usage"
            value={healthData?.system?.disk_percent?.toFixed(1) || '0'}
            unit="%"
            status={getStatusFromValue(healthData?.system?.disk_percent || 0, 80, 95)}
            icon={HardDrive}
            subtitle={`${formatBytes(healthData?.system?.disk_free || 0)} free`}
            color="orange"
          />
          <MetricCard
            title="Uptime"
            value={healthData?.system?.uptime_hours?.toFixed(0) || '0'}
            unit="hours"
            status="healthy"
            icon={Clock}
            subtitle="System running"
            color="green"
          />
        </div>
      </div>

      {/* Download Activity */}
      {healthData?.download_activity && (
        <div>
          <h3 className="text-lg font-semibold text-foreground mb-4">Download Activity</h3>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="card-glass-hover rounded-xl p-4">
              <div className="text-sm text-muted-foreground">Last 24 Hours</div>
              <div className="mt-2 text-2xl font-semibold text-foreground">
                {healthData.download_activity.last_24h}
              </div>
            </div>
            <div className="card-glass-hover rounded-xl p-4">
              <div className="text-sm text-muted-foreground">Last 7 Days</div>
              <div className="mt-2 text-2xl font-semibold text-foreground">
                {healthData.download_activity.last_7d}
              </div>
            </div>
            <div className="card-glass-hover rounded-xl p-4">
              <div className="text-sm text-muted-foreground">Last 30 Days</div>
              <div className="mt-2 text-2xl font-semibold text-foreground">
                {healthData.download_activity.last_30d}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Dependencies */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-foreground flex items-center space-x-2">
            <Package className="w-5 h-5" />
            <span>Dependencies</span>
          </h3>
          <button
            onClick={() => checkDepsMutation.mutate()}
            disabled={checkingDeps || checkDepsMutation.isPending}
            className="inline-flex items-center px-4 py-2 bg-primary hover:bg-primary/90 text-primary-foreground rounded-xl disabled:opacity-50 transition-colors btn-hover-lift"
            title="Check for updates and install if available"
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${checkingDeps ? 'animate-spin' : ''}`} />
            {checkingDeps ? 'Updating...' : 'Check & Update'}
          </button>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {['flaresolverr', 'playwright', 'yt_dlp', 'python_packages'].map((component) => {
            const componentData = depsStatus?.components?.[component]
            const componentNames: Record<string, string> = {
              flaresolverr: 'FlareSolverr',
              playwright: 'Playwright',
              yt_dlp: 'yt-dlp',
              python_packages: 'Python Packages'
            }
            const status = componentData?.status || 'unknown'
            const statusColors = {
              updated: 'bg-green-100 text-green-700 dark:bg-green-500/20 dark:text-green-400',
              current: 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400',
              unknown: 'bg-secondary text-muted-foreground'
            }

            return (
              <div key={component} className="card-glass-hover rounded-xl p-4">
                <div className="flex items-center justify-between mb-2">
                  <div className="font-medium text-foreground">
                    {componentNames[component]}
                  </div>
                  <span className={`px-2 py-1 text-xs font-medium rounded-lg ${statusColors[status as keyof typeof statusColors] || statusColors.unknown}`}>
                    {status}
                  </span>
                </div>
                {componentData?.last_update && (
                  <div className="text-xs text-muted-foreground">
                    Updated: {formatRelativeTime(componentData.last_update)}
                  </div>
                )}
                {componentData?.last_check && !componentData?.last_update && (
                  <div className="text-xs text-muted-foreground">
                    Checked: {formatRelativeTime(componentData.last_check)}
                  </div>
                )}
                {component === 'python_packages' && (componentData as any)?.updated_packages?.length > 0 && (
                  <div className="text-xs text-muted-foreground mt-1">
                    {(componentData as any).updated_packages.slice(0, 3).join(', ')}
                    {(componentData as any).updated_packages.length > 3 && ` +${(componentData as any).updated_packages.length - 3} more`}
                  </div>
                )}
              </div>
            )
          })}
        </div>
        {depsStatus?.last_check && (
          <div className="mt-3 text-sm text-muted-foreground">
            Last checked: {formatRelativeTime(depsStatus.last_check)}
          </div>
        )}
      </div>

      {/* Database Maintenance */}
      <div>
        <h3 className="text-lg font-semibold text-foreground mb-4 flex items-center space-x-2">
          <Database className="w-5 h-5" />
          <span>Database Maintenance</span>
        </h3>
        <div className="card-glass-hover rounded-xl p-6">
          {/* Info Banner */}
          <div className="mb-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
            <div className="flex items-start space-x-3">
              <AlertCircle className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
              <div className="text-sm">
                <p className="text-blue-900 dark:text-blue-100 font-medium mb-1">
                  Automatic Cleanup Schedule
                </p>
                <p className="text-blue-700 dark:text-blue-300">
                  Database cleanup runs automatically every night at 3:00 AM to remove references to deleted files.
                  You can also run a manual scan below.
                </p>
              </div>
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex flex-wrap gap-3 mb-4">
            <button
              onClick={() => handleDatabaseCleanup(true)}
              disabled={runningCleanup}
              className="inline-flex items-center px-4 py-2 bg-secondary hover:bg-secondary/80 text-foreground rounded-xl disabled:opacity-50 transition-colors btn-hover-lift"
            >
              <RefreshCw className={`w-4 h-4 mr-2 ${runningCleanup ? 'animate-spin' : ''}`} />
              {runningCleanup ? 'Scanning...' : 'Scan (Dry Run)'}
            </button>
            <button
              onClick={() => handleDatabaseCleanup(false)}
              disabled={runningCleanup}
              className="inline-flex items-center px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-xl disabled:opacity-50 transition-colors btn-hover-lift"
            >
              <Database className={`w-4 h-4 mr-2 ${runningCleanup ? 'animate-spin' : ''}`} />
              {runningCleanup ? 'Cleaning...' : 'Clean Now'}
            </button>
          </div>

          {/* Results Display */}
          {cleanupResult && (
            <div className="border border-border rounded-lg p-4 bg-secondary/50">
              <h4 className="font-medium text-foreground mb-3">Last Scan Results</h4>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">Status:</span>
                  <span className="font-medium text-foreground capitalize">{cleanupResult.status}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">Total Missing:</span>
                  <span className="font-medium text-foreground">{cleanupResult.total_missing}</span>
                </div>
                {cleanupResult.total_removed !== undefined && (
                  <div className="flex justify-between items-center">
                    <span className="text-muted-foreground">Total Removed:</span>
                    <span className="font-medium text-red-600 dark:text-red-400">{cleanupResult.total_removed}</span>
                  </div>
                )}
                {cleanupResult.tables && Object.keys(cleanupResult.tables).length > 0 && (
                  <div className="mt-3 pt-3 border-t border-border">
                    <div className="text-muted-foreground mb-2">By Table:</div>
                    <div className="space-y-1">
                      {Object.entries(cleanupResult.tables).map(([table, count]: [string, any]) => (
                        <div key={table} className="flex justify-between items-center pl-2">
                          <span className="text-xs text-muted-foreground">{table}:</span>
                          <span className="text-xs font-medium text-foreground">{count}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Recent Errors */}
      {healthData?.recent_errors && healthData.recent_errors.length > 0 && (
        <div>
          <h3 className="text-lg font-semibold text-foreground mb-4 flex items-center space-x-2">
            <AlertCircle className="w-5 h-5 text-red-500" />
            <span>Recent Errors</span>
          </h3>
          <div className="card-glass-hover rounded-xl overflow-hidden">
            <div className="divide-y divide-border">
              {healthData.recent_errors.map((error: any, index: number) => (
                <div key={index} className="p-4 hover:bg-secondary/50 transition-colors">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <p className="text-sm font-medium text-foreground">{error.message}</p>
                      {error.details && (
                        <p className="mt-1 text-sm text-muted-foreground">{error.details}</p>
                      )}
                    </div>
                    <span className="text-xs text-muted-foreground">
                      {formatRelativeTime(error.timestamp)}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
