import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useQuery } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import PDFViewer from '@/components/PDFViewer'
import { useToast } from '@/components/ui/toast'
import { apiClientV2 } from '@/services/apiV2'
import {
  FileText,
  Download,
  AlertCircle,
  TrendingUp,
  Clock,
  Layers,
  FileJson,
  Loader2,
  ArrowLeft,
  RefreshCw
} from 'lucide-react'
import { Badge } from '@/components/ui/badge'

export default function TaskDetailPage() {
  const { taskId } = useParams<{ taskId: string }>()
  const { t } = useTranslation()
  const navigate = useNavigate()
  const { toast } = useToast()

  // Get task details
  const { data: taskDetail, isLoading, refetch } = useQuery({
    queryKey: ['taskDetail', taskId],
    queryFn: () => apiClientV2.getTask(taskId!),
    enabled: !!taskId,
    refetchInterval: (query) => {
      const data = query.state.data
      if (!data) return 2000
      if (data.status === 'completed' || data.status === 'failed') {
        return false
      }
      return 2000 // Poll every 2 seconds for processing tasks
    },
  })

  const handleDownloadPDF = async () => {
    if (!taskId) return
    try {
      await apiClientV2.downloadPDF(taskId)
      toast({
        title: t('export.exportSuccess'),
        description: 'PDF 已下載',
        variant: 'success',
      })
    } catch (error: any) {
      toast({
        title: t('export.exportError'),
        description: error.response?.data?.detail || t('errors.networkError'),
        variant: 'destructive',
      })
    }
  }

  const handleDownloadMarkdown = async () => {
    if (!taskId) return
    try {
      await apiClientV2.downloadMarkdown(taskId)
      toast({
        title: t('export.exportSuccess'),
        description: 'Markdown 已下載',
        variant: 'success',
      })
    } catch (error: any) {
      toast({
        title: t('export.exportError'),
        description: error.response?.data?.detail || t('errors.networkError'),
        variant: 'destructive',
      })
    }
  }

  const handleDownloadJSON = async () => {
    if (!taskId) return
    try {
      await apiClientV2.downloadJSON(taskId)
      toast({
        title: t('export.exportSuccess'),
        description: 'JSON 已下載',
        variant: 'success',
      })
    } catch (error: any) {
      toast({
        title: t('export.exportError'),
        description: error.response?.data?.detail || t('errors.networkError'),
        variant: 'destructive',
      })
    }
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'completed':
        return <Badge variant="default" className="bg-green-600">已完成</Badge>
      case 'processing':
        return <Badge variant="default">處理中</Badge>
      case 'failed':
        return <Badge variant="destructive">失敗</Badge>
      default:
        return <Badge variant="secondary">待處理</Badge>
    }
  }

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return date.toLocaleString('zh-TW')
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-center">
          <Loader2 className="w-12 h-12 animate-spin text-primary mx-auto mb-4" />
          <p className="text-muted-foreground">載入任務詳情...</p>
        </div>
      </div>
    )
  }

  if (!taskDetail) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Card className="max-w-md text-center">
          <CardHeader>
            <div className="flex justify-center mb-4">
              <AlertCircle className="w-16 h-16 text-destructive" />
            </div>
            <CardTitle>任務不存在</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-muted-foreground">找不到任務 ID: {taskId}</p>
            <Button onClick={() => navigate('/tasks')}>
              返回任務歷史
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  const isCompleted = taskDetail.status === 'completed'
  const isProcessing = taskDetail.status === 'processing'
  const isFailed = taskDetail.status === 'failed'

  // Construct PDF URL for preview
  const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
  const pdfUrl = taskId ? `${API_BASE_URL}/api/v2/tasks/${taskId}/download/pdf` : ''

  // Get auth token for PDF preview
  const authToken = localStorage.getItem('auth_token_v2')
  const pdfHttpHeaders = authToken ? { Authorization: `Bearer ${authToken}` } : undefined

  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">任務詳情</h1>
              <p className="text-muted-foreground mt-1">
                任務 ID: <span className="font-mono text-primary">{taskId}</span>
              </p>
            </div>
          </div>
          <div className="flex gap-3 items-center">
            <Button onClick={() => refetch()} variant="outline" size="sm" className="gap-2">
              <RefreshCw className="w-4 h-4" />
              刷新
            </Button>
            {getStatusBadge(taskDetail.status)}
          </div>
        </div>
      </div>

      {/* Task Info Card */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="w-5 h-5" />
            任務資訊
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-3">
              <div>
                <p className="text-sm text-muted-foreground mb-1">檔案名稱</p>
                <p className="font-medium">{taskDetail.filename || '未知檔案'}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">建立時間</p>
                <p className="font-medium">{formatDate(taskDetail.created_at)}</p>
              </div>
              {taskDetail.completed_at && (
                <div>
                  <p className="text-sm text-muted-foreground mb-1">完成時間</p>
                  <p className="font-medium">{formatDate(taskDetail.completed_at)}</p>
                </div>
              )}
            </div>
            <div className="space-y-3">
              <div>
                <p className="text-sm text-muted-foreground mb-1">任務狀態</p>
                {getStatusBadge(taskDetail.status)}
              </div>
              {taskDetail.processing_time_ms && (
                <div>
                  <p className="text-sm text-muted-foreground mb-1">處理時間</p>
                  <p className="font-medium">{(taskDetail.processing_time_ms / 1000).toFixed(2)} 秒</p>
                </div>
              )}
              {taskDetail.updated_at && (
                <div>
                  <p className="text-sm text-muted-foreground mb-1">最後更新</p>
                  <p className="font-medium">{formatDate(taskDetail.updated_at)}</p>
                </div>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Download Options */}
      {isCompleted && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Download className="w-5 h-5" />
              下載結果
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <Button onClick={handleDownloadJSON} variant="outline" className="gap-2 h-20 flex-col">
                <FileJson className="w-8 h-8" />
                <span>JSON 格式</span>
              </Button>
              <Button onClick={handleDownloadMarkdown} variant="outline" className="gap-2 h-20 flex-col">
                <FileText className="w-8 h-8" />
                <span>Markdown 格式</span>
              </Button>
              <Button onClick={handleDownloadPDF} className="gap-2 h-20 flex-col">
                <Download className="w-8 h-8" />
                <span>PDF 格式</span>
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Error Message */}
      {isFailed && taskDetail.error_message && (
        <Card className="border-destructive">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-destructive">
              <AlertCircle className="w-5 h-5" />
              錯誤訊息
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-destructive">{taskDetail.error_message}</p>
          </CardContent>
        </Card>
      )}

      {/* Processing Status */}
      {isProcessing && (
        <Card>
          <CardContent className="p-12 text-center">
            <Loader2 className="w-16 h-16 animate-spin text-primary mx-auto mb-4" />
            <p className="text-lg font-semibold">正在處理中...</p>
            <p className="text-muted-foreground mt-2">請稍候，OCR 處理需要一些時間</p>
          </CardContent>
        </Card>
      )}

      {/* Stats Grid (for completed tasks) */}
      {isCompleted && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center gap-3">
                <div className="p-3 bg-primary/10 rounded-lg">
                  <Clock className="w-6 h-6 text-primary" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">處理時間</p>
                  <p className="text-2xl font-bold">
                    {taskDetail.processing_time_ms ? (taskDetail.processing_time_ms / 1000).toFixed(2) : '0'}s
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center gap-3">
                <div className="p-3 bg-success/10 rounded-lg">
                  <TrendingUp className="w-6 h-6 text-success" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">處理狀態</p>
                  <p className="text-2xl font-bold text-success">成功</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center gap-3">
                <div className="p-3 bg-accent/10 rounded-lg">
                  <Layers className="w-6 h-6 text-accent" />
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">任務類型</p>
                  <p className="text-2xl font-bold">OCR</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Result Preview */}
      {isCompleted && (
        <PDFViewer
          title={`OCR 結果預覽 - ${taskDetail.filename || '未知檔案'}`}
          pdfUrl={pdfUrl}
          httpHeaders={pdfHttpHeaders}
        />
      )}
    </div>
  )
}
