'use client'

/**
 * Export tab: export training data in various formats.
 */

import { useState } from 'react'
import Link from 'next/link'
import { API_BASE } from '../constants'
import type { OCRSession, OCRStats } from '../types'

interface ExportTabProps {
  sessions: OCRSession[]
  selectedSession: string | null
  setSelectedSession: (id: string | null) => void
  stats: OCRStats | null
  setError: (error: string | null) => void
}

export function ExportTab({
  sessions,
  selectedSession,
  setSelectedSession,
  stats,
  setError,
}: ExportTabProps) {
  const [exportFormat, setExportFormat] = useState<'generic' | 'trocr' | 'llama_vision'>('generic')
  const [exporting, setExporting] = useState(false)
  const [exportResult, setExportResult] = useState<{
    exported_count: number
    batch_id: string
    samples?: Array<Record<string, unknown>>
  } | null>(null)

  const handleExport = async () => {
    setExporting(true)
    try {
      const res = await fetch(`${API_BASE}/api/v1/ocr-label/export`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          export_format: exportFormat,
          session_id: selectedSession,
        }),
      })

      if (res.ok) {
        const data = await res.json()
        setExportResult(data)
      } else {
        setError('Export fehlgeschlagen')
      }
    } catch {
      setError('Netzwerkfehler')
    } finally {
      setExporting(false)
    }
  }

  return (
    <div className="space-y-6">
      <div className="bg-white rounded-lg shadow p-6">
        <h3 className="text-lg font-semibold mb-4">Training-Daten exportieren</h3>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Export-Format</label>
            <select
              value={exportFormat}
              onChange={(e) => setExportFormat(e.target.value as typeof exportFormat)}
              className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary-500"
            >
              <option value="generic">Generic JSON</option>
              <option value="trocr">TrOCR Fine-Tuning</option>
              <option value="llama_vision">Llama Vision Fine-Tuning</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-1">Session (optional)</label>
            <select
              value={selectedSession || ''}
              onChange={(e) => setSelectedSession(e.target.value || null)}
              className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary-500"
            >
              <option value="">Alle Sessions</option>
              {sessions.map((session) => (
                <option key={session.id} value={session.id}>{session.name}</option>
              ))}
            </select>
          </div>

          <button
            onClick={handleExport}
            disabled={exporting || (stats?.exportable_items || 0) === 0}
            className="w-full px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50"
          >
            {exporting ? 'Exportiere...' : `${stats?.exportable_items || 0} Samples exportieren`}
          </button>

          {/* Cross-Link to Magic Help for TrOCR Fine-Tuning */}
          {exportFormat === 'trocr' && (stats?.exportable_items || 0) > 0 && (
            <Link
              href="/ai/magic-help?source=ocr-labeling"
              className="w-full mt-3 px-4 py-2 bg-purple-100 text-purple-700 border border-purple-300 rounded-lg hover:bg-purple-200 flex items-center justify-center gap-2 transition-colors"
            >
              <span>✨</span>
              Mit Magic Help testen & fine-tunen
            </Link>
          )}
        </div>
      </div>

      {exportResult && (
        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-semibold mb-4">Export-Ergebnis</h3>
          <div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-4">
            <p className="text-green-800">
              {exportResult.exported_count} Samples erfolgreich exportiert
            </p>
            <p className="text-sm text-green-600">
              Batch: {exportResult.batch_id}
            </p>
          </div>
          <div className="bg-slate-50 p-4 rounded-lg overflow-auto max-h-64">
            <pre className="text-xs">{JSON.stringify(exportResult.samples?.slice(0, 3), null, 2)}</pre>
            {(exportResult.samples?.length || 0) > 3 && (
              <p className="text-slate-500 mt-2">... und {(exportResult.samples?.length ?? 0) - 3} weitere</p>
            )}
          </div>
        </div>
      )}
    </div>
  )
}
