import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useQuery, useMutation } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Progress } from '@/components/ui/progress'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { useToast } from '@/components/ui/toast'
import { useUploadStore } from '@/store/uploadStore'
import { apiClient } from '@/services/api'
import { Play, CheckCircle, FileText, AlertCircle, Clock, Activity, Loader2 } from 'lucide-react'

export default function ProcessingPage() {
  const { t } = useTranslation()
  const navigate = useNavigate()
  const { toast } = useToast()
  const { batchId, files } = useUploadStore()

  // Start OCR processing
  const processOCRMutation = useMutation({
    mutationFn: () => apiClient.processOCR({ batch_id: batchId! }),
    onSuccess: () => {
      toast({
        title: '開始處理',
        description: 'OCR 處理已開始',
        variant: 'success',
      })
    },
    onError: (error: any) => {
      toast({
        title: t('errors.processingFailed'),
        description: error.response?.data?.detail || t('errors.networkError'),
        variant: 'destructive',
      })
    },
  })

  // Poll batch status
  const { data: batchStatus } = useQuery({
    queryKey: ['batchStatus', batchId],
    queryFn: () => apiClient.getBatchStatus(batchId!),
    enabled: !!batchId,
    refetchInterval: (query) => {
      const data = query.state.data
      if (!data) return 2000
      // Stop polling if completed or failed
      if (data.batch.status === 'completed' || data.batch.status === 'failed') {
        return false
      }
      return 2000 // Poll every 2 seconds
    },
  })

  // Auto-redirect when completed
  useEffect(() => {
    if (batchStatus?.batch.status === 'completed') {
      setTimeout(() => {
        navigate('/results')
      }, 1000)
    }
  }, [batchStatus?.batch.status, navigate])

  const handleStartProcessing = () => {
    processOCRMutation.mutate()
  }

  const handleViewResults = () => {
    navigate('/results')
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'completed':
        return <Badge variant="success">{t('processing.completed')}</Badge>
      case 'processing':
        return <Badge variant="default">{t('processing.processing')}</Badge>
      case 'failed':
        return <Badge variant="destructive">{t('processing.failed')}</Badge>
      default:
        return <Badge variant="secondary">{t('processing.pending')}</Badge>
    }
  }

  // Show helpful message when no batch is selected
  if (!batchId) {
    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">
              <div className="w-16 h-16 bg-muted rounded-full flex items-center justify-center">
                <AlertCircle className="w-8 h-8 text-muted-foreground" />
              </div>
            </div>
            <CardTitle className="text-xl">{t('processing.title')}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-muted-foreground">
              {t('processing.noBatchMessage', { defaultValue: '尚未選擇任何批次。請先上傳檔案以建立批次。' })}
            </p>
            <Button
              onClick={() => navigate('/upload')}
              size="lg"
            >
              {t('processing.goToUpload', { defaultValue: '前往上傳頁面' })}
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  const isProcessing = batchStatus?.batch.status === 'processing'
  const isCompleted = batchStatus?.batch.status === 'completed'
  const isPending = !batchStatus || batchStatus.batch.status === 'pending'

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="page-header">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="page-title">{t('processing.title')}</h1>
            <p className="text-muted-foreground mt-1">
              批次 ID: <span className="font-mono text-primary">{batchId}</span> · 共 {files.length} 個檔案
            </p>
          </div>
          <div>
            {isCompleted && (
              <div className="flex items-center gap-2 text-success">
                <CheckCircle className="w-6 h-6" />
                <span className="font-semibold">處理完成</span>
              </div>
            )}
            {isProcessing && (
              <div className="flex items-center gap-2 text-primary">
                <Loader2 className="w-6 h-6 animate-spin" />
                <span className="font-semibold">處理中</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Overall Progress */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-primary/10 rounded-lg">
                <Activity className="w-5 h-5 text-primary" />
              </div>
              <CardTitle>{t('processing.progress')}</CardTitle>
            </div>
            {batchStatus && getStatusBadge(batchStatus.batch.status)}
          </div>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Progress bar */}
          <div>
            <div className="flex justify-between text-sm mb-3">
              <span className="text-muted-foreground font-medium">{t('processing.status')}</span>
              <span className="font-bold text-xl text-primary">
                {batchStatus?.batch.progress_percentage || 0}%
              </span>
            </div>
            <Progress value={batchStatus?.batch.progress_percentage || 0} max={100} className="h-4" />
          </div>

          {/* Stats */}
          {batchStatus && (
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div className="p-4 bg-muted/30 rounded-lg border border-border">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-success/10 rounded-lg">
                    <CheckCircle className="w-5 h-5 text-success" />
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-0.5">已完成</p>
                    <p className="text-2xl font-bold text-foreground">
                      {batchStatus.files.filter((f) => f.status === 'completed').length}
                    </p>
                  </div>
                </div>
              </div>
              <div className="p-4 bg-muted/30 rounded-lg border border-border">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-primary/10 rounded-lg">
                    <Loader2 className="w-5 h-5 text-primary" />
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-0.5">處理中</p>
                    <p className="text-2xl font-bold text-foreground">
                      {batchStatus.files.filter((f) => f.status === 'processing').length}
                    </p>
                  </div>
                </div>
              </div>
              <div className="p-4 bg-muted/30 rounded-lg border border-border">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-destructive/10 rounded-lg">
                    <AlertCircle className="w-5 h-5 text-destructive" />
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-0.5">失敗</p>
                    <p className="text-2xl font-bold text-foreground">
                      {batchStatus.files.filter((f) => f.status === 'failed').length}
                    </p>
                  </div>
                </div>
              </div>
              <div className="p-4 bg-muted/30 rounded-lg border border-border">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-muted rounded-lg">
                    <FileText className="w-5 h-5 text-muted-foreground" />
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-0.5">總計</p>
                    <p className="text-2xl font-bold text-foreground">{batchStatus.files.length}</p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Action buttons */}
          {(isPending || isCompleted) && (
            <div className="flex gap-3 pt-4 border-t border-border">
              {isPending && (
                <Button
                  onClick={handleStartProcessing}
                  disabled={processOCRMutation.isPending}
                  className="gap-2"
                  size="lg"
                >
                  {processOCRMutation.isPending ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      {t('processing.processing')}
                    </>
                  ) : (
                    <>
                      <Play className="w-4 h-4" />
                      {t('processing.startProcessing')}
                    </>
                  )}
                </Button>
              )}

              {isCompleted && (
                <Button
                  onClick={handleViewResults}
                  className="gap-2"
                  size="lg"
                >
                  <CheckCircle className="w-4 h-4" />
                  {t('common.next')}
                </Button>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* File List */}
      {batchStatus && (
        <Card>
          <CardHeader>
            <div className="flex items-center gap-3">
              <div className="p-2 bg-primary/10 rounded-lg">
                <FileText className="w-5 h-5 text-primary" />
              </div>
              <CardTitle>檔案處理狀態</CardTitle>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {batchStatus.files.map((file) => (
                <div
                  key={file.id}
                  className="flex items-center justify-between p-4 rounded-lg border border-border hover:bg-muted/50 transition-colors"
                >
                  <div className="flex items-center gap-4 flex-1 min-w-0">
                    <div className={`p-2 rounded-lg ${
                      file.status === 'completed' ? 'bg-success/10' :
                      file.status === 'processing' ? 'bg-primary/10' :
                      file.status === 'failed' ? 'bg-destructive/10' :
                      'bg-muted'
                    }`}>
                      {file.status === 'completed' ? (
                        <CheckCircle className="w-5 h-5 text-success" />
                      ) : file.status === 'processing' ? (
                        <Loader2 className="w-5 h-5 text-primary animate-spin" />
                      ) : file.status === 'failed' ? (
                        <AlertCircle className="w-5 h-5 text-destructive" />
                      ) : (
                        <FileText className="w-5 h-5 text-muted-foreground" />
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-foreground truncate">
                        {file.filename}
                      </p>
                      <div className="flex items-center gap-3 mt-1">
                        {file.processing_time && (
                          <p className="text-xs text-muted-foreground flex items-center gap-1">
                            <Clock className="w-3 h-3" />
                            處理時間: {file.processing_time.toFixed(2)}s
                          </p>
                        )}
                        {file.error && (
                          <p className="text-xs text-destructive flex items-center gap-1">
                            <AlertCircle className="w-3 h-3" />
                            {file.error}
                          </p>
                        )}
                      </div>
                    </div>
                  </div>
                  {getStatusBadge(file.status)}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
