import { useEffect, useState } from 'react'
import { api } from '../api/client'
import { Layout } from '../components/Layout'

interface Me {
  id: string
  first_name: string
  last_name: string
  role: string
}

interface ImportRowResult {
  row: number
  email: string
  personnel_number: string | null
  action: 'created' | 'reactivated' | 'error' | 'skipped'
  message: string | null
}

interface ImportResult {
  total_rows: number
  created: number
  reactivated: number
  errors: number
  items: ImportRowResult[]
}

const ACTION_LABEL: Record<string, { text: string; color: string }> = {
  created: { text: 'Neu',          color: 'bg-green-100 text-green-700' },
  reactivated: { text: 'Reaktiviert', color: 'bg-blue-100 text-blue-700' },
  error: { text: 'Fehler',         color: 'bg-red-100 text-red-700' },
  skipped: { text: 'Übersprungen', color: 'bg-gray-100 text-gray-600' },
}

export default function UserImportPage() {
  const [me, setMe] = useState<Me | null>(null)
  const [file, setFile] = useState<File | null>(null)
  const [preview, setPreview] = useState<ImportResult | null>(null)
  const [result, setResult] = useState<ImportResult | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    api.get<Me>('/auth/me').then(setMe).catch(() => {})
  }, [])

  function downloadTemplate() {
    // Endpoint mit Auth-Header öffnen → wir laden via fetch und triggern Download
    const token = localStorage.getItem('access_token')
    fetch('/api/v1/users/import-template.csv', {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
    })
      .then(r => r.blob())
      .then(blob => {
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = 'user-import-template.csv'
        a.click()
        URL.revokeObjectURL(url)
      })
      .catch(e => setError(e instanceof Error ? e.message : 'Download fehlgeschlagen'))
  }

  async function loadPreview() {
    if (!file) return
    setLoading(true)
    setError(null)
    setResult(null)
    setPreview(null)
    try {
      const form = new FormData()
      form.append('file', file)
      const r = await api.postForm<ImportResult>('/users/import/preview', form)
      setPreview(r)
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Fehler bei der Vorschau')
    } finally {
      setLoading(false)
    }
  }

  async function applyImport() {
    if (!file) return
    if (!confirm(`Import wirklich ausführen? ${preview?.total_rows ?? '?'} Zeilen werden verarbeitet.`)) return
    setLoading(true)
    setError(null)
    try {
      const form = new FormData()
      form.append('file', file)
      const r = await api.postForm<ImportResult>('/users/import/apply', form)
      setResult(r)
      setPreview(null)
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Fehler beim Import')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Layout userRole={me?.role ?? ''} userName={me ? `${me.first_name} ${me.last_name}` : ''}>
      <div className='max-w-4xl mx-auto space-y-6'>
        <div className='flex items-center justify-between'>
          <h1 className='text-2xl font-bold text-gray-900'>Mitarbeiter-Import (CSV)</h1>
          <button
            onClick={downloadTemplate}
            className='px-4 py-2 text-sm font-medium text-blue-600 border border-blue-200 rounded-lg hover:bg-blue-50'
          >
            Vorlage herunterladen
          </button>
        </div>

        <div className='bg-white rounded-xl shadow-sm border border-gray-200 p-6 space-y-4'>
          <p className='text-sm text-gray-600'>
            Lade eine CSV-Datei mit Mitarbeitern hoch. Pflicht-Spalten: <code className='font-mono text-xs bg-gray-100 px-1 rounded'>email, first_name, last_name</code>.
            Optional: <code className='font-mono text-xs bg-gray-100 px-1 rounded'>role, personnel_number, kuerzel</code>.
          </p>
          <ul className='text-xs text-gray-500 list-disc pl-5 space-y-1'>
            <li>Doppelte E-Mail im Import → Fehler.</li>
            <li>Existiert die E-Mail bereits aber deaktiviert → Reaktivierung mit neuen Daten.</li>
            <li>Leere Personalnr. → Auto-Vergabe (auch im manuellen Modus).</li>
            <li>Personalnr. nur Ziffern; Konflikt mit reservierten Nummern wird abgelehnt.</li>
          </ul>

          <div className='flex items-center gap-3 pt-2'>
            <input
              type='file'
              accept='.csv,text/csv'
              onChange={e => { setFile(e.target.files?.[0] ?? null); setPreview(null); setResult(null) }}
              className='text-sm'
            />
            <button
              onClick={loadPreview}
              disabled={!file || loading}
              className='px-4 py-2 bg-gray-700 text-white text-sm font-medium rounded-lg hover:bg-gray-800 disabled:opacity-50'
            >
              {loading && !preview ? 'Prüfe…' : 'Vorschau'}
            </button>
            {preview && (
              <button
                onClick={applyImport}
                disabled={loading || preview.errors > 0}
                className='px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50'
                title={preview.errors > 0 ? 'Erst alle Fehler beheben' : ''}
              >
                {loading ? 'Importiere…' : `Importieren (${preview.total_rows - preview.errors})`}
              </button>
            )}
          </div>

          {error && (
            <div className='bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700'>{error}</div>
          )}
        </div>

        {(preview || result) && (
          <div className='bg-white rounded-xl shadow-sm border border-gray-200 p-6'>
            <div className='flex items-center justify-between mb-4'>
              <h2 className='font-semibold text-gray-700'>{result ? 'Import-Ergebnis' : 'Vorschau'}</h2>
              <div className='flex gap-2 text-xs'>
                <span className='px-2 py-1 rounded bg-green-50 text-green-700'>
                  {(result ?? preview)!.created} Neu
                </span>
                <span className='px-2 py-1 rounded bg-blue-50 text-blue-700'>
                  {(result ?? preview)!.reactivated} Reaktiviert
                </span>
                <span className='px-2 py-1 rounded bg-red-50 text-red-700'>
                  {(result ?? preview)!.errors} Fehler
                </span>
              </div>
            </div>
            <div className='overflow-x-auto'>
              <table className='w-full text-sm'>
                <thead className='bg-gray-50 text-gray-500 text-xs uppercase'>
                  <tr>
                    <th className='px-3 py-2 text-left'>Zeile</th>
                    <th className='px-3 py-2 text-left'>Aktion</th>
                    <th className='px-3 py-2 text-left'>E-Mail</th>
                    <th className='px-3 py-2 text-left'>Pers.-Nr.</th>
                    <th className='px-3 py-2 text-left'>Meldung</th>
                  </tr>
                </thead>
                <tbody className='divide-y divide-gray-100'>
                  {(result ?? preview)!.items.map((it, i) => (
                    <tr key={i} className={it.action === 'error' ? 'bg-red-50/50' : ''}>
                      <td className='px-3 py-2 text-gray-500'>{it.row}</td>
                      <td className='px-3 py-2'>
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${ACTION_LABEL[it.action]?.color ?? 'bg-gray-100 text-gray-600'}`}>
                          {ACTION_LABEL[it.action]?.text ?? it.action}
                        </span>
                      </td>
                      <td className='px-3 py-2 text-gray-700'>{it.email || '—'}</td>
                      <td className='px-3 py-2 font-mono text-xs text-gray-600'>{it.personnel_number || '—'}</td>
                      <td className='px-3 py-2 text-xs text-gray-500'>{it.message || ''}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </Layout>
  )
}
