import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useEffect } from 'react'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import { Play, CheckCircle, XCircle, Loader, Video, ExternalLink, Layers, Settings, RefreshCw, StopCircle } from 'lucide-react'
import { api } from '../lib/api'
import { useNavigate } from 'react-router-dom'

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

export default function Platforms() {
  useBreadcrumb(breadcrumbConfig['/platforms'])
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [runningPlatforms, setRunningPlatforms] = useState<Set<string>>(new Set())
  const [ytCheckProgress, setYtCheckProgress] = useState<YouTubeCheckProgress>({
    isRunning: false,
    currentChannel: null,
    channelsChecked: 0,
    totalChannels: 0,
    videosFound: 0
  })

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

  const { data: youtubeMonitors, refetch: refetchMonitors } = useQuery({
    queryKey: ['youtube-monitors'],
    queryFn: () => api.getYouTubeMonitors(),
  })

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

  // Load running platforms on mount
  useEffect(() => {
    api.getRunningPlatforms().then(response => {
      if (response.platforms && response.platforms.length > 0) {
        const running = new Set(response.platforms.map(p => p.platform))
        setRunningPlatforms(running)
      }
    }).catch(err => {
      console.error('Failed to load running platforms:', err)
    })
  }, [])

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

    const pollInterval = setInterval(async () => {
      try {
        // Use the new background task API
        const task = await api.getBackgroundTask('youtube_monitor')

        if (task.active) {
          // Get info from extra_data
          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,
          }))
        } else if (!task.active && ytCheckProgress.isRunning) {
          // Check finished
          setYtCheckProgress(prev => ({
            ...prev,
            isRunning: false,
            currentChannel: null,
          }))
          // Refetch monitors to get updated counts
          refetchMonitors()
          queryClient.invalidateQueries({ queryKey: ['download-queue'] })
        }
      } catch (error) {
        console.error('Error polling background task:', error)
      }
    }, 1000)

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

  // Mutation for triggering YouTube check
  const ytCheckMutation = useMutation({
    mutationFn: () => api.checkAllYouTubeChannels(),
    onMutate: () => {
      setYtCheckProgress({
        isRunning: true,
        currentChannel: 'Starting...',
        channelsChecked: 0,
        totalChannels: youtubeMonitors?.channels?.length || 0,
        videosFound: 0
      })
    },
    onSuccess: (data) => {
      // The check runs in background, progress comes from polling
      setYtCheckProgress(prev => ({
        ...prev,
        totalChannels: data?.channels_count || prev.totalChannels
      }))
    },
    onError: () => {
      setYtCheckProgress(prev => ({
        ...prev,
        isRunning: false,
        currentChannel: null
      }))
    }
  })

  const triggerMutation = useMutation({
    mutationFn: ({ platform, username }: { platform: string; username?: string }) =>
      api.triggerDownload(platform, username),
    onMutate: ({ platform }) => {
      setRunningPlatforms((prev) => new Set([...prev, platform]))
    },
  })

  const stopMutation = useMutation({
    mutationFn: (platform: string) => api.stopPlatformDownload(platform),
    onSuccess: (_, platform) => {
      setRunningPlatforms((prev) => {
        const next = new Set(prev)
        next.delete(platform)
        return next
      })
    },
  })

  const getPlatformIcon = (name: string) => {
    const icons: Record<string, string> = {
      instagram_unified: '📸',
      snapchat: '👻',
      tiktok: '🎵',
      forums: '💬',
      coppermine: '🖼️',
      youtube_monitors: '📺',
    }
    return icons[name] || '📥'
  }

  const getPlatformColor = (name: string) => {
    const colors: Record<string, string> = {
      instagram_unified: 'from-purple-500 to-pink-500',
      snapchat: 'from-yellow-500 to-yellow-600',
      tiktok: 'from-pink-500 to-rose-500',
      forums: 'from-indigo-500 to-purple-500',
      coppermine: 'from-amber-500 to-orange-500',
      youtube_monitors: 'from-red-500 to-red-600',
    }
    return colors[name] || 'from-gray-500 to-gray-600'
  }

  const enabledMonitorsCount = youtubeStats?.active || 0
  const totalMonitorsCount = youtubeStats?.total || 0

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader className="w-8 h-8 animate-spin text-blue-500" />
      </div>
    )
  }

  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">
          <Layers className="w-8 h-8 text-cyan-500" />
          Platforms
        </h1>
        <p className="text-slate-600 dark:text-slate-400 mt-1">
          Manage download sources and manually trigger downloads
        </p>
      </div>

      {/* Platforms Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {/* YouTube Monitors Card */}
        <div className="card-glass-hover rounded-xl overflow-hidden">
          <div className={`h-24 bg-gradient-to-br ${getPlatformColor('youtube_monitors')} flex items-center justify-center`}>
            <span className="text-5xl">{getPlatformIcon('youtube_monitors')}</span>
          </div>
          <div className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-foreground">
                YouTube Monitors
              </h3>
              <div className="flex items-center space-x-2">
                {enabledMonitorsCount > 0 ? (
                  <CheckCircle className="w-5 h-5 text-green-500" />
                ) : (
                  <XCircle className="w-5 h-5 text-gray-400" />
                )}
                <span className={`text-xs font-medium ${enabledMonitorsCount > 0 ? 'text-green-600 dark:text-green-400' : 'text-gray-500'}`}>
                  {enabledMonitorsCount > 0 ? `${enabledMonitorsCount} Active` : 'None Active'}
                </span>
              </div>
            </div>

            {/* Progress Display */}
            {ytCheckProgress.isRunning ? (
              <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg border border-red-200 dark:border-red-800">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center space-x-2">
                    <Loader className="w-4 h-4 animate-spin text-red-600 dark:text-red-400" />
                    <span className="text-sm font-medium text-red-700 dark:text-red-300">
                      Checking Channels
                    </span>
                  </div>
                  <span className="text-sm font-bold text-red-700 dark:text-red-300">
                    {ytCheckProgress.channelsChecked} / {ytCheckProgress.totalChannels}
                  </span>
                </div>

                {/* Progress bar */}
                <div className="w-full bg-red-200 dark:bg-red-900 rounded-full h-1.5 sm:h-2 mb-2">
                  <div
                    className="bg-red-600 dark:bg-red-500 h-1.5 sm:h-2 rounded-full transition-all duration-300"
                    style={{
                      width: `${ytCheckProgress.totalChannels > 0
                        ? (ytCheckProgress.channelsChecked / ytCheckProgress.totalChannels) * 100
                        : 0}%`
                    }}
                  />
                </div>

                {/* Current channel status */}
                {ytCheckProgress.currentChannel && (
                  <div className={`text-xs p-2 rounded ${
                    ytCheckProgress.currentChannel.startsWith('Found')
                      ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 font-medium'
                      : 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400'
                  }`}>
                    {ytCheckProgress.currentChannel.startsWith('Found') ? (
                      <div className="flex items-center space-x-1">
                        <CheckCircle className="w-3 h-3 flex-shrink-0" />
                        <span className="truncate">{ytCheckProgress.currentChannel}</span>
                      </div>
                    ) : (
                      <span className="truncate block">{ytCheckProgress.currentChannel}</span>
                    )}
                  </div>
                )}

                {/* Total videos found badge */}
                {ytCheckProgress.videosFound > 0 && (
                  <div className="mt-2 flex items-center justify-center space-x-1.5 py-1.5 bg-green-100 dark:bg-green-900/40 rounded text-green-700 dark:text-green-300">
                    <Video className="w-4 h-4" />
                    <span className="text-sm font-semibold">{ytCheckProgress.videosFound} new videos queued</span>
                  </div>
                )}
              </div>
            ) : (
              <div className="space-y-2 mb-4">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Total Channels:</span>
                  <span className="font-medium text-foreground">{totalMonitorsCount}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Active:</span>
                  <span className="font-medium text-foreground">{enabledMonitorsCount}</span>
                </div>
              </div>
            )}

            {/* Action Buttons */}
            <div className="space-y-2">
              <button
                onClick={() => ytCheckMutation.mutate()}
                disabled={ytCheckProgress.isRunning || enabledMonitorsCount === 0}
                className="w-full flex items-center justify-center space-x-2 px-4 py-2.5 bg-red-600 hover:bg-red-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white rounded-xl transition-colors min-h-[44px]"
              >
                {ytCheckProgress.isRunning ? (
                  <>
                    <Loader className="w-4 h-4 animate-spin" />
                    <span>Checking...</span>
                  </>
                ) : (
                  <>
                    <RefreshCw className="w-4 h-4" />
                    <span>Check All Channels</span>
                  </>
                )}
              </button>
              <button
                onClick={() => navigate('/config?tab=platforms&platform=youtube_monitors')}
                className="w-full flex items-center justify-center space-x-2 px-4 py-2.5 bg-secondary hover:bg-secondary/80 text-foreground rounded-xl transition-colors min-h-[44px]"
              >
                <Settings className="w-4 h-4" />
                <span>Configure</span>
              </button>
            </div>
          </div>
        </div>

        {platforms?.map((platform) => {
          const isRunning = runningPlatforms.has(platform.name)

          return (
            <div
              key={platform.name}
              className="card-glass-hover rounded-xl overflow-hidden"
            >
              {/* Header with gradient */}
              <div
                className={`h-24 bg-gradient-to-br ${getPlatformColor(
                  platform.name
                )} flex items-center justify-center`}
              >
                <span className="text-5xl">{getPlatformIcon(platform.name)}</span>
              </div>

              {/* Content */}
              <div className="p-6">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold text-foreground">
                    {platform.display_name}
                  </h3>
                  {platform.type === 'scheduled' && (
                    <div className="flex items-center space-x-2">
                      {platform.enabled ? (
                        <CheckCircle className="w-5 h-5 text-green-500" />
                      ) : (
                        <XCircle className="w-5 h-5 text-gray-400" />
                      )}
                      <span
                        className={`text-xs font-medium ${
                          platform.enabled
                            ? 'text-green-600 dark:text-green-400'
                            : 'text-gray-500'
                        }`}
                      >
                        {platform.enabled ? 'Enabled' : 'Disabled'}
                      </span>
                    </div>
                  )}
                  {platform.type === 'manual' && (
                    <div className="flex items-center space-x-2">
                      <Video className="w-5 h-5 text-blue-500" />
                      <span className="text-xs font-medium text-blue-600 dark:text-blue-400">
                        Manual Tool
                      </span>
                    </div>
                  )}
                </div>

                {/* Platform Details */}
                <div className="space-y-2 mb-4">
                  {platform.type === 'scheduled' ? (
                    <>
                      {platform.check_interval_hours && (
                        <div className="flex justify-between text-sm">
                          <span className="text-muted-foreground">Check Interval:</span>
                          <span className="font-medium text-foreground">
                            {platform.check_interval_hours}h
                          </span>
                        </div>
                      )}
                      {platform.account_count !== undefined && platform.account_count > 0 && (
                        <div className="flex justify-between text-sm">
                          <span className="text-muted-foreground">Accounts:</span>
                          <span className="font-medium text-foreground">
                            {platform.account_count}
                          </span>
                        </div>
                      )}
                    </>
                  ) : (
                    <>
                      <div className="flex justify-between text-sm">
                        <span className="text-muted-foreground">Type:</span>
                        <span className="font-medium text-foreground">
                          Manual Download Tool
                        </span>
                      </div>
                      {platform.download_count !== undefined && (
                        <div className="flex justify-between text-sm">
                          <span className="text-muted-foreground">Videos Downloaded:</span>
                          <span className="font-medium text-foreground">
                            {platform.download_count}
                          </span>
                        </div>
                      )}
                    </>
                  )}
                </div>

                {/* Actions */}
                <div className="space-y-2">
                  {platform.type === 'scheduled' ? (
                    <>
                      {isRunning ? (
                        <button
                          onClick={() => stopMutation.mutate(platform.name)}
                          disabled={stopMutation.isPending}
                          className="w-full flex items-center justify-center space-x-2 px-4 py-2.5 bg-red-600 hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed text-white rounded-xl transition-colors min-h-[44px]"
                        >
                          <StopCircle className="w-4 h-4" />
                          <span>{stopMutation.isPending ? 'Stopping...' : 'Stop Download'}</span>
                        </button>
                      ) : (
                        <button
                          onClick={() => {
                            if (platform.enabled) {
                              triggerMutation.mutate({ platform: platform.name })
                            }
                          }}
                          disabled={!platform.enabled}
                          className="w-full flex items-center justify-center space-x-2 px-4 py-2.5 bg-slate-800 hover:bg-slate-700 disabled:bg-muted disabled:cursor-not-allowed text-white rounded-xl transition-colors min-h-[44px]"
                        >
                          <Play className="w-4 h-4" />
                          <span>Trigger Download</span>
                        </button>
                      )}
                      <button
                        onClick={() => navigate(
                          platform.name === 'instagram_unified'
                            ? '/config?tab=instagram_unified'
                            : `/config?tab=platforms&platform=${platform.name}`
                        )}
                        className="w-full flex items-center justify-center space-x-2 px-4 py-2.5 bg-secondary hover:bg-secondary/80 text-foreground rounded-xl transition-colors min-h-[44px]"
                      >
                        <Settings className="w-4 h-4" />
                        <span>Configure</span>
                      </button>
                    </>
                  ) : (
                    <button
                      onClick={() => navigate('/videos')}
                      className="w-full flex items-center justify-center space-x-2 px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-xl transition-colors"
                    >
                      <Video className="w-4 h-4" />
                      <span>Open Video Downloader</span>
                      <ExternalLink className="w-3 h-3" />
                    </button>
                  )}
                </div>
              </div>
            </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">
          Manual Triggers
        </h4>
        <p className="text-sm text-blue-800 dark:text-blue-300">
          Click "Trigger Download" to manually start a download for any enabled platform. The
          download will run immediately and follow the configured settings for that platform.
          You can monitor progress in the Logs tab.
        </p>
      </div>
    </div>
  )
}
