import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useQuery } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { useToast } from '@/components/ui/toast'
import { apiClientV2 } from '@/services/apiV2'
import {
  Download,
  FileText,
  FileJson,
  FileType,
  AlertCircle,
  Settings,
  CheckCircle2,
  ArrowLeft,
  Loader2
} from 'lucide-react'

type ExportFormat = 'json' | 'markdown' | 'pdf'

export default function ExportPage() {
  const { t } = useTranslation()
  const navigate = useNavigate()
  const { toast } = useToast()

  const [selectedTasks, setSelectedTasks] = useState<Set<string>>(new Set())
  const [exportFormat, setExportFormat] = useState<ExportFormat>('markdown')
  const [isExporting, setIsExporting] = useState(false)

  // Fetch completed tasks
  const { data: tasksData, isLoading } = useQuery({
    queryKey: ['tasks', 'completed'],
    queryFn: () => apiClientV2.listTasks({
      status: 'completed',
      page: 1,
      page_size: 100,
      order_by: 'completed_at',
      order_desc: true
    }),
  })

  const completedTasks = tasksData?.tasks || []

  // Select/Deselect all
  const handleSelectAll = () => {
    if (selectedTasks.size === completedTasks.length) {
      setSelectedTasks(new Set())
    } else {
      setSelectedTasks(new Set(completedTasks.map(t => t.task_id)))
    }
  }

  // Toggle task selection
  const handleToggleTask = (taskId: string) => {
    const newSelected = new Set(selectedTasks)
    if (newSelected.has(taskId)) {
      newSelected.delete(taskId)
    } else {
      newSelected.add(taskId)
    }
    setSelectedTasks(newSelected)
  }

  // Export selected tasks
  const handleExport = async () => {
    if (selectedTasks.size === 0) {
      toast({
        title: '請選擇任務',
        description: '請至少選擇一個任務進行匯出',
        variant: 'destructive',
      })
      return
    }

    setIsExporting(true)
    let successCount = 0
    let errorCount = 0

    try {
      for (const taskId of selectedTasks) {
        try {
          if (exportFormat === 'json') {
            await apiClientV2.downloadJSON(taskId)
          } else if (exportFormat === 'markdown') {
            await apiClientV2.downloadMarkdown(taskId)
          } else if (exportFormat === 'pdf') {
            await apiClientV2.downloadPDF(taskId)
          }
          successCount++
        } catch (error) {
          console.error(`Export failed for task ${taskId}:`, error)
          errorCount++
        }
      }

      if (successCount > 0) {
        toast({
          title: t('export.exportSuccess'),
          description: `成功匯出 ${successCount} 個檔案${errorCount > 0 ? `，${errorCount} 個失敗` : ''}`,
          variant: 'success',
        })
      }

      if (errorCount > 0 && successCount === 0) {
        toast({
          title: t('export.exportError'),
          description: `所有匯出失敗 (${errorCount} 個檔案)`,
          variant: 'destructive',
        })
      }
    } finally {
      setIsExporting(false)
    }
  }

  const formatIcons = {
    json: FileJson,
    markdown: FileText,
    pdf: FileType,
  }

  const formatLabels = {
    json: 'JSON',
    markdown: 'Markdown',
    pdf: 'PDF',
  }

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="page-header">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Button variant="outline" onClick={() => navigate('/tasks')} className="gap-2">
              <ArrowLeft className="w-4 h-4" />
              返回
            </Button>
            <div>
              <h1 className="page-title">{t('export.title')}</h1>
              <p className="text-muted-foreground mt-1">批次匯出 OCR 處理結果</p>
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Task Selection */}
        <div className="lg:col-span-2 space-y-6">
          {/* Format Selection */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <FileType className="w-5 h-5" />
                選擇匯出格式
              </CardTitle>
              <CardDescription>選擇要匯出的檔案格式</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-3 gap-3">
                {(['json', 'markdown', 'pdf'] as ExportFormat[]).map((fmt) => {
                  const Icon = formatIcons[fmt]
                  return (
                    <button
                      key={fmt}
                      onClick={() => setExportFormat(fmt)}
                      className={`p-4 border-2 rounded-lg transition-all ${
                        exportFormat === fmt
                          ? 'border-primary bg-primary/10 shadow-md'
                          : 'border-border hover:border-primary/50 hover:bg-muted/50'
                      }`}
                    >
                      <Icon className={`w-6 h-6 mx-auto mb-2 ${exportFormat === fmt ? 'text-primary' : 'text-muted-foreground'}`} />
                      <div className={`text-sm font-medium ${exportFormat === fmt ? 'text-primary' : 'text-foreground'}`}>
                        {formatLabels[fmt]}
                      </div>
                    </button>
                  )
                })}
              </div>
            </CardContent>
          </Card>

          {/* Task List */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="flex items-center gap-2">
                    <CheckCircle2 className="w-5 h-5" />
                    選擇任務
                  </CardTitle>
                  <CardDescription>
                    選擇要匯出的已完成任務 ({selectedTasks.size}/{completedTasks.length} 已選)
                  </CardDescription>
                </div>
                {completedTasks.length > 0 && (
                  <Button variant="outline" size="sm" onClick={handleSelectAll}>
                    {selectedTasks.size === completedTasks.length ? '取消全選' : '全選'}
                  </Button>
                )}
              </div>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="w-8 h-8 animate-spin text-primary" />
                </div>
              ) : completedTasks.length === 0 ? (
                <div className="text-center py-12">
                  <AlertCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
                  <p className="text-muted-foreground">沒有已完成的任務</p>
                  <Button onClick={() => navigate('/upload')} className="mt-4">
                    前往上傳頁面
                  </Button>
                </div>
              ) : (
                <div className="space-y-2 max-h-[500px] overflow-y-auto">
                  {completedTasks.map((task) => (
                    <div
                      key={task.task_id}
                      className={`flex items-center gap-3 p-3 border rounded-lg cursor-pointer transition-colors ${
                        selectedTasks.has(task.task_id)
                          ? 'border-primary bg-primary/5'
                          : 'border-border hover:border-primary/50 hover:bg-muted/50'
                      }`}
                      onClick={() => handleToggleTask(task.task_id)}
                    >
                      <Checkbox
                        checked={selectedTasks.has(task.task_id)}
                        onCheckedChange={() => handleToggleTask(task.task_id)}
                        onClick={(e) => e.stopPropagation()}
                      />
                      <div className="flex-1 min-w-0">
                        <p className="font-medium truncate">{task.filename || '未知檔案'}</p>
                        <p className="text-xs text-muted-foreground">
                          {new Date(task.completed_at!).toLocaleString('zh-TW')}
                          {task.processing_time_ms && ` · ${(task.processing_time_ms / 1000).toFixed(2)}s`}
                        </p>
                      </div>
                      <FileText className="w-5 h-5 text-muted-foreground flex-shrink-0" />
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Right Column - Export Summary */}
        <div className="lg:col-span-1">
          <Card className="sticky top-6">
            <CardHeader>
              <CardTitle>匯出摘要</CardTitle>
              <CardDescription>當前設定概覽</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="p-4 bg-muted/30 rounded-lg space-y-3">
                <div>
                  <div className="text-xs text-muted-foreground mb-1">格式</div>
                  <div className="flex items-center gap-2">
                    {(() => {
                      const Icon = formatIcons[exportFormat]
                      return <Icon className="w-4 h-4 text-primary" />
                    })()}
                    <span className="text-sm font-medium text-foreground">{formatLabels[exportFormat]}</span>
                  </div>
                </div>

                <div>
                  <div className="text-xs text-muted-foreground mb-1">已選任務</div>
                  <div className="text-2xl font-bold text-foreground">{selectedTasks.size}</div>
                </div>

                {selectedTasks.size > 0 && (
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">預計下載</div>
                    <div className="text-sm font-medium text-foreground">
                      {selectedTasks.size} 個 {formatLabels[exportFormat]} 檔案
                    </div>
                  </div>
                )}
              </div>

              <div className="flex flex-col gap-2">
                <Button
                  onClick={handleExport}
                  disabled={selectedTasks.size === 0 || isExporting}
                  className="w-full gap-2"
                  size="lg"
                >
                  {isExporting ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      匯出中...
                    </>
                  ) : (
                    <>
                      <Download className="w-4 h-4" />
                      匯出選定任務
                    </>
                  )}
                </Button>

                <Button
                  variant="outline"
                  onClick={() => navigate('/tasks')}
                  className="w-full gap-2"
                >
                  <ArrowLeft className="w-4 h-4" />
                  返回任務歷史
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}
