import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useBreadcrumb } from '../../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../../config/breadcrumbConfig'
import {
  ListOrdered,
  Download,
  AlertCircle,
  Trash2,
  StopCircle,
  PlayCircle,
  RefreshCw,
  Check,
  X,
  Clock,
  Loader2,
  ChevronDown,
  ChevronRight,
  ToggleLeft,
  ToggleRight,
} from 'lucide-react'
import { api, getErrorMessage, PaidContentAttachment, PaidContentActiveTask } from '../../lib/api'
import { notificationManager } from '../../lib/notificationManager'
import { formatBytes } from '../../lib/utils'

type QueueItem = PaidContentAttachment & {
  username?: string
  platform?: string
  post_title?: string
  auto_requeue?: number
}

// Use shared types from api.ts
type ActiveTask = PaidContentActiveTask

function ActiveTaskCard({ task }: { task: ActiveTask }) {
  const getPhaseIcon = () => {
    switch (task.phase) {
      case 'fetching':
        return <RefreshCw className="w-4 h-4 animate-spin text-blue-500" />
      case 'processing':
        return <Loader2 className="w-4 h-4 animate-spin text-amber-500" />
      case 'downloading':
        return <Download className="w-4 h-4 animate-pulse text-emerald-500" />
      default:
        return <Loader2 className="w-4 h-4 animate-spin text-primary" />
    }
  }

  const getPhaseLabel = () => {
    switch (task.phase) {
      case 'fetching':
        return 'Fetching posts'
      case 'processing':
        return 'Processing'
      case 'downloading':
        return 'Downloading'
      default:
        return 'Working'
    }
  }

  const progressPercent = task.total_files
    ? Math.round(((task.downloaded || 0) / task.total_files) * 100)
    : 0

  return (
    <div className="p-4 bg-secondary/50 rounded-lg border border-border">
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center space-x-3">
          <div className="p-2 rounded-lg bg-primary/10">
            {getPhaseIcon()}
          </div>
          <div>
            <p className="font-semibold text-foreground">{task.username}</p>
            <p className="text-xs text-muted-foreground capitalize">
              {task.platform} • {task.service}
            </p>
          </div>
        </div>
        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-primary/10 text-primary">
          {getPhaseLabel()}
        </span>
      </div>

      <p className="text-sm text-foreground mb-2">{task.status}</p>

      {task.phase === 'downloading' && task.total_files && (
        <div className="bg-background/50 rounded-lg p-3 space-y-2">
          <div className="flex justify-between items-center mb-1">
            <span className="text-xs font-medium text-foreground">Progress</span>
            <span className="text-xs text-muted-foreground">
              {task.downloaded || 0} / {task.total_files} ({progressPercent}%)
            </span>
          </div>
          <div className="h-2 bg-secondary rounded-full overflow-hidden">
            <div
              className="h-full bg-gradient-to-r from-primary to-emerald-500 rounded-full transition-all duration-300"
              style={{ width: `${progressPercent}%` }}
            />
          </div>

          {/* Active Downloads */}
          {task.active_downloads && task.active_downloads.length > 0 && (
            <div className="pt-2 border-t border-border/50 space-y-1.5">
              <span className="text-xs text-muted-foreground">
                Downloading ({task.active_count || task.active_downloads.length}):
              </span>
              {task.active_downloads.slice(0, 2).map((dl, idx) => (
                <div key={idx} className="text-xs">
                  <div className="flex justify-between items-center mb-0.5">
                    <span className="text-foreground truncate flex-1 mr-2" title={dl.name}>
                      {dl.name.length > 30 ? dl.name.slice(0, 30) + '...' : dl.name}
                    </span>
                    <span className="text-muted-foreground whitespace-nowrap">
                      {formatBytes(dl.progress)}{dl.size ? ` / ${formatBytes(dl.size)}` : ''}
                    </span>
                  </div>
                  {dl.size && (
                    <div className="h-1 bg-secondary rounded-full overflow-hidden">
                      <div
                        className="h-full bg-blue-500 rounded-full transition-all duration-200"
                        style={{ width: `${dl.size > 0 ? Math.min(100, (dl.progress / dl.size) * 100) : 0}%` }}
                      />
                    </div>
                  )}
                </div>
              ))}
              {task.active_downloads.length > 2 && (
                <span className="text-xs text-muted-foreground">
                  +{task.active_downloads.length - 2} more...
                </span>
              )}
            </div>
          )}
        </div>
      )}

      {task.phase === 'fetching' && task.posts_fetched !== undefined && (
        <div className="bg-background/50 rounded-lg p-3">
          <p className="text-xs text-muted-foreground">
            <span className="font-medium text-foreground">{task.posts_fetched}</span> posts fetched
          </p>
        </div>
      )}
    </div>
  )
}

function StatCard({
  title,
  value,
  icon: Icon,
  color = 'blue',
  subtitle,
  action,
}: {
  title: string
  value: string | number
  icon: React.ElementType
  color?: 'blue' | 'green' | 'orange' | 'red'
  subtitle?: string
  action?: React.ReactNode
}) {
  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',
    },
    orange: {
      card: 'stat-card-orange shadow-orange-glow',
      icon: 'bg-amber-500/20 text-amber-600 dark:text-amber-400',
    },
    red: {
      card: 'bg-card border border-red-200 dark:border-red-800',
      icon: 'bg-red-500/20 text-red-600 dark:text-red-400',
    },
  }

  const styles = colorStyles[color]

  return (
    <div className={`p-4 md:p-6 rounded-xl ${styles.card} transition-all duration-200 hover:scale-[1.02]`}>
      <div className="flex items-start justify-between">
        <div>
          <p className="text-sm font-medium text-muted-foreground">{title}</p>
          <p className="text-2xl font-bold text-foreground mt-1">{value}</p>
          {subtitle && <p className="text-xs text-muted-foreground mt-1">{subtitle}</p>}
        </div>
        <div className="flex items-center gap-2">
          {action}
          <div className={`p-3 rounded-xl ${styles.icon}`}>
            <Icon className="w-5 h-5" />
          </div>
        </div>
      </div>
    </div>
  )
}

export default function PaidContentQueue() {
  useBreadcrumb(breadcrumbConfig['/paid-content/queue'])

  const queryClient = useQueryClient()
  const [selectedIds, setSelectedIds] = useState<number[]>([])
  const [expandedSections, setExpandedSections] = useState({
    downloading: true,
    pending: true,
    failed: true,
  })

  const { data: queue, isLoading } = useQuery({
    queryKey: ['paid-content-queue'],
    queryFn: () => api.paidContent.getQueue(),
    refetchInterval: 5000,
  })

  const { data: activeSyncs } = useQuery({
    queryKey: ['paid-content-active-syncs'],
    queryFn: () => api.paidContent.getActiveSyncs(),
    refetchInterval: 2000,
  })

  const { data: settings } = useQuery({
    queryKey: ['paid-content-settings'],
    queryFn: () => api.paidContent.getSettings(),
  })

  const updateSettingsMutation = useMutation({
    mutationFn: (updates: { auto_retry_failed?: number }) => api.paidContent.updateSettings(updates),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['paid-content-settings'] })
      notificationManager.success('Settings Updated', 'Auto-requeue setting changed')
    },
    onError: (error) => {
      notificationManager.error('Error', getErrorMessage(error))
    },
  })

  const removeFromQueueMutation = useMutation({
    mutationFn: (ids: number[]) => api.paidContent.removeMultipleFromQueue(ids),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['paid-content-queue'] })
      notificationManager.success('Removed', `${data.count} items removed from queue`)
      setSelectedIds([])
    },
    onError: (error) => {
      notificationManager.error('Error', getErrorMessage(error))
    },
  })

  const stopAllMutation = useMutation({
    mutationFn: () => api.paidContent.stopAllDownloads(),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['paid-content-queue'] })
      queryClient.invalidateQueries({ queryKey: ['paid-content-active-syncs'] })
      notificationManager.success(
        'Downloads Stopped',
        `${data.syncs_cancelled} syncs cancelled, ${data.downloads_paused} downloads paused`
      )
    },
    onError: (error) => {
      notificationManager.error('Error', getErrorMessage(error))
    },
  })

  const clearFailedMutation = useMutation({
    mutationFn: () => api.paidContent.clearFailedDownloads(),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['paid-content-queue'] })
      notificationManager.success('Cleared', `${data.count} failed downloads cleared`)
    },
    onError: (error) => {
      notificationManager.error('Error', getErrorMessage(error))
    },
  })

  const toggleAutoRequeueMutation = useMutation({
    mutationFn: ({ id, autoRequeue }: { id: number; autoRequeue: boolean }) =>
      api.paidContent.updateQueueItem(id, autoRequeue),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['paid-content-queue'] })
    },
    onError: (error) => {
      notificationManager.error('Error', getErrorMessage(error))
    },
  })

  const handleSelectAll = (items: QueueItem[]) => {
    const allIds = items.map((i) => i.id)
    const allSelected = allIds.every((id) => selectedIds.includes(id))
    if (allSelected) {
      setSelectedIds(selectedIds.filter((id) => !allIds.includes(id)))
    } else {
      setSelectedIds([...new Set([...selectedIds, ...allIds])])
    }
  }

  const handleSelect = (id: number) => {
    if (selectedIds.includes(id)) {
      setSelectedIds(selectedIds.filter((i) => i !== id))
    } else {
      setSelectedIds([...selectedIds, id])
    }
  }

  const toggleSection = (section: keyof typeof expandedSections) => {
    setExpandedSections((prev) => ({ ...prev, [section]: !prev[section] }))
  }

  const hasActiveDownloads = activeSyncs && activeSyncs.length > 0

  const renderQueueItem = (item: QueueItem, showAutoRequeue = false) => (
    <div
      key={item.id}
      className={`flex items-center gap-3 p-3 rounded-lg border ${
        selectedIds.includes(item.id)
          ? 'border-primary bg-primary/5'
          : 'border-border bg-card hover:bg-secondary/50'
      }`}
    >
      <input
        type="checkbox"
        checked={selectedIds.includes(item.id)}
        onChange={() => handleSelect(item.id)}
        className="checkbox checkbox-sm"
      />

      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className="font-medium text-sm truncate">{item.name}</span>
        </div>
        <div className="flex items-center gap-2 text-xs text-muted-foreground mt-0.5">
          <span>{item.username}</span>
          <span className="opacity-50">|</span>
          <span>{item.platform}</span>
          {item.post_title && (
            <>
              <span className="opacity-50">|</span>
              <span className="truncate max-w-[200px]">{item.post_title}</span>
            </>
          )}
        </div>
        {item.error_message && (
          <p className="text-xs text-red-500 mt-1 truncate">{item.error_message}</p>
        )}
      </div>

      {showAutoRequeue && (
        <button
          onClick={() =>
            toggleAutoRequeueMutation.mutate({
              id: item.id,
              autoRequeue: !item.auto_requeue,
            })
          }
          className={`btn btn-xs ${item.auto_requeue ? 'btn-primary' : 'btn-ghost'}`}
          title={item.auto_requeue ? 'Auto-requeue enabled' : 'Auto-requeue disabled'}
        >
          <RefreshCw className="w-3 h-3" />
        </button>
      )}

      {item.download_attempts !== undefined && item.download_attempts > 0 && (
        <span className="badge badge-sm badge-warning">
          {item.download_attempts} attempts
        </span>
      )}

      <button
        onClick={() => removeFromQueueMutation.mutate([item.id])}
        className="btn btn-ghost btn-xs text-red-500 hover:text-red-600"
        title="Remove from queue"
      >
        <X className="w-4 h-4" />
      </button>
    </div>
  )

  const renderSection = (
    title: string,
    icon: React.ReactNode,
    items: QueueItem[],
    sectionKey: keyof typeof expandedSections,
    totalCount: number,
    showAutoRequeue = false
  ) => (
    <div className="bg-card rounded-xl border border-border overflow-hidden">
      <button
        onClick={() => toggleSection(sectionKey)}
        className="w-full flex items-center justify-between p-4 hover:bg-secondary/50 transition-colors"
      >
        <div className="flex items-center gap-3">
          {icon}
          <h2 className="text-lg font-semibold">{title}</h2>
          <span className="badge badge-sm">{totalCount.toLocaleString()}</span>
        </div>
        {expandedSections[sectionKey] ? (
          <ChevronDown className="w-5 h-5 text-muted-foreground" />
        ) : (
          <ChevronRight className="w-5 h-5 text-muted-foreground" />
        )}
      </button>

      {expandedSections[sectionKey] && totalCount > 0 && (
        <div className="p-4 pt-0 space-y-2">
          <div className="flex items-center gap-2 mb-3">
            <input
              type="checkbox"
              checked={items.every((i) => selectedIds.includes(i.id))}
              onChange={() => handleSelectAll(items)}
              className="checkbox checkbox-sm"
            />
            <span className="text-sm text-muted-foreground">Select all ({items.length} shown)</span>
          </div>
          <div className="space-y-2 max-h-[400px] overflow-y-auto">
            {items.map((item) => renderQueueItem(item, showAutoRequeue))}
          </div>
          {totalCount > items.length && (
            <p className="text-sm text-muted-foreground text-center py-2">
              Showing {items.length} of {totalCount.toLocaleString()} items
            </p>
          )}
        </div>
      )}

      {expandedSections[sectionKey] && totalCount === 0 && (
        <div className="p-8 text-center text-muted-foreground">
          <Check className="w-8 h-8 mx-auto mb-2 text-emerald-500" />
          <p>No items</p>
        </div>
      )}
    </div>
  )

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

  const pending = queue?.pending || []
  const downloading = queue?.downloading || []
  const failed = queue?.failed || []
  const counts = queue?.counts || { pending: 0, downloading: 0, failed: 0 }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <ListOrdered className="w-8 h-8 text-violet-500" />
            Download Queue
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            Manage pending, active, and failed downloads
          </p>
        </div>

        <div className="flex items-center gap-3">
          {/* Auto-Requeue Toggle */}
          <button
            onClick={() => updateSettingsMutation.mutate({ auto_retry_failed: settings?.auto_retry_failed ? 0 : 1 })}
            disabled={updateSettingsMutation.isPending}
            className={`btn btn-sm ${settings?.auto_retry_failed ? 'btn-primary' : 'btn-ghost border-border'}`}
            title={settings?.auto_retry_failed ? 'Auto-requeue is ON' : 'Auto-requeue is OFF'}
          >
            {settings?.auto_retry_failed ? (
              <ToggleRight className="w-4 h-4 mr-1" />
            ) : (
              <ToggleLeft className="w-4 h-4 mr-1" />
            )}
            Auto-Requeue
          </button>

          {/* Remove Selected */}
          {selectedIds.length > 0 && (
            <button
              onClick={() => removeFromQueueMutation.mutate(selectedIds)}
              disabled={removeFromQueueMutation.isPending}
              className="btn btn-error btn-sm"
            >
              <Trash2 className="w-4 h-4 mr-1" />
              Remove {selectedIds.length}
            </button>
          )}

          {/* Stop/Start Queue */}
          {hasActiveDownloads ? (
            <button
              onClick={() => stopAllMutation.mutate()}
              disabled={stopAllMutation.isPending}
              className="btn btn-warning"
            >
              <StopCircle className="w-4 h-4 mr-2" />
              Stop Downloads
            </button>
          ) : (
            <button
              onClick={async () => {
                try {
                  await api.paidContent.syncAllCreators()
                  notificationManager.success('Queue Started', 'Resuming downloads for all creators')
                } catch (err) {
                  notificationManager.error('Queue Failed', err instanceof Error ? err.message : 'Failed to start queue')
                }
              }}
              disabled={counts.pending === 0}
              className="btn btn-primary"
            >
              <PlayCircle className="w-4 h-4 mr-2" />
              Start Queue
            </button>
          )}
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <StatCard
          title="Downloading"
          value={counts.downloading}
          icon={Download}
          color="blue"
          subtitle="Active downloads"
        />
        <StatCard
          title="Pending"
          value={counts.pending}
          icon={Clock}
          color="orange"
          subtitle="Queued for download"
        />
        <StatCard
          title="Failed"
          value={counts.failed}
          icon={AlertCircle}
          color="red"
          subtitle="Need attention"
          action={
            failed.length > 0 ? (
              <button
                onClick={() => clearFailedMutation.mutate()}
                disabled={clearFailedMutation.isPending}
                className="p-2 rounded-lg hover:bg-red-500/10 transition-colors"
                title="Clear all failed"
              >
                <Trash2 className="w-4 h-4 text-red-500" />
              </button>
            ) : undefined
          }
        />
      </div>

      {/* Active Syncs */}
      {activeSyncs && activeSyncs.length > 0 && (
        <div className="bg-card rounded-xl border border-border p-4 md:p-6">
          <div className="flex items-center gap-3 mb-4">
            <div className="p-2 rounded-lg bg-blue-500/10">
              <Loader2 className="w-5 h-5 animate-spin text-blue-500" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-foreground">Active Syncs</h2>
              <p className="text-sm text-muted-foreground">{activeSyncs.length} creator{activeSyncs.length !== 1 ? 's' : ''} syncing</p>
            </div>
          </div>
          <div className="space-y-3">
            {activeSyncs.map((sync: ActiveTask) => (
              <ActiveTaskCard key={sync.creator_id} task={sync} />
            ))}
          </div>
        </div>
      )}

      {/* Queue Sections */}
      <div className="space-y-4">
        {renderSection(
          'Downloading',
          <Download className="w-5 h-5 text-blue-500" />,
          downloading,
          'downloading',
          counts.downloading
        )}

        {renderSection(
          'Pending',
          <Clock className="w-5 h-5 text-amber-500" />,
          pending,
          'pending',
          counts.pending,
          true
        )}

        {renderSection(
          'Failed',
          <AlertCircle className="w-5 h-5 text-red-500" />,
          failed,
          'failed',
          counts.failed,
          true
        )}
      </div>
    </div>
  )
}
