import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { 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 { apiClientV2 } from '@/services/apiV2'
import { Play, CheckCircle, FileText, AlertCircle, Clock, Activity, Loader2 } from 'lucide-react'
import PPStructureParams from '@/components/PPStructureParams'
import TaskNotFound from '@/components/TaskNotFound'
import { useTaskValidation } from '@/hooks/useTaskValidation'
import type { PPStructureV3Params, ProcessingOptions } from '@/types/apiV2'

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

  // Use shared hook for task validation
  const { taskId, taskDetail, isLoading: isValidating, isNotFound, clearAndReset } = useTaskValidation({
    refetchInterval: (query) => {
      const data = query.state.data
      if (!data) return 2000
      if (data.status === 'completed' || data.status === 'failed') {
        return false
      }
      return 2000
    },
  })

  // PP-StructureV3 parameters state
  const [ppStructureParams, setPpStructureParams] = useState<PPStructureV3Params>({})

  // Start OCR processing
  const processOCRMutation = useMutation({
    mutationFn: () => {
      const options: ProcessingOptions = {
        use_dual_track: true,
        language: 'ch',
      }

      // Only include pp_structure_params if user has customized them
      if (Object.keys(ppStructureParams).length > 0) {
        options.pp_structure_params = ppStructureParams
      }

      return apiClientV2.startTask(taskId!, options)
    },
    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',
      })
    },
  })

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

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

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

  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>
    }
  }

  const getProgressPercentage = (status: string) => {
    switch (status) {
      case 'completed':
        return 100
      case 'processing':
        return 50
      case 'failed':
        return 100
      default:
        return 0
    }
  }

  // Show loading while validating task
  if (isValidating) {
    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>
    )
  }

  // Show message when task was deleted
  if (isNotFound) {
    return <TaskNotFound taskId={taskId} onClearAndUpload={clearAndReset} />
  }

  // Show helpful message when no task is selected
  if (!taskId) {
    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 = taskDetail?.status === 'processing'
  const isCompleted = taskDetail?.status === 'completed'
  const isPending = !taskDetail || taskDetail.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">{taskId}</span>
              {taskDetail?.filename && ` · ${taskDetail.filename}`}
            </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>
            {taskDetail && getStatusBadge(taskDetail.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">
                {taskDetail ? getProgressPercentage(taskDetail.status) : 0}%
              </span>
            </div>
            <Progress
              value={taskDetail ? getProgressPercentage(taskDetail.status) : 0}
              max={100}
              className="h-4"
            />
          </div>

          {/* Task Info */}
          {taskDetail && (
            <div className="grid grid-cols-1 md:grid-cols-2 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-primary/10 rounded-lg">
                    <FileText className="w-5 h-5 text-primary" />
                  </div>
                  <div>
                    <p className="text-xs text-muted-foreground mb-0.5">檔案名稱</p>
                    <p className="text-sm font-medium text-foreground truncate">
                      {taskDetail.filename || '未知檔案'}
                    </p>
                  </div>
                </div>
              </div>
              {taskDetail.processing_time_ms && (
                <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">
                      <Clock className="w-5 h-5 text-success" />
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground mb-0.5">處理時間</p>
                      <p className="text-sm font-medium text-foreground">
                        {(taskDetail.processing_time_ms / 1000).toFixed(2)}s
                      </p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Error message */}
          {taskDetail?.error_message && (
            <div className="p-4 bg-destructive/10 rounded-lg border border-destructive/20">
              <div className="flex items-start gap-3">
                <AlertCircle className="w-5 h-5 text-destructive flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-medium text-destructive mb-1">處理失敗</p>
                  <p className="text-sm text-destructive/80">{taskDetail.error_message}</p>
                </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" />
                  查看任務歷史
                </Button>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Task Details Card */}
      {taskDetail && (
        <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-3">
              <div className="flex justify-between py-2 border-b border-border">
                <span className="text-sm text-muted-foreground">任務狀態</span>
                {getStatusBadge(taskDetail.status)}
              </div>
              <div className="flex justify-between py-2 border-b border-border">
                <span className="text-sm text-muted-foreground">建立時間</span>
                <span className="text-sm font-medium">
                  {new Date(taskDetail.created_at).toLocaleString('zh-TW')}
                </span>
              </div>
              {taskDetail.updated_at && (
                <div className="flex justify-between py-2 border-b border-border">
                  <span className="text-sm text-muted-foreground">更新時間</span>
                  <span className="text-sm font-medium">
                    {new Date(taskDetail.updated_at).toLocaleString('zh-TW')}
                  </span>
                </div>
              )}
              {taskDetail.completed_at && (
                <div className="flex justify-between py-2 border-b border-border">
                  <span className="text-sm text-muted-foreground">完成時間</span>
                  <span className="text-sm font-medium">
                    {new Date(taskDetail.completed_at).toLocaleString('zh-TW')}
                  </span>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* PP-StructureV3 Parameters (only show when task is pending) */}
      {isPending && (
        <PPStructureParams
          value={ppStructureParams}
          onChange={setPpStructureParams}
          disabled={processOCRMutation.isPending}
        />
      )}
    </div>
  )
}
