import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import { Clock, Play, Pause, Calendar, TrendingUp, Activity, Power, RefreshCw, CalendarClock, Timer, X } from 'lucide-react'
import { api } from '../lib/api'
import { formatRelativeTime } from '../lib/utils'

export default function Scheduler() {
  useBreadcrumb(breadcrumbConfig['/scheduler'])
  const queryClient = useQueryClient()

  const { data: schedulerStatus, isLoading } = useQuery({
    queryKey: ['scheduler-status'],
    queryFn: () => api.getSchedulerStatus(),
    refetchInterval: 10000, // Refresh every 10 seconds
  })

  const { data: serviceStatus } = useQuery({
    queryKey: ['scheduler-service-status'],
    queryFn: () => api.getSchedulerServiceStatus(),
    refetchInterval: 10000, // Refresh every 10 seconds
  })

  const { data: platforms } = useQuery({
    queryKey: ['platforms'],
    queryFn: () => api.getPlatforms(),
  })

  const { data: config } = useQuery({
    queryKey: ['config'],
    queryFn: () => api.getConfig(),
  })

  // Filter out tasks for disabled and hidden platforms
  const hiddenModules = (config?.hidden_modules || []) as string[]
  const enabledTasks = (schedulerStatus?.tasks.filter((task) => {
    const [platformKey] = task.task_id.split(':')
    if (hiddenModules.includes(platformKey)) return false
    const platform = platforms?.find((p) => p.name === platformKey)
    return platform?.enabled !== false
  }) || []).sort((a, b) => {
    const parseRun = (s: string | null) => s ? new Date(s.replace(' ', 'T')).getTime() || Infinity : Infinity
    return parseRun(a.next_run) - parseRun(b.next_run)
  })

  const pauseMutation = useMutation({
    mutationFn: (taskId: string) => api.pauseSchedulerTask(taskId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scheduler-status'] })
    },
  })

  const resumeMutation = useMutation({
    mutationFn: (taskId: string) => api.resumeSchedulerTask(taskId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scheduler-status'] })
    },
  })

  const startServiceMutation = useMutation({
    mutationFn: () => api.startSchedulerService(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scheduler-service-status'] })
    },
  })

  const stopServiceMutation = useMutation({
    mutationFn: () => api.stopSchedulerService(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scheduler-service-status'] })
    },
  })

  const restartServiceMutation = useMutation({
    mutationFn: () => api.restartSchedulerService(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scheduler-service-status'] })
    },
  })

  const handlePause = (taskId: string) => {
    if (confirm(`Are you sure you want to pause task: ${taskId}?`)) {
      pauseMutation.mutate(taskId)
    }
  }

  const handleResume = (taskId: string) => {
    resumeMutation.mutate(taskId)
  }

  const [rescheduleTask, setRescheduleTask] = useState<{ task_id: string; next_run: string } | null>(null)
  const [rescheduleTime, setRescheduleTime] = useState('')

  const rescheduleMutation = useMutation({
    mutationFn: ({ taskId, nextRun }: { taskId: string; nextRun: string }) =>
      api.rescheduleTask(taskId, nextRun),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scheduler-status'] })
      setRescheduleTask(null)
    },
  })

  const toLocalDatetimeString = (d: Date): string => {
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hours = String(d.getHours()).padStart(2, '0')
    const minutes = String(d.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day}T${hours}:${minutes}`
  }

  const adjustTime = (minutes: number) => {
    const d = new Date(rescheduleTime)
    d.setMinutes(d.getMinutes() + minutes)
    setRescheduleTime(toLocalDatetimeString(d))
  }

  const getStatusColor = (status: string) => {
    if (status === 'active') return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400'
    if (status === 'paused') return 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-400'
    return 'bg-slate-100 text-slate-700 dark:bg-slate-500/20 dark:text-slate-400'
  }

  const getTaskPlatform = (taskId: string) => {
    const [platform] = taskId.split(':')
    const platformNames: Record<string, string> = {
      instagram_unified: 'Instagram',
      instagram: 'InstaLoader',
      fastdl: 'FastDL',
      imginn: 'ImgInn',
      imginn_api: 'ImgInn API',
      instagram_client: 'Instagram',
      toolzu: 'Toolzu',
      snapchat: 'Snapchat',
      snapchat_client: 'Snapchat',
      tiktok: 'TikTok',
      forum: 'Forum',
      monitor: 'Monitor',
      appearances: 'Appearances',
      paid_content: 'Paid Content',
      youtube_channel_monitor: 'YouTube Monitor',
      youtube_monitor: 'YouTube Monitor',
      youtube_paused_monitor: 'YouTube Monitor',  // Legacy name (pre-rename)
      easynews_monitor: 'Easynews',
      reddit_monitor: 'Reddit Monitor',
      press_monitor: 'Press',
      tmdb_appearances_sync: 'TMDb Appearances',  // Legacy name
      appearance_reminders: 'Appearances'  // Legacy name
    }
    return platformNames[platform] || platform
  }

  const getTaskAccount = (taskId: string) => {
    const parts = taskId.split(':')
    // Tasks without accounts (like youtube_channel_monitor) should show description, not "Unknown"
    if (parts.length === 1) {
      const taskDescriptions: Record<string, string> = {
        youtube_channel_monitor: 'Channel phrase matching',
        youtube_monitor: 'Channel phrase matching',
        youtube_paused_monitor: 'Paused channel re-checks',  // Legacy name (pre-rename)
        easynews_monitor: 'Media Monitor',
        reddit_monitor: 'Community Monitor',
        press_monitor: 'GDELT News Monitor',
        tmdb_appearances_sync: 'Celebrity TV sync',  // Legacy name
        appearance_reminders: 'Daily Reminders'  // Legacy name
      }
      return taskDescriptions[parts[0]] || ''
    }
    // Special handling for youtube_monitor subtasks
    if (parts[0] === 'youtube_monitor' && parts[1] === 'paused') {
      return 'Paused channel re-checks'
    }
    // Appearance task descriptions
    if (parts[0] === 'appearances') {
      const appearanceDescriptions: Record<string, string> = {
        'tmdb_sync': 'TMDb Sync',
        'reminders': 'Daily Reminders'
      }
      return appearanceDescriptions[parts[1]] || parts[1]
    }
    // Paid content task descriptions
    if (parts[0] === 'paid_content') {
      const paidContentDescriptions: Record<string, string> = {
        'sync': 'All Creators'
      }
      return paidContentDescriptions[parts[1]] || parts[1]
    }
    return parts[1]
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="animate-pulse">
          <div className="h-8 bg-slate-200 dark:bg-slate-700 rounded w-1/4 mb-2"></div>
          <div className="h-4 bg-slate-200 dark:bg-slate-700 rounded w-1/2"></div>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-3">
            <CalendarClock className="w-7 h-7 sm:w-8 sm:h-8 text-emerald-500" />
            Scheduler
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1 text-sm sm:text-base">
            Manage scheduled download tasks
          </p>
        </div>
        <div className="flex items-center gap-2 sm:gap-3">
          <div className="flex items-center gap-2">
            <div className={`w-2 h-2 rounded-full ${serviceStatus?.running ? 'bg-green-500' : 'bg-red-500'}`} />
            <span className="text-sm font-medium text-slate-700 dark:text-slate-300">
              {serviceStatus?.running ? 'Running' : 'Stopped'}
            </span>
          </div>
          {serviceStatus?.running ? (
            <>
              <button
                onClick={() => stopServiceMutation.mutate()}
                disabled={stopServiceMutation.isPending}
                className="inline-flex items-center justify-center p-2 sm:px-4 sm:py-2 border border-red-300 dark:border-red-700 text-red-700 dark:text-red-400 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 disabled:opacity-50 transition-colors min-w-[44px] min-h-[44px]"
                title="Stop"
              >
                <Pause className="w-4 h-4 sm:mr-2" />
                <span className="hidden sm:inline">Stop</span>
              </button>
              <button
                onClick={() => restartServiceMutation.mutate()}
                disabled={restartServiceMutation.isPending}
                className="inline-flex items-center justify-center p-2 sm:px-4 sm:py-2 border border-blue-300 dark:border-blue-700 text-blue-700 dark:text-blue-400 rounded-lg hover:bg-blue-50 dark:hover:bg-blue-900/20 disabled:opacity-50 transition-colors min-w-[44px] min-h-[44px]"
                title="Restart"
              >
                <RefreshCw className="w-4 h-4 sm:mr-2" />
                <span className="hidden sm:inline">Restart</span>
              </button>
            </>
          ) : (
            <button
              onClick={() => startServiceMutation.mutate()}
              disabled={startServiceMutation.isPending}
              className="inline-flex items-center justify-center p-2 sm:px-4 sm:py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg disabled:opacity-50 transition-colors min-w-[44px] min-h-[44px]"
              title="Start"
            >
              <Power className="w-4 h-4 sm:mr-2" />
              <span className="hidden sm:inline">Start</span>
            </button>
          )}
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <div className="card-glass-hover rounded-xl p-6 border stat-card-blue shadow-blue-glow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-muted-foreground">Total Tasks</p>
              <p className="mt-2 text-3xl font-bold text-foreground animate-count-up">
                {enabledTasks.length}
              </p>
            </div>
            <div className="p-3 rounded-xl bg-blue-500/20 text-blue-600 dark:text-blue-400">
              <Clock className="w-6 h-6" />
            </div>
          </div>
        </div>

        <div className="card-glass-hover rounded-xl p-6 border stat-card-green shadow-green-glow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-muted-foreground">Active Tasks</p>
              <p className="mt-2 text-3xl font-bold text-emerald-600 dark:text-emerald-400 animate-count-up">
                {enabledTasks.filter(t => t.status === 'active').length}
              </p>
            </div>
            <div className="p-3 rounded-xl bg-emerald-500/20 text-emerald-600 dark:text-emerald-400">
              <Activity className="w-6 h-6" />
            </div>
          </div>
        </div>

        <div className="card-glass-hover rounded-xl p-6 border stat-card-orange shadow-orange-glow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-muted-foreground">Paused Tasks</p>
              <p className="mt-2 text-3xl font-bold text-amber-600 dark:text-amber-400 animate-count-up">
                {enabledTasks.filter(t => t.status === 'paused').length}
              </p>
            </div>
            <div className="p-3 rounded-xl bg-amber-500/20 text-amber-600 dark:text-amber-400">
              <Pause className="w-6 h-6" />
            </div>
          </div>
        </div>

        <div className="card-glass-hover rounded-xl p-6 border stat-card-purple shadow-purple-glow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-muted-foreground">Next Run</p>
              <p className="mt-2 text-sm font-bold text-foreground">
                {schedulerStatus?.next_run ? formatRelativeTime(schedulerStatus.next_run) : 'N/A'}
              </p>
            </div>
            <div className="p-3 rounded-xl bg-violet-500/20 text-violet-600 dark:text-violet-400">
              <Calendar className="w-6 h-6" />
            </div>
          </div>
        </div>
      </div>

      {/* Tasks Table */}
      <div className="card-glass-hover rounded-xl overflow-hidden">
        <div className="px-6 py-4 border-b border-border">
          <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
            Scheduled Tasks
          </h3>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full min-w-full">
            <thead className="bg-slate-50 dark:bg-slate-800">
              <tr>
                <th className="px-3 sm:px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                  Task
                </th>
                <th className="hidden md:table-cell px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                  Status
                </th>
                <th className="hidden lg:table-cell px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                  Last Run
                </th>
                <th className="hidden sm:table-cell px-3 sm:px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                  Next Run
                </th>
                <th className="hidden lg:table-cell px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                  Runs
                </th>
                <th className="px-3 sm:px-6 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200 dark:divide-slate-800">
              {enabledTasks.map((task) => (
                <tr key={task.task_id} className="table-row-hover-stripe">
                  <td className="px-3 sm:px-6 py-3 sm:py-4">
                    <div className="flex items-center max-w-[180px] sm:max-w-none">
                      <TrendingUp className="w-4 h-4 sm:w-5 sm:h-5 mr-2 sm:mr-3 text-slate-400 flex-shrink-0" />
                      <div className="min-w-0 flex-1 overflow-hidden">
                        <div className="text-xs sm:text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
                          {getTaskPlatform(task.task_id)}
                        </div>
                        <div className="text-xs text-slate-600 dark:text-slate-400 truncate">
                          {getTaskAccount(task.task_id)}
                        </div>
                        {/* Mobile-only: Show status, last run, and next run */}
                        <div className="sm:hidden mt-1.5 space-y-1">
                          <div className="flex items-center gap-2">
                            <span className={`px-2 py-0.5 text-[10px] font-medium rounded-full ${getStatusColor(task.status)}`}>
                              {task.status}
                            </span>
                            <span className="text-[10px] text-slate-500 dark:text-slate-400">
                              {task.run_count} runs
                            </span>
                          </div>
                          <div className="text-[10px] text-slate-500 dark:text-slate-400">
                            <span className="inline-flex items-center gap-1 mr-5">
                              <Calendar className="w-3 h-3 flex-shrink-0" />
                              {task.last_run ? formatRelativeTime(task.last_run) : 'Never'}
                            </span>
                            <span className="inline-flex items-center gap-1">
                              <Clock className="w-3 h-3 flex-shrink-0" />
                              {task.next_run ? formatRelativeTime(task.next_run) : 'N/A'}
                            </span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </td>
                  <td className="hidden md:table-cell px-6 py-4 whitespace-nowrap">
                    <span className={`px-3 py-1 text-xs font-medium rounded-full ${getStatusColor(task.status)}`}>
                      {task.status}
                    </span>
                  </td>
                  <td className="hidden lg:table-cell px-6 py-4 whitespace-nowrap text-sm text-slate-600 dark:text-slate-400">
                    {task.last_run ? formatRelativeTime(task.last_run) : 'Never'}
                  </td>
                  <td className="hidden sm:table-cell px-3 sm:px-6 py-4 whitespace-nowrap text-xs sm:text-sm text-slate-600 dark:text-slate-400">
                    {task.next_run ? formatRelativeTime(task.next_run) : 'N/A'}
                  </td>
                  <td className="hidden lg:table-cell px-6 py-4 whitespace-nowrap text-sm text-slate-600 dark:text-slate-400">
                    {task.run_count}
                  </td>
                  <td className="px-3 sm:px-6 py-3 sm:py-4 whitespace-nowrap text-right text-sm">
                    <div className="inline-flex items-center gap-2">
                      {task.status === 'active' ? (
                        <button
                          onClick={() => handlePause(task.task_id)}
                          disabled={pauseMutation.isPending}
                          className="inline-flex items-center p-2 sm:px-3 sm:py-2 border border-amber-300 dark:border-amber-700 text-amber-700 dark:text-amber-400 rounded-lg hover:bg-amber-50 dark:hover:bg-amber-900/20 disabled:opacity-50 min-w-[44px] min-h-[44px] justify-center transition-colors"
                        >
                          <Pause className="w-4 h-4 sm:mr-1" />
                          <span className="hidden sm:inline">Pause</span>
                        </button>
                      ) : (
                        <button
                          onClick={() => handleResume(task.task_id)}
                          disabled={resumeMutation.isPending}
                          className="inline-flex items-center p-2 sm:px-3 sm:py-2 border border-emerald-300 dark:border-emerald-700 text-emerald-700 dark:text-emerald-400 rounded-lg hover:bg-emerald-50 dark:hover:bg-emerald-900/20 disabled:opacity-50 min-w-[44px] min-h-[44px] justify-center transition-colors"
                        >
                          <Play className="w-4 h-4 sm:mr-1" />
                          <span className="hidden sm:inline">Resume</span>
                        </button>
                      )}
                      <button
                        onClick={() => {
                          setRescheduleTask({ task_id: task.task_id, next_run: task.next_run || new Date().toISOString() })
                          const d = new Date(task.next_run || new Date())
                          setRescheduleTime(toLocalDatetimeString(d))
                        }}
                        className="inline-flex items-center p-2 sm:px-3 sm:py-2 border border-blue-300 dark:border-blue-700 text-blue-700 dark:text-blue-400 rounded-lg hover:bg-blue-50 dark:hover:bg-blue-900/20 min-w-[44px] min-h-[44px] justify-center transition-colors"
                        title="Reschedule"
                      >
                        <Timer className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Info Box */}
      <div className="glass-gradient-border rounded-xl p-4">
        <h4 className="text-sm font-medium text-blue-900 dark:text-blue-200 mb-2">
          About the Scheduler
        </h4>
        <p className="text-sm text-blue-800 dark:text-blue-300">
          The scheduler automatically runs download tasks at randomized intervals to avoid detection.
          You can pause individual tasks here without affecting the main scheduler service.
          Paused tasks will be skipped until resumed.
        </p>
      </div>

      {/* Reschedule Modal */}
      {rescheduleTask && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={() => setRescheduleTask(null)} />
          <div className="relative bg-card rounded-xl shadow-2xl border border-border w-full max-w-md">
            <div className="flex items-center justify-between px-6 py-4 border-b border-border">
              <h3 className="text-lg font-semibold text-foreground">
                Reschedule {getTaskPlatform(rescheduleTask.task_id)}
              </h3>
              <button
                onClick={() => setRescheduleTask(null)}
                className="p-1 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
              >
                <X className="w-5 h-5 text-slate-500" />
              </button>
            </div>

            <div className="px-6 py-5 space-y-4">
              <div>
                <p className="text-sm text-muted-foreground mb-1">Current next run</p>
                <p className="text-sm font-medium text-foreground">
                  {new Date(rescheduleTask.next_run).toLocaleString()}
                </p>
              </div>

              <div>
                <p className="text-sm text-muted-foreground mb-2">Quick adjust</p>
                <div className="flex gap-2">
                  <button
                    onClick={() => adjustTime(-60)}
                    className="flex-1 px-3 py-2 text-sm font-medium border border-border rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                  >
                    -1h
                  </button>
                  <button
                    onClick={() => adjustTime(-15)}
                    className="flex-1 px-3 py-2 text-sm font-medium border border-border rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                  >
                    -15m
                  </button>
                  <button
                    onClick={() => adjustTime(15)}
                    className="flex-1 px-3 py-2 text-sm font-medium border border-border rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                  >
                    +15m
                  </button>
                  <button
                    onClick={() => adjustTime(60)}
                    className="flex-1 px-3 py-2 text-sm font-medium border border-border rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                  >
                    +1h
                  </button>
                </div>
              </div>

              <div>
                <label className="block text-sm text-muted-foreground mb-2">Custom time</label>
                <input
                  type="datetime-local"
                  value={rescheduleTime}
                  onChange={(e) => setRescheduleTime(e.target.value)}
                  className="w-full px-3 py-2 text-sm border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
            </div>

            <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-border">
              <button
                onClick={() => setRescheduleTask(null)}
                className="px-4 py-2 text-sm font-medium border border-border rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => rescheduleMutation.mutate({
                  taskId: rescheduleTask.task_id,
                  nextRun: rescheduleTime
                })}
                disabled={rescheduleMutation.isPending}
                className="px-4 py-2 text-sm font-medium bg-blue-600 hover:bg-blue-700 text-white rounded-lg disabled:opacity-50 transition-colors"
              >
                {rescheduleMutation.isPending ? 'Saving...' : 'Save'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
