'use client'

import React, { useState, useRef } from 'react'
import type { GroundTruthEntry } from '../_hooks/useBenchmark'

interface Props {
  onImport: (gt: { entries: GroundTruthEntry[]; source_file?: string; description?: string }) => Promise<void>
  loading: boolean
}

export function GTImportForm({ onImport, loading }: Props) {
  const [jsonText, setJsonText] = useState('')
  const [parseError, setParseError] = useState<string | null>(null)
  const [preview, setPreview] = useState<{ count: number; groups: Record<string, number> } | null>(null)
  const fileRef = useRef<HTMLInputElement>(null)

  function tryParse(text: string) {
    setJsonText(text)
    setParseError(null)
    setPreview(null)
    if (!text.trim()) return

    try {
      const parsed = JSON.parse(text)
      const entries: GroundTruthEntry[] = parsed.entries || parsed
      if (!Array.isArray(entries) || entries.length === 0) {
        setParseError('JSON muss ein Array "entries" enthalten')
        return
      }
      // Validate first entry has required fields
      const first = entries[0]
      if (!first.hazard_type && !first.hazard_group) {
        setParseError('Eintraege muessen hazard_type oder hazard_group enthalten')
        return
      }
      // Build preview
      const groups: Record<string, number> = {}
      for (const e of entries) {
        const g = e.hazard_group || 'Unbekannt'
        groups[g] = (groups[g] || 0) + 1
      }
      setPreview({ count: entries.length, groups })
    } catch (err) {
      setParseError('Ungueltiges JSON: ' + (err instanceof Error ? err.message : String(err)))
    }
  }

  async function handleImport() {
    if (!jsonText.trim()) return
    try {
      const parsed = JSON.parse(jsonText)
      const gt = parsed.entries ? parsed : { entries: parsed }
      await onImport(gt)
      setJsonText('')
      setPreview(null)
    } catch (err) {
      setParseError(err instanceof Error ? err.message : 'Import fehlgeschlagen')
    }
  }

  function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return
    const reader = new FileReader()
    reader.onload = (ev) => {
      const text = ev.target?.result as string
      tryParse(text)
    }
    reader.readAsText(file)
  }

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
      <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Ground Truth importieren</h3>
      <p className="text-xs text-gray-500 mb-3">
        JSON-Datei mit der professionellen Risikobeurteilung einfuegen oder hochladen.
      </p>

      <div className="flex gap-2 mb-3">
        <button
          onClick={() => fileRef.current?.click()}
          className="px-3 py-1.5 text-xs bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 rounded-md transition-colors"
        >
          JSON-Datei waehlen
        </button>
        <input ref={fileRef} type="file" accept=".json" onChange={handleFileUpload} className="hidden" />
      </div>

      <textarea
        value={jsonText}
        onChange={(e) => tryParse(e.target.value)}
        placeholder='{"entries": [...], "source_file": "...", "description": "..."}'
        rows={6}
        className="w-full text-xs font-mono border border-gray-300 dark:border-gray-600 rounded-md p-2 bg-gray-50 dark:bg-gray-900 text-gray-800 dark:text-gray-200 resize-y"
      />

      {parseError && (
        <div className="mt-2 px-3 py-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded text-xs text-red-600">
          {parseError}
        </div>
      )}

      {preview && (
        <div className="mt-2 px-3 py-2 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded text-xs text-green-700 dark:text-green-400">
          <strong>{preview.count} Eintraege</strong> erkannt:
          {Object.entries(preview.groups).map(([g, c]) => (
            <span key={g} className="ml-2">{g}: {c}</span>
          ))}
        </div>
      )}

      <button
        onClick={handleImport}
        disabled={loading || !preview}
        className="mt-3 w-full px-4 py-2 text-sm font-medium bg-purple-600 hover:bg-purple-700 disabled:bg-gray-300 text-white rounded-md transition-colors"
      >
        {loading ? 'Importiere...' : 'Ground Truth importieren'}
      </button>
    </div>
  )
}
