import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useEffect, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import { Pause, Play, Shield, ShieldCheck, CheckSquare, Square, Trash2, AlertCircle, RefreshCcw, ArrowUpDown, Video, Plus, X } from 'lucide-react'
import { FilterBar, FilterSection, ActiveFilter } from '../components/FilterPopover'
import { api, YouTubeChannel } from '../lib/api'
import { formatDistanceToNow } from 'date-fns'
import { notificationManager } from '../lib/notificationManager'

interface YouTubeCheckProgress {
  isRunning: boolean
  currentChannel: string | null
  channelsChecked: number
  totalChannels: number
  videosFound: number
}

type StatusFilter = 'all' | 'active' | 'paused_manual' | 'paused_auto' | 'paused_all'
type AlwaysActiveFilter = 'all' | 'always_active' | 'regular'
type SortField = 'name' | 'last_checked' | 'last_video_date' | 'videos_found' | 'created_at'

export default function ChannelMonitors() {
  useBreadcrumb(breadcrumbConfig['/video/channel-monitors'])
  const queryClient = useQueryClient()
  const navigate = useNavigate()
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('active')
  const [alwaysActiveFilter, setAlwaysActiveFilter] = useState<AlwaysActiveFilter>('all')
  const [sortField, setSortField] = useState<SortField>('name')
  const [sortAscending, setSortAscending] = useState(true)
  const [selectedChannels, setSelectedChannels] = useState<number[]>([])
  const [showAddModal, setShowAddModal] = useState(false)
  const [newChannelUrl, setNewChannelUrl] = useState('')
  const [newChannelName, setNewChannelName] = useState('')
  const [ytCheckProgress, setYtCheckProgress] = useState<YouTubeCheckProgress>({
    isRunning: false,
    currentChannel: null,
    channelsChecked: 0,
    totalChannels: 0,
    videosFound: 0
  })

  // Queries
  const { data: statistics } = useQuery({
    queryKey: ['youtube-monitor-stats'],
    queryFn: async () => {
      const response = await api.getYouTubeMonitorStatistics()
      return response.statistics
    }
  })

  // Fetch YouTube monitor settings to get search phrases
  const { data: monitorSettings } = useQuery({
    queryKey: ['youtube-monitor-settings'],
    queryFn: async () => {
      const response = await api.getYouTubeMonitors()
      return response.settings
    }
  })

  // Get the first search phrase to use in channel URLs
  const searchPhrase = monitorSettings?.phrases?.[0] || 'Eva Longoria'

  // Fetch channels with server-side filtering
  const { data: channelsData, isLoading } = useQuery({
    queryKey: ['youtube-monitors', statusFilter, alwaysActiveFilter, searchTerm, sortField, sortAscending],
    queryFn: async () => {
      const response = await api.getYouTubeChannelsFiltered({
        status: statusFilter !== 'all' ? statusFilter : undefined,
        always_active: alwaysActiveFilter !== 'all' ? alwaysActiveFilter : undefined,
        search: searchTerm || undefined,
        sort_field: sortField,
        sort_ascending: sortAscending
      })
      return response
    }
  })

  const filteredChannels = channelsData?.channels || []
  const totalChannels = channelsData?.total || 0

  // Check for running task on mount
  useEffect(() => {
    const checkRunningTask = async () => {
      try {
        const task = await api.getBackgroundTask('youtube_monitor')
        if (task.active) {
          setYtCheckProgress({
            isRunning: true,
            currentChannel: task.detailed_status || task.extra_data?.current_channel || 'Checking...',
            channelsChecked: task.progress?.current || 0,
            totalChannels: task.progress?.total || 0,
            videosFound: task.extra_data?.videos_found || 0
          })
        }
      } catch (error) {
        console.error('Error checking for running task:', error)
      }
    }
    checkRunningTask()
  }, [])

  // Poll for YouTube monitor background task status
  useEffect(() => {
    if (!ytCheckProgress.isRunning) return

    let pollCount = 0

    const pollInterval = setInterval(async () => {
      try {
        const task = await api.getBackgroundTask('youtube_monitor')

        if (task.active) {
          const videosFound = task.extra_data?.videos_found || 0
          const currentChannel = task.detailed_status || task.extra_data?.current_channel || 'Checking...'

          setYtCheckProgress(prev => ({
            ...prev,
            currentChannel: currentChannel,
            channelsChecked: task.progress?.current || prev.channelsChecked,
            totalChannels: task.progress?.total || prev.totalChannels,
            videosFound: videosFound,
          }))

          // Refresh channel data every 3 seconds during scan for real-time updates
          pollCount++
          if (pollCount % 3 === 0) {
            queryClient.invalidateQueries({ queryKey: ['youtube-monitors'] })
            queryClient.invalidateQueries({ queryKey: ['youtube-monitor-stats'] })
          }
        } else if (!task.active && ytCheckProgress.isRunning) {
          setYtCheckProgress(prev => ({
            ...prev,
            isRunning: false,
            currentChannel: null,
          }))
          queryClient.invalidateQueries({ queryKey: ['youtube-monitors'] })
          queryClient.invalidateQueries({ queryKey: ['youtube-monitor-stats'] })
        }
      } catch (error) {
        console.error('Error polling background task:', error)
      }
    }, 1000)

    return () => clearInterval(pollInterval)
  }, [ytCheckProgress.isRunning, queryClient])

  // Mutations
  const checkAllMutation = useMutation({
    mutationFn: () => api.checkAllYouTubeChannels(),
    onMutate: () => {
      setYtCheckProgress({
        isRunning: true,
        currentChannel: 'Starting...',
        channelsChecked: 0,
        totalChannels: filteredChannels?.length || 0,
        videosFound: 0
      })
    },
    onSuccess: (data) => {
      setYtCheckProgress(prev => ({
        ...prev,
        totalChannels: data?.channels_count || prev.totalChannels
      }))
    },
    onError: () => {
      setYtCheckProgress(prev => ({
        ...prev,
        isRunning: false,
        currentChannel: null
      }))
    }
  })

  const pauseMutation = useMutation({
    mutationFn: (id: number) => api.pauseYouTubeChannel(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['youtube-monitors'] })
      queryClient.invalidateQueries({ queryKey: ['youtube-monitor-stats'] })
    }
  })

  const resumeMutation = useMutation({
    mutationFn: (id: number) => api.resumeYouTubeChannel(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['youtube-monitors'] })
      queryClient.invalidateQueries({ queryKey: ['youtube-monitor-stats'] })
    }
  })

  const deleteMutation = useMutation({
    mutationFn: (id: number) => api.deleteYouTubeChannel(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['youtube-monitors'] })
      queryClient.invalidateQueries({ queryKey: ['youtube-monitor-stats'] })
    }
  })

  const toggleAlwaysActiveMutation = useMutation({
    mutationFn: ({ id, value }: { id: number, value: boolean }) =>
      api.toggleYouTubeChannelAlwaysActive(id, value),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['youtube-monitors'] })
      queryClient.invalidateQueries({ queryKey: ['youtube-monitor-stats'] })
    }
  })

  const checkChannelMutation = useMutation({
    mutationFn: ({ id }: { id: number, channelName: string }) => {
      return api.checkYouTubeChannel(id)
    },
    onSuccess: (_, variables) => {
      notificationManager.syncStarted(`${variables.channelName}`)
      queryClient.invalidateQueries({ queryKey: ['youtube-monitors'] })
      queryClient.invalidateQueries({ queryKey: ['youtube-monitor-stats'] })
    },
    onError: (err: unknown, variables) => {
      notificationManager.apiError('Check Failed', err, `Failed to check ${variables.channelName}`)
    }
  })

  const checkSelectedMutation = useMutation({
    mutationFn: (channelIds: number[]) => {
      return api.checkSelectedYouTubeChannels(channelIds)
    },
    onSuccess: (_, channelIds) => {
      notificationManager.syncStarted(`${channelIds.length} channel(s)`)
      queryClient.invalidateQueries({ queryKey: ['youtube-monitors'] })
      queryClient.invalidateQueries({ queryKey: ['youtube-monitor-stats'] })
      setSelectedChannels([])
    },
    onError: (err: unknown) => {
      notificationManager.syncError('Channels', err)
    }
  })

  const addChannelMutation = useMutation({
    mutationFn: (data: { channel_url: string, channel_name?: string, enabled?: boolean }) =>
      api.addYouTubeChannel(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['youtube-monitors'] })
      queryClient.invalidateQueries({ queryKey: ['youtube-monitor-stats'] })
      setShowAddModal(false)
      setNewChannelUrl('')
      setNewChannelName('')
    },
    onError: (error: any) => {
      const errorMessage = error?.response?.data?.detail || error?.message || 'Failed to add channel'
      alert(errorMessage)
    }
  })

  const handleAddChannel = () => {
    if (!newChannelUrl.trim()) return
    addChannelMutation.mutate({
      channel_url: newChannelUrl,
      channel_name: newChannelName || undefined,
      enabled: true
    })
  }

  // Bulk actions
  const handleBulkPause = async () => {
    if (!confirm(`Pause ${selectedChannels.length} selected channel(s)?`)) return
    await Promise.all(selectedChannels.map(id => pauseMutation.mutateAsync(id)))
    setSelectedChannels([])
  }

  const handleBulkResume = async () => {
    if (!confirm(`Resume ${selectedChannels.length} selected channel(s)?`)) return
    await Promise.all(selectedChannels.map(id => resumeMutation.mutateAsync(id)))
    setSelectedChannels([])
  }

  const handleBulkDelete = async () => {
    if (!confirm(`Delete ${selectedChannels.length} selected channel(s)? This cannot be undone!`)) return
    await Promise.all(selectedChannels.map(id => deleteMutation.mutateAsync(id)))
    setSelectedChannels([])
  }

  const handleBulkToggleAlwaysActive = async (value: boolean) => {
    if (!confirm(`${value ? 'Enable' : 'Disable'} "Always Active" for ${selectedChannels.length} selected channel(s)?`)) return
    await Promise.all(
      selectedChannels.map(id => toggleAlwaysActiveMutation.mutateAsync({ id, value }))
    )
    setSelectedChannels([])
  }

  const handleBulkCheck = async () => {
    if (!confirm(`Check ${selectedChannels.length} selected channel(s) for new videos?`)) return
    await checkSelectedMutation.mutateAsync(selectedChannels)
  }

  const handleSelectAll = () => {
    if (selectedChannels.length === filteredChannels?.length) {
      setSelectedChannels([])
    } else {
      setSelectedChannels(filteredChannels?.map((c: YouTubeChannel) => c.id) || [])
    }
  }

  const handleToggleChannel = (id: number) => {
    setSelectedChannels(prev =>
      prev.includes(id) ? prev.filter(cid => cid !== id) : [...prev, id]
    )
  }

  const formatDate = (date: string | null | undefined) => {
    if (!date) return 'Never'
    try {
      // Handle YYYYMMDD format from yt-dlp (e.g., "20200814")
      if (date.length === 8 && /^\d{8}$/.test(date)) {
        const year = date.substring(0, 4)
        const month = date.substring(4, 6)
        const day = date.substring(6, 8)
        const parsedDate = new Date(`${year}-${month}-${day}`)
        return formatDistanceToNow(parsedDate, { addSuffix: true })
      }
      // Handle ISO format
      return formatDistanceToNow(new Date(date), { addSuffix: true })
    } catch {
      return 'Unknown'
    }
  }

  const getStatusBadge = (channel: YouTubeChannel) => {
    if (channel.status === 'active') {
      return <span className="px-2 py-1 text-xs font-semibold rounded bg-green-500/20 text-green-400">🟢 Active</span>
    }
    if (channel.status === 'paused_manual') {
      return <span className="px-2 py-1 text-xs font-semibold rounded bg-yellow-500/20 text-yellow-400">⏸️ Paused (Manual)</span>
    }
    if (channel.status === 'paused_auto') {
      return <span className="px-2 py-1 text-xs font-semibold rounded bg-orange-500/20 text-orange-400">⏸️ Paused (Auto)</span>
    }
    return null
  }

  const toggleSortDirection = () => {
    setSortAscending(!sortAscending)
  }

  // Filter sections for FilterBar
  const filterSections: FilterSection[] = useMemo(() => [
    {
      id: 'status',
      label: 'Status',
      type: 'select',
      options: [
        { value: 'all', label: 'All Status' },
        { value: 'active', label: 'Active' },
        { value: 'paused_manual', label: 'Paused (Manual)' },
        { value: 'paused_auto', label: 'Paused (Auto)' },
        { value: 'paused_all', label: 'All Paused' },
      ],
      value: statusFilter,
      onChange: (v) => setStatusFilter(v as StatusFilter),
    },
    {
      id: 'alwaysActive',
      label: 'Channel Type',
      type: 'select',
      options: [
        { value: 'all', label: 'All Channels' },
        { value: 'always_active', label: 'Protected' },
        { value: 'regular', label: 'Regular' },
      ],
      value: alwaysActiveFilter,
      onChange: (v) => setAlwaysActiveFilter(v as AlwaysActiveFilter),
    },
  ], [statusFilter, alwaysActiveFilter])

  // Active filters for FilterBar
  const activeFilters: ActiveFilter[] = useMemo(() => {
    const filters: ActiveFilter[] = []
    if (statusFilter !== 'all') {
      const statusLabels: Record<StatusFilter, string> = {
        all: 'All',
        active: 'Active',
        paused_manual: 'Paused (Manual)',
        paused_auto: 'Paused (Auto)',
        paused_all: 'All Paused',
      }
      filters.push({
        id: 'status',
        label: 'Status',
        value: statusFilter,
        displayValue: statusLabels[statusFilter],
        onRemove: () => setStatusFilter('all'),
      })
    }
    if (alwaysActiveFilter !== 'all') {
      filters.push({
        id: 'alwaysActive',
        label: 'Type',
        value: alwaysActiveFilter,
        displayValue: alwaysActiveFilter === 'always_active' ? 'Protected' : 'Regular',
        onRemove: () => setAlwaysActiveFilter('all'),
      })
    }
    if (searchTerm) {
      filters.push({
        id: 'search',
        label: 'Search',
        value: searchTerm,
        displayValue: `"${searchTerm}"`,
        onRemove: () => setSearchTerm(''),
      })
    }
    return filters
  }, [statusFilter, alwaysActiveFilter, searchTerm])

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4">
        <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-2 sm:gap-3">
              <Video className="w-6 h-6 sm:w-8 sm:h-8 text-indigo-500" />
              YouTube Channel Monitors
            </h1>
            <p className="text-sm sm:text-base text-slate-600 dark:text-slate-400 mt-1">
              Manage monitored YouTube channels with auto-pause for inactive channels
            </p>
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowAddModal(true)}
              className="flex items-center justify-center gap-2 px-3 sm:px-4 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors min-h-[44px]"
            >
              <Plus className="w-4 h-4" />
              <span>Add Channel</span>
            </button>
            <button
              onClick={() => checkAllMutation.mutate()}
              disabled={checkAllMutation.isPending || ytCheckProgress.isRunning || !filteredChannels?.length}
              className="flex items-center justify-center gap-2 px-3 sm:px-4 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed min-h-[44px]"
            >
              <RefreshCcw className={`w-4 h-4 ${checkAllMutation.isPending || ytCheckProgress.isRunning ? 'animate-spin' : ''}`} />
              <span>Check All</span>
            </button>
          </div>
        </div>
      </div>

      {/* Running Status Banner */}
      {ytCheckProgress.isRunning && (
        <div className="card-glass rounded-xl bg-gradient-to-r from-red-500/10 to-rose-500/10 border border-red-500/30 p-4 glow-border">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="relative">
                <Video className="w-5 h-5 text-red-600 dark:text-red-400" />
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full animate-pulse"></span>
              </div>
              <h3 className="text-sm font-semibold text-red-900 dark:text-red-100">
                YouTube Channel Monitor
              </h3>
            </div>
            <span className="text-xs text-red-600 dark:text-red-400">
              {ytCheckProgress.totalChannels || 0} channels
            </span>
          </div>

          {ytCheckProgress.currentChannel && (
            <div className="mb-3 px-3 py-2 bg-red-100 dark:bg-red-900/30 rounded-lg">
              <div className="flex items-center gap-2 text-sm text-red-800 dark:text-red-200">
                <span className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></span>
                <span className="truncate">{ytCheckProgress.currentChannel}</span>
              </div>
            </div>
          )}

          <div className="mb-2">
            <div className="flex justify-between text-xs text-red-700 dark:text-red-300 mb-1">
              <span>Progress</span>
              <span>{ytCheckProgress.channelsChecked || 0}/{ytCheckProgress.totalChannels || 0}</span>
            </div>
            <div className="w-full bg-red-200 dark:bg-red-800 rounded-full h-1.5 sm:h-2">
              <div
                className="bg-red-600 dark:bg-red-400 h-1.5 sm:h-2 rounded-full transition-all duration-300 progress-animated"
                style={{ width: `${ytCheckProgress.totalChannels > 0 ? (ytCheckProgress.channelsChecked / ytCheckProgress.totalChannels * 100) : 0}%` }}
              ></div>
            </div>
          </div>

          {(ytCheckProgress.videosFound ?? 0) > 0 && (
            <div className="flex items-center gap-1.5 text-xs text-green-700 dark:text-green-300 font-medium">
              <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
              <span>Found {ytCheckProgress.videosFound} matching video{ytCheckProgress.videosFound !== 1 ? 's' : ''}</span>
            </div>
          )}
        </div>
      )}

      {/* Statistics Dashboard */}
      {statistics && (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2 sm:gap-4">
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-blue shadow-blue-glow">
            <div className="text-lg sm:text-2xl font-bold text-foreground animate-count-up">{statistics.total}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Total</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-green shadow-green-glow">
            <div className="text-lg sm:text-2xl font-bold text-emerald-600 dark:text-emerald-400 animate-count-up">{statistics.active}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Active</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-orange shadow-orange-glow">
            <div className="text-lg sm:text-2xl font-bold text-amber-600 dark:text-amber-400 animate-count-up">{statistics.paused_manual}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Paused (Manual)</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-red shadow-red-glow">
            <div className="text-lg sm:text-2xl font-bold text-red-600 dark:text-red-400 animate-count-up">{statistics.paused_auto}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Paused (Auto)</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-cyan">
            <div className="text-lg sm:text-2xl font-bold text-cyan-600 dark:text-cyan-400 animate-count-up">{statistics.always_active_count}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Protected</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border bg-gradient-to-br from-purple-500/10 via-purple-500/5 to-indigo-500/10 border-purple-500/20">
            <div className="text-lg sm:text-2xl font-bold text-purple-600 dark:text-purple-400 animate-count-up">{statistics.total_videos}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Videos</div>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="card-glass-hover rounded-xl p-4 relative z-30">
        <FilterBar
          searchValue={searchTerm}
          onSearchChange={setSearchTerm}
          searchPlaceholder="Search channels..."
          filterSections={filterSections}
          activeFilters={activeFilters}
          onClearAll={() => {
            setStatusFilter('all')
            setAlwaysActiveFilter('all')
            setSortField('name')
            setSortAscending(true)
            setSearchTerm('')
          }}
          totalCount={filteredChannels?.length || 0}
          countLabel={`of ${totalChannels} channels`}
        >
          {/* Sort Controls */}
          <div className="flex gap-2 mt-3">
            <select
              value={sortField}
              onChange={(e) => {
                const newField = e.target.value as SortField
                setSortField(newField)
                if (newField !== 'name') {
                  setSortAscending(false)
                } else {
                  setSortAscending(true)
                }
              }}
              className="flex-1 px-4 py-2 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="name">Sort by: Name</option>
              <option value="last_checked">Sort by: Last Checked</option>
              <option value="last_video_date">Sort by: Last Video</option>
              <option value="videos_found">Sort by: Matched Videos</option>
              <option value="created_at">Sort by: Created</option>
            </select>
            <button
              onClick={toggleSortDirection}
              className={`px-3 py-2 rounded-lg border ${
                !sortAscending
                  ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                  : 'border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800'
              } text-slate-900 dark:text-slate-100 hover:border-blue-400 transition-colors`}
              title={sortAscending ? 'Ascending' : 'Descending'}
            >
              <ArrowUpDown className={`w-4 h-4 ${sortAscending ? '' : 'rotate-180'} transition-transform`} />
            </button>
          </div>
        </FilterBar>
      </div>

      {/* Bulk Actions (shown when items selected) */}
      {selectedChannels.length > 0 && (
        <div className="card-glass-hover rounded-xl p-3 border border-border">
          <div className="flex flex-wrap items-center gap-3">
            <button
              onClick={handleSelectAll}
              className="text-muted-foreground hover:text-foreground transition-colors touch-manipulation"
              title={selectedChannels.length === filteredChannels?.length ? 'Deselect All' : 'Select All'}
            >
              {selectedChannels.length === filteredChannels?.length ? (
                <CheckSquare className="w-5 h-5" />
              ) : (
                <Square className="w-5 h-5" />
              )}
            </button>
            <span className="text-sm font-medium text-foreground">
              {selectedChannels.length} selected
            </span>
            <div className="flex-1"></div>
            <button
              onClick={handleBulkPause}
              className="px-3 py-2 bg-yellow-600 hover:bg-yellow-700 rounded-lg text-sm font-medium flex items-center gap-1.5 transition-colors min-h-[44px]"
            >
              <Pause className="w-4 h-4" />
              <span className="hidden sm:inline">Pause</span>
            </button>
            <button
              onClick={handleBulkResume}
              className="px-3 py-2 bg-green-600 hover:bg-green-700 rounded-lg text-sm font-medium flex items-center gap-1.5 transition-colors min-h-[44px]"
            >
              <Play className="w-4 h-4" />
              <span className="hidden sm:inline">Resume</span>
            </button>
            <button
              onClick={handleBulkCheck}
              disabled={checkSelectedMutation.isPending}
              className="px-3 py-2 bg-indigo-600 hover:bg-indigo-700 rounded-lg text-sm font-medium flex items-center gap-1.5 transition-colors min-h-[44px] disabled:opacity-50 disabled:cursor-not-allowed"
              title="Check selected channels for new videos"
            >
              <RefreshCcw className={`w-4 h-4 ${checkSelectedMutation.isPending ? 'animate-spin' : ''}`} />
              <span className="hidden sm:inline">{checkSelectedMutation.isPending ? 'Checking...' : 'Check Now'}</span>
            </button>
            <button
              onClick={() => handleBulkToggleAlwaysActive(true)}
              className="px-3 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg text-sm font-medium flex items-center gap-1.5 transition-colors min-h-[44px]"
            >
              <ShieldCheck className="w-4 h-4" />
              <span className="hidden sm:inline">Protect</span>
            </button>
            <button
              onClick={() => handleBulkToggleAlwaysActive(false)}
              className="px-3 py-2 bg-slate-600 hover:bg-slate-700 rounded-lg text-sm font-medium flex items-center gap-1.5 transition-colors min-h-[44px]"
            >
              <Shield className="w-4 h-4" />
              <span className="hidden sm:inline">Unprotect</span>
            </button>
            <button
              onClick={handleBulkDelete}
              className="px-3 py-2 bg-red-600 hover:bg-red-700 rounded-lg text-sm font-medium flex items-center gap-1.5 transition-colors min-h-[44px]"
            >
              <Trash2 className="w-4 h-4" />
              <span className="hidden sm:inline">Delete</span>
            </button>
          </div>
        </div>
      )}

      {/* Channel List */}
      <div className="card-glass rounded-xl overflow-hidden">
        {isLoading ? (
          <div className="flex items-center justify-center p-12">
            <RefreshCcw className="w-8 h-8 animate-spin text-indigo-500" />
          </div>
        ) : filteredChannels && filteredChannels.length === 0 ? (
          <div className="text-center p-12">
            <Video className="w-12 h-12 mx-auto text-slate-400 mb-4" />
            <h3 className="text-lg font-medium mb-2">No channels found</h3>
            <p className="text-slate-600 dark:text-slate-400">
              No channels match your current filters
            </p>
          </div>
        ) : (
          <div className="divide-y divide-slate-200 dark:divide-slate-700">
            {filteredChannels.map((channel: YouTubeChannel) => (
            <div
              key={channel.id}
              className="p-3 sm:p-4 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"
            >
              <div className="flex items-start gap-3 sm:gap-4">
                {/* Checkbox */}
                <button
                  onClick={() => handleToggleChannel(channel.id)}
                  className="mt-1 text-muted-foreground hover:text-foreground transition-colors touch-manipulation"
                >
                  {selectedChannels.includes(channel.id) ? (
                    <CheckSquare className="w-5 h-5 text-indigo-500" />
                  ) : (
                    <Square className="w-5 h-5" />
                  )}
                </button>

                {/* Channel Info */}
                <div className="flex-1 min-w-0">
                  {/* Header Row */}
                  <div className="flex items-start gap-2 mb-2">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1 flex-wrap">
                        <h3
                          className={`text-base sm:text-lg font-semibold truncate transition-colors touch-manipulation ${
                            (channel.total_videos_found || 0) > 0
                              ? 'cursor-pointer hover:text-blue-400'
                              : 'cursor-default opacity-60'
                          }`}
                          onClick={() => {
                            if ((channel.total_videos_found || 0) > 0) {
                              navigate(`/celebrities?channel_name=${encodeURIComponent(channel.channel_name || channel.channel_url)}&status=all&watched=`)
                            }
                          }}
                          title={(channel.total_videos_found || 0) > 0 ? "View in Internet Discovery" : "No videos found yet"}
                        >
                          {channel.channel_name || channel.channel_url.replace('https://www.youtube.com/@', '@')}
                        </h3>
                        {getStatusBadge(channel)}
                        {channel.always_active === 1 && (
                          <span className="px-2 py-0.5 text-xs font-semibold rounded bg-blue-500/20 text-blue-400 border border-blue-400/30 whitespace-nowrap">
                            <ShieldCheck className="w-3 h-3 inline mr-1" />
                            Protected
                          </span>
                        )}
                      </div>
                      <a
                        href={`${channel.channel_url}/search?query=${encodeURIComponent(searchPhrase)}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-xs text-slate-500 dark:text-slate-400 hover:text-blue-400 truncate block touch-manipulation"
                        title={`${channel.channel_url}/search?query=${searchPhrase}`}
                      >
                        {channel.channel_url.replace('https://www.youtube.com/', '')}
                      </a>
                    </div>
                  </div>

                  {/* Stats Row */}
                  <div className="flex flex-wrap gap-x-4 sm:gap-x-6 gap-y-1 text-xs text-slate-600 dark:text-slate-400 mb-2">
                    <div className="flex items-center gap-1.5">
                      <span className="font-medium text-slate-500 dark:text-slate-500">Last Check:</span>
                      <span>{formatDate(channel.last_check_date)}</span>
                    </div>
                    <div className="flex items-center gap-1.5">
                      <span className="font-medium text-slate-500 dark:text-slate-500">Last Video:</span>
                      <span>{formatDate(channel.last_video_date)}</span>
                    </div>
                    <div className="flex items-center gap-1.5">
                      <span className="font-medium text-slate-500 dark:text-slate-500">Videos:</span>
                      <span className="font-semibold text-slate-700 dark:text-slate-300">{channel.total_videos_found || 0}</span>
                    </div>
                    <div className="flex items-center gap-1.5">
                      <span className="font-medium text-slate-500 dark:text-slate-500">Added:</span>
                      <span>{formatDate(channel.created_at)}</span>
                    </div>
                  </div>

                  {/* Pause Reason */}
                  {channel.paused_reason && (
                    <div className="text-xs bg-yellow-500/10 border border-yellow-500/30 text-yellow-600 dark:text-yellow-400 px-3 py-1.5 rounded mb-2 flex items-start gap-2">
                      <AlertCircle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
                      <span>{channel.paused_reason}</span>
                    </div>
                  )}

                  {/* Action Buttons - Mobile Only (Icon Only) */}
                  <div className="flex gap-2 lg:hidden">
                    {channel.status === 'active' ? (
                      <button
                        onClick={() => pauseMutation.mutate(channel.id)}
                        className="p-2.5 bg-yellow-600 hover:bg-yellow-700 active:bg-yellow-800 rounded transition-colors touch-manipulation"
                        title="Pause"
                        aria-label="Pause channel"
                      >
                        <Pause className="w-4 h-4" />
                      </button>
                    ) : (
                      <button
                        onClick={() => resumeMutation.mutate(channel.id)}
                        className="p-2.5 bg-green-600 hover:bg-green-700 active:bg-green-800 rounded transition-colors touch-manipulation"
                        title="Resume"
                        aria-label="Resume channel"
                      >
                        <Play className="w-4 h-4" />
                      </button>
                    )}
                    <button
                      onClick={() => checkChannelMutation.mutate({ id: channel.id, channelName: channel.channel_name || 'Unknown Channel' })}
                      disabled={checkChannelMutation.isPending}
                      className="p-2.5 bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 rounded transition-colors touch-manipulation disabled:opacity-50 disabled:cursor-not-allowed"
                      title="Check for new videos"
                      aria-label="Check channel for new videos"
                    >
                      <RefreshCcw className={`w-4 h-4 ${checkChannelMutation.isPending ? 'animate-spin' : ''}`} />
                    </button>
                    <button
                      onClick={() => toggleAlwaysActiveMutation.mutate({ id: channel.id, value: !channel.always_active })}
                      className={`p-2.5 rounded transition-colors touch-manipulation ${
                        channel.always_active
                          ? 'bg-slate-600 hover:bg-slate-700 active:bg-slate-800'
                          : 'bg-blue-600 hover:bg-blue-700 active:bg-blue-800'
                      }`}
                      title={channel.always_active ? 'Unprotect' : 'Protect'}
                      aria-label={channel.always_active ? 'Unprotect channel' : 'Protect channel'}
                    >
                      {channel.always_active ? (
                        <Shield className="w-4 h-4" />
                      ) : (
                        <ShieldCheck className="w-4 h-4" />
                      )}
                    </button>
                    <button
                      onClick={() => {
                        if (confirm(`Delete channel "${channel.channel_name || channel.channel_url}"? This cannot be undone!`)) {
                          deleteMutation.mutate(channel.id)
                        }
                      }}
                      className="p-2.5 bg-red-600 hover:bg-red-700 active:bg-red-800 rounded transition-colors touch-manipulation"
                      title="Delete"
                      aria-label="Delete channel"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>

                {/* Action Buttons - Desktop Only (Right Side) */}
                <div className="hidden lg:flex gap-2 flex-shrink-0 items-start">
                  {channel.status === 'active' ? (
                    <button
                      onClick={() => pauseMutation.mutate(channel.id)}
                      className="px-3 py-1.5 bg-yellow-600 hover:bg-yellow-700 rounded text-xs font-medium flex items-center gap-1.5 transition-colors whitespace-nowrap"
                    >
                      <Pause className="w-3.5 h-3.5" />
                      Pause
                    </button>
                  ) : (
                    <button
                      onClick={() => resumeMutation.mutate(channel.id)}
                      className="px-3 py-1.5 bg-green-600 hover:bg-green-700 rounded text-xs font-medium flex items-center gap-1.5 transition-colors whitespace-nowrap"
                    >
                      <Play className="w-3.5 h-3.5" />
                      Resume
                    </button>
                  )}
                  <button
                    onClick={() => checkChannelMutation.mutate({ id: channel.id, channelName: channel.channel_name || 'Unknown Channel' })}
                    disabled={checkChannelMutation.isPending}
                    className="px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 rounded text-xs font-medium flex items-center gap-1.5 transition-colors whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
                    title="Check this channel for new videos"
                  >
                    <RefreshCcw className={`w-3.5 h-3.5 ${checkChannelMutation.isPending ? 'animate-spin' : ''}`} />
                    {checkChannelMutation.isPending ? 'Checking...' : 'Check Now'}
                  </button>
                  <button
                    onClick={() => toggleAlwaysActiveMutation.mutate({ id: channel.id, value: !channel.always_active })}
                    className={`px-3 py-1.5 rounded text-xs font-medium flex items-center gap-1.5 transition-colors whitespace-nowrap ${
                      channel.always_active
                        ? 'bg-slate-600 hover:bg-slate-700'
                        : 'bg-blue-600 hover:bg-blue-700'
                    }`}
                  >
                    {channel.always_active ? (
                      <>
                        <Shield className="w-3.5 h-3.5" />
                        Unprotect
                      </>
                    ) : (
                      <>
                        <ShieldCheck className="w-3.5 h-3.5" />
                        Protect
                      </>
                    )}
                  </button>
                  <button
                    onClick={() => {
                      if (confirm(`Delete channel "${channel.channel_name || channel.channel_url}"? This cannot be undone!`)) {
                        deleteMutation.mutate(channel.id)
                      }
                    }}
                    className="px-3 py-1.5 bg-red-600 hover:bg-red-700 rounded text-xs font-medium flex items-center gap-1.5 transition-colors whitespace-nowrap"
                  >
                    <Trash2 className="w-3.5 h-3.5" />
                    Delete
                  </button>
                </div>
              </div>
            </div>
            ))}
          </div>
        )}
      </div>

      {/* Add Channel Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-card border border-border rounded-xl shadow-2xl max-w-md w-full p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
                Add YouTube Channel
              </h3>
              <button
                onClick={() => {
                  setShowAddModal(false)
                  setNewChannelUrl('')
                  setNewChannelName('')
                }}
                className="text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200"
              >
                <X className="w-6 h-6" />
              </button>
            </div>
            <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
              Add a new YouTube channel to monitor for matching videos. The channel will be automatically checked based on your configured schedule.
            </p>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Channel URL <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={newChannelUrl}
                  onChange={(e) => setNewChannelUrl(e.target.value)}
                  placeholder="https://www.youtube.com/@channelname or https://www.youtube.com/channel/UC..."
                  className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground placeholder-muted-foreground"
                  autoFocus
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && newChannelUrl.trim()) {
                      handleAddChannel()
                    }
                  }}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  Channel Name (optional)
                </label>
                <input
                  type="text"
                  value={newChannelName}
                  onChange={(e) => setNewChannelName(e.target.value)}
                  placeholder="Optional custom name for this channel"
                  className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground placeholder-muted-foreground"
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && newChannelUrl.trim()) {
                      handleAddChannel()
                    }
                  }}
                />
                <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">
                  If not provided, the channel name will be fetched automatically
                </p>
              </div>
            </div>
            <div className="flex justify-end space-x-2 mt-6">
              <button
                onClick={() => {
                  setShowAddModal(false)
                  setNewChannelUrl('')
                  setNewChannelName('')
                }}
                className="px-4 py-2.5 text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors min-h-[44px]"
              >
                Cancel
              </button>
              <button
                onClick={handleAddChannel}
                disabled={!newChannelUrl.trim() || addChannelMutation.isPending}
                className="px-4 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors min-h-[44px]"
              >
                {addChannelMutation.isPending ? 'Adding...' : 'Add Channel'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
