'use client'

import { useState } from 'react'
import type { IngestionStatus } from './types'
import { API_BASE } from './types'

export function IngestionTab({
  status,
  onRefresh,
}: {
  status: IngestionStatus | null
  onRefresh: () => void
}) {
  const [starting, setStarting] = useState(false)

  const startIngestion = async () => {
    setStarting(true)
    try {
      await fetch(`${API_BASE}/api/v1/admin/nibis/ingest`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ewh_only: true }),
      })
      onRefresh()
    } catch (err) {
      console.error('Failed to start ingestion:', err)
    } finally {
      setStarting(false)
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-slate-900">Ingestion Status</h2>
          <p className="text-sm text-slate-500">Übersicht über laufende und vergangene Indexierungsvorgänge</p>
        </div>
        <div className="flex gap-3">
          <button onClick={onRefresh} className="px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-300 rounded-lg hover:bg-slate-50">
            Aktualisieren
          </button>
          <button
            onClick={startIngestion}
            disabled={status?.running || starting}
            className="px-4 py-2 text-sm font-medium text-white bg-primary-600 rounded-lg hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {starting ? 'Startet...' : 'Ingestion starten'}
          </button>
        </div>
      </div>

      <div className="bg-white rounded-lg border border-slate-200 p-6">
        <div className="flex items-center gap-4 mb-4">
          {status?.running ? (
            <div className="w-3 h-3 bg-yellow-500 rounded-full animate-pulse"></div>
          ) : (
            <div className="w-3 h-3 bg-green-500 rounded-full"></div>
          )}
          <span className="text-lg font-medium text-slate-900">
            {status?.running ? 'Indexierung läuft...' : 'Bereit'}
          </span>
        </div>

        {status && (
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider">Letzte Ausführung</p>
              <p className="text-lg font-semibold text-slate-900">{status.lastRun ? new Date(status.lastRun).toLocaleString('de-DE') : '-'}</p>
            </div>
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider">Dokumente</p>
              <p className="text-lg font-semibold text-slate-900">{status.documentsIndexed ?? '-'}</p>
            </div>
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider">Chunks</p>
              <p className="text-lg font-semibold text-slate-900">{status.chunksCreated ?? '-'}</p>
            </div>
            <div>
              <p className="text-xs text-slate-500 uppercase tracking-wider">Fehler</p>
              <p className={`text-lg font-semibold ${status.errors.length > 0 ? 'text-red-600' : 'text-slate-900'}`}>{status.errors.length}</p>
            </div>
          </div>
        )}

        {status?.errors && status.errors.length > 0 && (
          <div className="mt-4 p-4 bg-red-50 rounded-lg">
            <h4 className="text-sm font-medium text-red-800 mb-2">Fehler</h4>
            <ul className="text-sm text-red-700 space-y-1">
              {status.errors.slice(0, 5).map((error, i) => (<li key={i}>{error}</li>))}
              {status.errors.length > 5 && (<li className="text-red-500">... und {status.errors.length - 5} weitere</li>)}
            </ul>
          </div>
        )}
      </div>
    </div>
  )
}
