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

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

  // Show helpful message when no batch is selected
  if (!batchId) {
    return (
      <div className="max-w-2xl mx-auto mt-12">
        <Card>
          <CardHeader>
            <CardTitle>{t('export.title')}</CardTitle>
          </CardHeader>
          <CardContent className="text-center space-y-4">
            <p className="text-muted-foreground">
              {t('export.noBatchMessage', { defaultValue: '尚未選擇任何批次。請先上傳並完成處理檔案。' })}
            </p>
            <Button onClick={() => navigate('/upload')}>
              {t('export.goToUpload', { defaultValue: '前往上傳頁面' })}
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground mb-2">{t('export.title')}</h1>
        <p className="text-muted-foreground">批次 ID: {batchId}</p>
      </div>

      {/* Format Selection */}
      <Card>
        <CardHeader>
          <CardTitle>{t('export.format')}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
            {(['txt', 'json', 'excel', 'markdown', 'pdf'] as ExportFormat[]).map((fmt) => (
              <button
                key={fmt}
                onClick={() => handleFormatChange(fmt)}
                className={`p-4 border rounded-lg text-center transition-colors ${
                  format === fmt
                    ? 'border-primary bg-primary/10 text-primary font-semibold'
                    : 'border-gray-200 hover:border-primary/50'
                }`}
              >
                <div className="text-sm">{t(`export.formats.${fmt}`)}</div>
              </button>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Export Rules */}
      {exportRules && exportRules.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>{t('export.rules.title')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <label className="block text-sm font-medium text-foreground">
                {t('export.rules.selectRule')}
              </label>
              <select
                value={selectedRuleId || ''}
                onChange={(e) => handleRuleChange(e.target.value ? Number(e.target.value) : undefined)}
                className="w-full px-3 py-2 border border-gray-200 rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              >
                <option value="">無 (使用預設設定)</option>
                {exportRules.map((rule) => (
                  <option key={rule.id} value={rule.id}>
                    {rule.rule_name}
                  </option>
                ))}
              </select>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Export Options */}
      <Card>
        <CardHeader>
          <CardTitle>{t('export.options.title')}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Confidence Threshold */}
          <div>
            <label className="block text-sm font-medium text-foreground mb-2">
              {t('export.options.confidenceThreshold')}: {options.confidence_threshold}
            </label>
            <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"
            />
            <div className="flex justify-between text-xs text-muted-foreground mt-1">
              <span>0</span>
              <span>0.5</span>
              <span>1.0</span>
            </div>
          </div>

          {/* Include Metadata */}
          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="include-metadata"
              checked={options.include_metadata}
              onChange={(e) =>
                setOptions((prev) => ({
                  ...prev,
                  include_metadata: e.target.checked,
                }))
              }
              className="w-4 h-4 border border-gray-200 rounded"
            />
            <label htmlFor="include-metadata" className="text-sm font-medium text-foreground">
              {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-3 py-2 border border-gray-200 rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              placeholder="{filename}_ocr"
            />
            <p className="text-xs text-muted-foreground mt-1">
              可用變數: {'{filename}'}, {'{batch_id}'}, {'{date}'}
            </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-3 py-2 border border-gray-200 rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              >
                {cssTemplates.map((template) => (
                  <option key={template.filename} value={template.filename}>
                    {template.name} - {template.description}
                  </option>
                ))}
              </select>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Export Button */}
      <div className="flex justify-end gap-3">
        <Button variant="outline" onClick={() => navigate('/results')}>
          {t('common.back')}
        </Button>
        <Button onClick={handleExport} disabled={exportMutation.isPending}>
          {exportMutation.isPending ? t('export.exporting') : t('export.exportButton')}
        </Button>
      </div>
    </div>
  )
}
