'use client'

/**
 * DSFA Document Manager
 *
 * Manages DSFA-related sources and documents for the RAG pipeline.
 */

import { useState, useEffect } from 'react'
import Link from 'next/link'
import {
  ArrowLeft,
  RefreshCw,
  Upload,
  FileText,
  Database,
  Search,
  Filter,
  AlertCircle,
  BookOpen,
} from 'lucide-react'
import { DSFASource, DSFACorpusStats, DSFASourceStats } from '@/lib/sdk/types'

import {
  fetchSources,
  fetchStats,
  initializeCorpus,
  triggerIngestion,
  MOCK_SOURCES,
  MOCK_STATS,
} from './_components/dsfa-api'
import { LicenseBadge } from './_components/DSFABadges'
import { SourceCard } from './_components/SourceCard'
import { StatsOverview } from './_components/StatsOverview'

export default function DSFADocumentManagerPage() {
  const [sources, setSources] = useState<DSFASource[]>([])
  const [stats, setStats] = useState<DSFACorpusStats | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [filterType, setFilterType] = useState<string>('all')
  const [ingestingSource, setIngestingSource] = useState<string | null>(null)
  const [isInitializing, setIsInitializing] = useState(false)

  useEffect(() => {
    async function loadData() {
      setIsLoading(true)
      try {
        const [sourcesData, statsData] = await Promise.all([
          fetchSources(),
          fetchStats(),
        ])
        setSources(sourcesData)
        setStats(statsData)
        setError(null)
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load data')
        setSources(MOCK_SOURCES)
        setStats(MOCK_STATS)
      } finally {
        setIsLoading(false)
      }
    }
    loadData()
  }, [])

  const handleInitialize = async () => {
    setIsInitializing(true)
    try {
      await initializeCorpus()
      const [sourcesData, statsData] = await Promise.all([
        fetchSources(),
        fetchStats(),
      ])
      setSources(sourcesData)
      setStats(statsData)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to initialize')
    } finally {
      setIsInitializing(false)
    }
  }

  const handleIngest = async (sourceCode: string) => {
    setIngestingSource(sourceCode)
    try {
      await triggerIngestion(sourceCode)
      const statsData = await fetchStats()
      setStats(statsData)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to ingest')
    } finally {
      setIngestingSource(null)
    }
  }

  // Filter sources
  const filteredSources = sources.filter(source => {
    const matchesSearch = searchQuery === '' ||
      source.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      source.sourceCode.toLowerCase().includes(searchQuery.toLowerCase()) ||
      source.organization?.toLowerCase().includes(searchQuery.toLowerCase())

    const matchesType = filterType === 'all' || source.documentType === filterType

    return matchesSearch && matchesType
  })

  const getStatsForSource = (sourceCode: string): DSFASourceStats | undefined => {
    return stats?.sources.find(s => s.sourceCode === sourceCode)
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 p-8">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <Link
            href="/ai/rag-pipeline"
            className="inline-flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white mb-4"
          >
            <ArrowLeft className="w-4 h-4" />
            Zurueck zur RAG-Pipeline
          </Link>

          <div className="flex justify-between items-start">
            <div>
              <h1 className="text-3xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
                <BookOpen className="w-8 h-8 text-blue-600" />
                DSFA-Quellen Manager
              </h1>
              <p className="text-gray-500 dark:text-gray-400 mt-1">
                Verwalten Sie DSFA-Guidance Dokumente mit vollstaendiger Lizenzattribution
              </p>
            </div>

            <div className="flex gap-2">
              <button
                onClick={handleInitialize}
                disabled={isInitializing}
                className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 disabled:opacity-50 flex items-center gap-2"
              >
                {isInitializing ? (
                  <RefreshCw className="w-4 h-4 animate-spin" />
                ) : (
                  <Database className="w-4 h-4" />
                )}
                Initialisieren
              </button>
              <button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2">
                <Upload className="w-4 h-4" />
                Dokument hochladen
              </button>
            </div>
          </div>
        </div>

        {/* Error Banner */}
        {error && (
          <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-700 rounded-xl">
            <div className="flex items-center gap-3">
              <AlertCircle className="w-5 h-5 text-red-500" />
              <span className="text-red-800 dark:text-red-200">{error}</span>
              <button
                onClick={() => setError(null)}
                className="ml-auto text-red-600 hover:text-red-800"
              >
                &times;
              </button>
            </div>
          </div>
        )}

        {/* Stats Overview */}
        {stats && <StatsOverview stats={stats} />}

        {/* Search & Filter */}
        <div className="mt-6 flex gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder="Quellen durchsuchen..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800"
            />
          </div>
          <div className="relative">
            <Filter className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <select
              value={filterType}
              onChange={(e) => setFilterType(e.target.value)}
              className="pl-9 pr-8 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 appearance-none"
            >
              <option value="all">Alle Typen</option>
              <option value="guideline">Leitlinien</option>
              <option value="checklist">Prueflisten</option>
              <option value="regulation">Verordnungen</option>
            </select>
          </div>
        </div>

        {/* Sources List */}
        <div className="mt-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
              Registrierte Quellen ({filteredSources.length})
            </h2>
          </div>

          {isLoading ? (
            <div className="flex items-center justify-center py-20">
              <div className="text-center">
                <div className="w-12 h-12 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin mx-auto mb-4" />
                <p className="text-gray-500 dark:text-gray-400">Lade Quellen...</p>
              </div>
            </div>
          ) : filteredSources.length === 0 ? (
            <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
              <FileText className="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-500 dark:text-gray-400">
                {searchQuery || filterType !== 'all'
                  ? 'Keine Quellen gefunden'
                  : 'Noch keine Quellen registriert'}
              </p>
              {!searchQuery && filterType === 'all' && (
                <button
                  onClick={handleInitialize}
                  className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  Quellen initialisieren
                </button>
              )}
            </div>
          ) : (
            <div className="grid gap-4">
              {filteredSources.map(source => (
                <SourceCard
                  key={source.id}
                  source={source}
                  stats={getStatsForSource(source.sourceCode)}
                  onIngest={() => handleIngest(source.sourceCode)}
                  isIngesting={ingestingSource === source.sourceCode}
                />
              ))}
            </div>
          )}
        </div>

        {/* Info Box */}
        <div className="mt-8 p-6 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-xl">
          <h3 className="font-semibold text-blue-900 dark:text-blue-100 mb-2">
            Ueber die Lizenzattribution
          </h3>
          <p className="text-sm text-blue-800 dark:text-blue-200 mb-4">
            Alle DSFA-Quellen werden mit vollstaendiger Lizenzinformation gespeichert.
            Bei der Nutzung der RAG-Suche werden automatisch die korrekten Attributionen angezeigt.
          </p>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-3 text-sm">
            <div className="flex items-center gap-2">
              <LicenseBadge licenseCode="DL-DE-BY-2.0" />
              <span className="text-blue-700 dark:text-blue-300">Namensnennung</span>
            </div>
            <div className="flex items-center gap-2">
              <LicenseBadge licenseCode="DL-DE-ZERO-2.0" />
              <span className="text-blue-700 dark:text-blue-300">Keine Attribution</span>
            </div>
            <div className="flex items-center gap-2">
              <LicenseBadge licenseCode="CC-BY-4.0" />
              <span className="text-blue-700 dark:text-blue-300">CC Attribution</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
