import { useMemo, useState, useEffect } from 'react'
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 { useTaskStore } from '@/store/taskStore'
import {
  FileText,
  Download,
  AlertCircle,
  Clock,
  Layers,
  FileJson,
  Loader2,
  ArrowLeft,
  RefreshCw,
  FileSearch,
  Table2,
  Image,
  BarChart3,
  Database,
  Languages,
  Globe,
  CheckCircle,
  Trash2,
  FileOutput
} from 'lucide-react'
import type { ProcessingTrack, TranslationStatus, TranslationListItem } from '@/types/apiV2'
import { Badge } from '@/components/ui/badge'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select'
import { Progress } from '@/components/ui/progress'

// Language options for translation
const LANGUAGE_OPTIONS = [
  { value: 'en', label: 'English' },
  { value: 'ja', label: '日本語' },
  { value: 'ko', label: '한국어' },
  { value: 'zh-TW', label: '繁體中文' },
  { value: 'zh-CN', label: '简体中文' },
  { value: 'de', label: 'Deutsch' },
  { value: 'fr', label: 'Français' },
  { value: 'es', label: 'Español' },
  { value: 'pt', label: 'Português' },
  { value: 'it', label: 'Italiano' },
  { value: 'ru', label: 'Русский' },
  { value: 'vi', label: 'Tiếng Việt' },
  { value: 'th', label: 'ไทย' },
]

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

  // TaskStore for caching
  const { updateTaskCache } = useTaskStore()

  // Translation state
  const [targetLang, setTargetLang] = useState('en')
  const [isTranslating, setIsTranslating] = useState(false)
  const [translationStatus, setTranslationStatus] = useState<TranslationStatus | null>(null)
  const [translationProgress, setTranslationProgress] = useState(0)

  // 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
    },
  })

  // Sync task details to TaskStore cache
  useEffect(() => {
    if (taskDetail) {
      updateTaskCache(taskDetail)
    }
  }, [taskDetail, updateTaskCache])

  // Get processing metadata for completed tasks
  const { data: processingMetadata } = useQuery({
    queryKey: ['processingMetadata', taskId],
    queryFn: () => apiClientV2.getProcessingMetadata(taskId!),
    enabled: !!taskId && taskDetail?.status === 'completed',
    retry: false,
  })

  // Get existing translations
  const { data: translationList, refetch: refetchTranslations } = useQuery({
    queryKey: ['translations', taskId],
    queryFn: () => apiClientV2.listTranslations(taskId!),
    enabled: !!taskId && taskDetail?.status === 'completed',
    retry: false,
  })

  // Poll translation status when translating
  useEffect(() => {
    if (!isTranslating || !taskId) return

    const pollInterval = setInterval(async () => {
      try {
        const status = await apiClientV2.getTranslationStatus(taskId)
        setTranslationStatus(status.status)

        if (status.progress) {
          setTranslationProgress(status.progress.percentage)
        }

        if (status.status === 'completed') {
          setIsTranslating(false)
          setTranslationProgress(100)
          toast({
            title: '翻譯完成',
            description: `文件已翻譯為 ${LANGUAGE_OPTIONS.find(l => l.value === targetLang)?.label || targetLang}`,
            variant: 'success',
          })
          refetchTranslations()
        } else if (status.status === 'failed') {
          setIsTranslating(false)
          toast({
            title: '翻譯失敗',
            description: status.error_message || '未知錯誤',
            variant: 'destructive',
          })
        }
      } catch (error) {
        console.error('Failed to poll translation status:', error)
      }
    }, 2000)

    return () => clearInterval(pollInterval)
  }, [isTranslating, taskId, targetLang, toast, refetchTranslations])

  // Construct PDF URL for preview - memoize to prevent unnecessary reloads
  // Must be called unconditionally before any early returns (React hooks rule)
  const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
  const pdfUrl = useMemo(() => {
    return taskId ? `${API_BASE_URL}/api/v2/tasks/${taskId}/download/pdf` : ''
  }, [taskId, API_BASE_URL])

  // Get auth token for PDF preview - memoize to prevent new object reference each render
  const pdfHttpHeaders = useMemo(() => {
    const authToken = localStorage.getItem('auth_token_v2')
    return authToken ? { Authorization: `Bearer ${authToken}` } : undefined
  }, [])

  const getTrackBadge = (track?: ProcessingTrack) => {
    if (!track) return null
    switch (track) {
      case 'direct':
        return <Badge variant="default" className="bg-blue-600">直接提取</Badge>
      case 'ocr':
        return <Badge variant="default" className="bg-purple-600">OCR</Badge>
      case 'hybrid':
        return <Badge variant="default" className="bg-orange-600">混合</Badge>
      default:
        return <Badge variant="secondary">自動</Badge>
    }
  }

  const getTrackDescription = (track?: ProcessingTrack) => {
    switch (track) {
      case 'direct':
        return 'PyMuPDF 直接提取'
      case 'ocr':
        return 'PP-StructureV3 OCR'
      case 'hybrid':
        return '混合處理'
      default:
        return 'OCR'
    }
  }

  const handleDownloadLayoutPDF = async () => {
    if (!taskId) return
    try {
      await apiClientV2.downloadPDF(taskId, 'layout')
      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 handleDownloadReflowPDF = async () => {
    if (!taskId) return
    try {
      await apiClientV2.downloadPDF(taskId, 'reflow')
      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 handleDownloadUnified = async () => {
    if (!taskId) return
    try {
      await apiClientV2.downloadUnified(taskId)
      toast({
        title: t('export.exportSuccess'),
        description: 'UnifiedDocument JSON 已下載',
        variant: 'success',
      })
    } catch (error: any) {
      toast({
        title: t('export.exportError'),
        description: error.response?.data?.detail || t('errors.networkError'),
        variant: 'destructive',
      })
    }
  }

  const handleStartTranslation = async () => {
    if (!taskId || isTranslating) return

    try {
      setIsTranslating(true)
      setTranslationStatus('pending')
      setTranslationProgress(0)

      const response = await apiClientV2.startTranslation(taskId, {
        target_lang: targetLang,
        source_lang: 'auto',
      })

      if (response.status === 'completed') {
        // Translation already exists
        setIsTranslating(false)
        setTranslationProgress(100)
        toast({
          title: '翻譯已存在',
          description: response.message,
          variant: 'success',
        })
        refetchTranslations()
      } else {
        setTranslationStatus(response.status)
        toast({
          title: '開始翻譯',
          description: '翻譯任務已啟動，請稍候...',
        })
      }
    } catch (error: any) {
      setIsTranslating(false)
      setTranslationStatus(null)
      toast({
        title: '啟動翻譯失敗',
        description: error.response?.data?.detail || t('errors.networkError'),
        variant: 'destructive',
      })
    }
  }

  const handleDownloadTranslation = async (lang: string) => {
    if (!taskId) return
    try {
      await apiClientV2.downloadTranslation(taskId, lang)
      toast({
        title: '下載成功',
        description: `翻譯結果 (${lang}) 已下載`,
        variant: 'success',
      })
    } catch (error: any) {
      toast({
        title: '下載失敗',
        description: error.response?.data?.detail || t('errors.networkError'),
        variant: 'destructive',
      })
    }
  }

  const handleDeleteTranslation = async (lang: string) => {
    if (!taskId) return
    try {
      await apiClientV2.deleteTranslation(taskId, lang)
      toast({
        title: '刪除成功',
        description: `翻譯結果 (${lang}) 已刪除`,
        variant: 'success',
      })
      refetchTranslations()
    } catch (error: any) {
      toast({
        title: '刪除失敗',
        description: error.response?.data?.detail || t('errors.networkError'),
        variant: 'destructive',
      })
    }
  }

  const handleDownloadTranslatedPdf = async (lang: string, format: 'layout' | 'reflow' = 'reflow') => {
    if (!taskId) return
    try {
      await apiClientV2.downloadTranslatedPdf(taskId, lang, format)
      const formatLabel = format === 'layout' ? '版面' : '流式'
      toast({
        title: '下載成功',
        description: `翻譯 ${formatLabel} PDF (${lang}) 已下載`,
        variant: 'success',
      })
    } catch (error: any) {
      toast({
        title: '下載失敗',
        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 getTranslationStatusText = (status: TranslationStatus | null) => {
    switch (status) {
      case 'pending':
        return '準備中...'
      case 'loading_model':
        return '載入翻譯模型...'
      case 'translating':
        return '翻譯中...'
      case 'completed':
        return '完成'
      case 'failed':
        return '失敗'
      default:
        return ''
    }
  }

  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'

  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_track || processingMetadata?.processing_track) && (
                <div>
                  <p className="text-sm text-muted-foreground mb-1">處理軌道</p>
                  <div className="flex items-center gap-2">
                    {getTrackBadge(taskDetail.processing_track || processingMetadata?.processing_track)}
                    <span className="text-sm text-muted-foreground">
                      {getTrackDescription(taskDetail.processing_track || processingMetadata?.processing_track)}
                    </span>
                  </div>
                </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-2 md:grid-cols-5 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={handleDownloadUnified} variant="outline" className="gap-2 h-20 flex-col">
                <Database className="w-8 h-8" />
                <span>統一格式</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={handleDownloadLayoutPDF} className="gap-2 h-20 flex-col">
                <Download className="w-8 h-8" />
                <span>版面 PDF</span>
              </Button>
              <Button onClick={handleDownloadReflowPDF} variant="outline" className="gap-2 h-20 flex-col">
                <Download className="w-8 h-8" />
                <span>流式 PDF</span>
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Translation Options */}
      {isCompleted && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Languages className="w-5 h-5" />
              文件翻譯
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Start New Translation */}
            <div className="flex flex-col md:flex-row items-start md:items-center gap-4">
              <div className="flex items-center gap-2">
                <Globe className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm text-muted-foreground">目標語言：</span>
                <Select
                  value={targetLang}
                  onValueChange={setTargetLang}
                  disabled={isTranslating}
                >
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="選擇語言" />
                  </SelectTrigger>
                  <SelectContent>
                    {LANGUAGE_OPTIONS.map(lang => (
                      <SelectItem key={lang.value} value={lang.value}>
                        {lang.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <Button
                onClick={handleStartTranslation}
                disabled={isTranslating}
                className="gap-2"
              >
                {isTranslating ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Languages className="w-4 h-4" />
                )}
                {isTranslating ? getTranslationStatusText(translationStatus) : '開始翻譯'}
              </Button>
            </div>

            {/* Translation Progress */}
            {isTranslating && (
              <div className="space-y-2">
                <div className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground">{getTranslationStatusText(translationStatus)}</span>
                  <span className="text-muted-foreground">{translationProgress.toFixed(0)}%</span>
                </div>
                <Progress value={translationProgress} className="h-2" />
              </div>
            )}

            {/* Existing Translations */}
            {translationList && translationList.translations.length > 0 && (
              <div className="space-y-2">
                <p className="text-sm font-medium text-muted-foreground">已完成的翻譯：</p>
                <div className="space-y-2">
                  {translationList.translations.map((item: TranslationListItem) => (
                    <div
                      key={item.target_lang}
                      className="flex items-center justify-between p-3 bg-muted/50 rounded-lg"
                    >
                      <div className="flex items-center gap-3">
                        <CheckCircle className="w-4 h-4 text-green-500" />
                        <div>
                          <span className="font-medium">
                            {LANGUAGE_OPTIONS.find(l => l.value === item.target_lang)?.label || item.target_lang}
                          </span>
                          <span className="text-sm text-muted-foreground ml-2">
                            ({item.statistics.translated_elements} 元素, {item.statistics.processing_time_seconds.toFixed(1)}s)
                          </span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleDownloadTranslation(item.target_lang)}
                          className="gap-1"
                        >
                          <Download className="w-3 h-3" />
                          JSON
                        </Button>
                        <Select
                          onValueChange={(format: 'layout' | 'reflow') =>
                            handleDownloadTranslatedPdf(item.target_lang, format)
                          }
                        >
                          <SelectTrigger className="w-[100px] h-8">
                            <div className="flex items-center gap-1">
                              <FileOutput className="w-3 h-3" />
                              <span className="text-xs">PDF</span>
                            </div>
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="layout">版面 PDF</SelectItem>
                            <SelectItem value="reflow">流式 PDF</SelectItem>
                          </SelectContent>
                        </Select>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteTranslation(item.target_lang)}
                          className="gap-1 text-destructive hover:text-destructive"
                        >
                          <Trash2 className="w-3 h-3" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <p className="text-xs text-muted-foreground">
              使用雲端翻譯服務進行多語言翻譯，支援多種目標語言。
            </p>
          </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-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-primary/10 rounded-lg">
                  <Clock className="w-5 h-5 text-primary" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">處理時間</p>
                  <p className="text-lg font-bold">
                    {processingMetadata?.processing_time_seconds?.toFixed(2) ||
                     (taskDetail.processing_time_ms ? (taskDetail.processing_time_ms / 1000).toFixed(2) : '0')}s
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-blue-500/10 rounded-lg">
                  <Layers className="w-5 h-5 text-blue-500" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">頁數</p>
                  <p className="text-lg font-bold">
                    {processingMetadata?.page_count || '-'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-purple-500/10 rounded-lg">
                  <FileSearch className="w-5 h-5 text-purple-500" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">文本區域</p>
                  <p className="text-lg font-bold">
                    {processingMetadata?.total_text_regions || '-'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-green-500/10 rounded-lg">
                  <Table2 className="w-5 h-5 text-green-500" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">表格</p>
                  <p className="text-lg font-bold">
                    {processingMetadata?.total_tables || '-'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-orange-500/10 rounded-lg">
                  <Image className="w-5 h-5 text-orange-500" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">圖片</p>
                  <p className="text-lg font-bold">
                    {processingMetadata?.total_images || '-'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-cyan-500/10 rounded-lg">
                  <BarChart3 className="w-5 h-5 text-cyan-500" />
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">平均置信度</p>
                  <p className="text-lg font-bold">
                    {processingMetadata?.average_confidence
                      ? `${(processingMetadata.average_confidence * 100).toFixed(0)}%`
                      : '-'}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

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