import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useMutation, useQuery } from '@tanstack/react-query'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/toast'
import { useUploadStore } from '@/store/uploadStore'
import { apiClient } from '@/services/api'
import type { ExportRequest, ExportOptions } from '@/types/api'
import {
  Download,
  FileText,
  FileJson,
  FileSpreadsheet,
  FileCode,
  FileType,
  AlertCircle,
  Settings,
  CheckCircle2,
  ArrowLeft
} from 'lucide-react'

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

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

  const [format, setFormat] = useState<ExportFormat>('txt')
  const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>()
  const [options, setOptions] = useState<ExportOptions>({
    confidence_threshold: 0.5,
    include_metadata: true,
    filename_pattern: '{filename}_ocr',
    css_template: 'default',
  })

  // Fetch export rules
  const { data: exportRules } = useQuery({
    queryKey: ['exportRules'],
    queryFn: () => apiClient.getExportRules(),
    enabled: true,
  })

  // Fetch CSS templates
  const { data: cssTemplates } = useQuery({
    queryKey: ['cssTemplates'],
    queryFn: () => apiClient.getCSSTemplates(),
    enabled: format === 'pdf',
  })

  // Export mutation
  const exportMutation = useMutation({
    mutationFn: async (data: ExportRequest) => {
      const blob = await apiClient.exportResults(data)
      return { blob, format: data.format }
    },
    onSuccess: ({ blob, format: exportFormat }) => {
      // Create download link
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url

      // Determine file extension
      const extensions: Record<ExportFormat, string> = {
        txt: 'txt',
        json: 'json',
        excel: 'xlsx',
        markdown: 'md',
        pdf: 'pdf',
      }

      a.download = `batch_${batchId}_export.${extensions[exportFormat]}`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)

      toast({
        title: t('export.exportSuccess'),
        description: `已成功匯出為 ${exportFormat.toUpperCase()} 格式`,
        variant: 'success',
      })
    },
    onError: (error: any) => {
      toast({
        title: t('export.exportError'),
        description: error.response?.data?.detail || t('errors.networkError'),
        variant: 'destructive',
      })
    },
  })

  const handleExport = () => {
    if (!batchId) {
      toast({
        title: t('errors.validationError'),
        description: '請先上傳並處理檔案',
        variant: 'destructive',
      })
      return
    }

    const exportRequest: ExportRequest = {
      batch_id: batchId,
      format,
      rule_id: selectedRuleId,
      options,
    }

    exportMutation.mutate(exportRequest)
  }

  const handleFormatChange = (newFormat: ExportFormat) => {
    setFormat(newFormat)
    // Reset CSS template if switching away from PDF
    if (newFormat !== 'pdf') {
      setOptions((prev) => ({ ...prev, css_template: undefined }))
    } else {
      setOptions((prev) => ({ ...prev, css_template: 'default' }))
    }
  }

  const handleRuleChange = (ruleId: number | undefined) => {
    setSelectedRuleId(ruleId)
    if (ruleId && exportRules) {
      const rule = exportRules.find((r) => r.id === ruleId)
      if (rule && rule.config_json) {
        // Apply rule configuration
        setOptions((prev) => ({
          ...prev,
          ...rule.config_json,
          css_template: rule.css_template || prev.css_template,
        }))
      }
    }
  }

  const formatIcons = {
    txt: FileText,
    json: FileJson,
    excel: FileSpreadsheet,
    markdown: FileCode,
    pdf: FileType,
  }

  // 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('export.title')}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-muted-foreground">
              {t('export.noBatchMessage', { defaultValue: '尚未選擇任何批次。請先上傳並完成處理檔案。' })}
            </p>
            <Button onClick={() => navigate('/upload')} size="lg">
              {t('export.goToUpload', { defaultValue: '前往上傳頁面' })}
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="page-header">
        <h1 className="page-title">{t('export.title')}</h1>
        <p className="text-muted-foreground mt-1">
          批次 ID: <span className="font-mono text-primary">{batchId}</span>
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Configuration */}
        <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" />
                {t('export.format')}
              </CardTitle>
              <CardDescription>選擇要匯出的檔案格式</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                {(['txt', 'json', 'excel', 'markdown', 'pdf'] as ExportFormat[]).map((fmt) => {
                  const Icon = formatIcons[fmt]
                  return (
                    <button
                      key={fmt}
                      onClick={() => handleFormatChange(fmt)}
                      className={`p-4 border-2 rounded-lg transition-all ${
                        format === 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 ${format === fmt ? 'text-primary' : 'text-muted-foreground'}`} />
                      <div className={`text-sm font-medium ${format === fmt ? 'text-primary' : 'text-foreground'}`}>
                        {t(`export.formats.${fmt}`)}
                      </div>
                    </button>
                  )
                })}
              </div>
            </CardContent>
          </Card>

          {/* Export Rules */}
          {exportRules && exportRules.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <CheckCircle2 className="w-5 h-5" />
                  {t('export.rules.title')}
                </CardTitle>
                <CardDescription>選擇預設的匯出規則</CardDescription>
              </CardHeader>
              <CardContent>
                <select
                  value={selectedRuleId || ''}
                  onChange={(e) => handleRuleChange(e.target.value ? Number(e.target.value) : undefined)}
                  className="w-full px-4 py-3 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-colors"
                >
                  <option value="">無 (使用預設設定)</option>
                  {exportRules.map((rule) => (
                    <option key={rule.id} value={rule.id}>
                      {rule.rule_name}
                    </option>
                  ))}
                </select>
              </CardContent>
            </Card>
          )}

          {/* Export Options */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Settings className="w-5 h-5" />
                {t('export.options.title')}
              </CardTitle>
              <CardDescription>自訂匯出參數</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Confidence Threshold */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <label className="text-sm font-medium text-foreground">
                    {t('export.options.confidenceThreshold')}
                  </label>
                  <span className="text-sm font-bold text-primary">
                    {(options.confidence_threshold * 100).toFixed(0)}%
                  </span>
                </div>
                <input
                  type="range"
                  min="0"
                  max="1"
                  step="0.05"
                  value={options.confidence_threshold}
                  onChange={(e) =>
                    setOptions((prev) => ({
                      ...prev,
                      confidence_threshold: Number(e.target.value),
                    }))
                  }
                  className="w-full h-2 bg-muted rounded-lg appearance-none cursor-pointer accent-primary"
                />
                <div className="flex justify-between text-xs text-muted-foreground mt-2">
                  <span>0%</span>
                  <span>50%</span>
                  <span>100%</span>
                </div>
              </div>

              {/* Include Metadata */}
              <div className="flex items-center p-4 bg-muted/30 rounded-lg">
                <input
                  type="checkbox"
                  id="include-metadata"
                  checked={options.include_metadata}
                  onChange={(e) =>
                    setOptions((prev) => ({
                      ...prev,
                      include_metadata: e.target.checked,
                    }))
                  }
                  className="w-5 h-5 border border-border rounded accent-primary"
                />
                <label htmlFor="include-metadata" className="ml-3 text-sm font-medium text-foreground cursor-pointer">
                  {t('export.options.includeMetadata')}
                </label>
              </div>

              {/* Filename Pattern */}
              <div>
                <label className="block text-sm font-medium text-foreground mb-2">
                  {t('export.options.filenamePattern')}
                </label>
                <input
                  type="text"
                  value={options.filename_pattern}
                  onChange={(e) =>
                    setOptions((prev) => ({
                      ...prev,
                      filename_pattern: e.target.value,
                    }))
                  }
                  className="w-full px-4 py-3 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-colors font-mono text-sm"
                  placeholder="{filename}_ocr"
                />
                <p className="text-xs text-muted-foreground mt-2">
                  可用變數: <code className="bg-muted px-1.5 py-0.5 rounded">{'{filename}'}</code>,{' '}
                  <code className="bg-muted px-1.5 py-0.5 rounded">{'{batch_id}'}</code>,{' '}
                  <code className="bg-muted px-1.5 py-0.5 rounded">{'{date}'}</code>
                </p>
              </div>

              {/* CSS Template (PDF only) */}
              {format === 'pdf' && cssTemplates && cssTemplates.length > 0 && (
                <div>
                  <label className="block text-sm font-medium text-foreground mb-2">
                    {t('export.options.cssTemplate')}
                  </label>
                  <select
                    value={options.css_template || 'default'}
                    onChange={(e) =>
                      setOptions((prev) => ({
                        ...prev,
                        css_template: e.target.value,
                      }))
                    }
                    className="w-full px-4 py-3 border border-border rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-colors"
                  >
                    {cssTemplates.map((template) => (
                      <option key={template.filename} value={template.filename}>
                        {template.name} - {template.description}
                      </option>
                    ))}
                  </select>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Right Column - Preview */}
        <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[format]
                      return <Icon className="w-4 h-4 text-primary" />
                    })()}
                    <span className="text-sm font-medium text-foreground">{format.toUpperCase()}</span>
                  </div>
                </div>

                {selectedRuleId && exportRules && (
                  <div>
                    <div className="text-xs text-muted-foreground mb-1">匯出規則</div>
                    <div className="text-sm font-medium text-foreground">
                      {exportRules.find((r) => r.id === selectedRuleId)?.rule_name || '未選擇'}
                    </div>
                  </div>
                )}

                <div>
                  <div className="text-xs text-muted-foreground mb-1">準確率門檻</div>
                  <div className="text-sm font-medium text-foreground">
                    {(options.confidence_threshold * 100).toFixed(0)}%
                  </div>
                </div>

                <div>
                  <div className="text-xs text-muted-foreground mb-1">包含元數據</div>
                  <div className="text-sm font-medium text-foreground">
                    {options.include_metadata ? '是' : '否'}
                  </div>
                </div>

                <div>
                  <div className="text-xs text-muted-foreground mb-1">檔名模式</div>
                  <div className="text-xs font-mono bg-background px-2 py-1 rounded border border-border">
                    {options.filename_pattern || '{filename}_ocr'}
                  </div>
                </div>
              </div>

              <div className="flex flex-col gap-2">
                <Button
                  onClick={handleExport}
                  disabled={exportMutation.isPending}
                  className="w-full gap-2"
                  size="lg"
                >
                  {exportMutation.isPending ? (
                    <>
                      <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                      {t('export.exporting')}
                    </>
                  ) : (
                    <>
                      <Download className="w-4 h-4" />
                      {t('export.exportButton')}
                    </>
                  )}
                </Button>

                <Button
                  variant="outline"
                  onClick={() => navigate('/results')}
                  className="w-full gap-2"
                >
                  <ArrowLeft className="w-4 h-4" />
                  {t('common.back')}
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}
