'use client'

/**
 * Middleware Admin - Rate Limiting, IP Whitelist/Blacklist, Events
 *
 * Manage middleware configurations and monitor events
 * Migrated from old admin (/admin/middleware)
 */

import { useEffect, useState, useCallback } from 'react'
import { PagePurpose } from '@/components/common/PagePurpose'
import type { MiddlewareConfig, RateLimitIP, MiddlewareEvent, MiddlewareStats } from './types'
import { StatusOverview } from './_components/StatusOverview'
import { OverviewTab } from './_components/OverviewTab'
import { ConfigTab } from './_components/ConfigTab'
import { IpListTab } from './_components/IpListTab'
import { EventsTab } from './_components/EventsTab'
import { StatsTab } from './_components/StatsTab'

export default function MiddlewareAdminPage() {
  const [configs, setConfigs] = useState<MiddlewareConfig[]>([])
  const [ipList, setIpList] = useState<RateLimitIP[]>([])
  const [events, setEvents] = useState<MiddlewareEvent[]>([])
  const [stats, setStats] = useState<MiddlewareStats[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<'overview' | 'config' | 'ip-list' | 'events' | 'stats'>('overview')
  const [actionLoading, setActionLoading] = useState<string | null>(null)

  // IP Form
  const [newIP, setNewIP] = useState('')
  const [newIPType, setNewIPType] = useState<'whitelist' | 'blacklist'>('whitelist')
  const [newIPReason, setNewIPReason] = useState('')

  const fetchData = useCallback(async () => {
    setLoading(true)
    setError(null)

    try {
      const [configsRes, ipListRes, eventsRes, statsRes] = await Promise.all([
        fetch('/api/admin/middleware'),
        fetch('/api/admin/middleware/rate-limit/ip-list'),
        fetch('/api/admin/middleware/events?limit=50'),
        fetch('/api/admin/middleware/stats'),
      ])

      if (configsRes.ok) {
        setConfigs(await configsRes.json())
      }
      if (ipListRes.ok) {
        setIpList(await ipListRes.json())
      }
      if (eventsRes.ok) {
        setEvents(await eventsRes.json())
      }
      if (statsRes.ok) {
        setStats(await statsRes.json())
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Verbindung zum Backend fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchData()
  }, [fetchData])

  useEffect(() => {
    const interval = setInterval(fetchData, 30000)
    return () => clearInterval(interval)
  }, [fetchData])

  const toggleMiddleware = async (name: string, enabled: boolean) => {
    setActionLoading(name)
    setError(null)

    try {
      const response = await fetch(`/api/admin/middleware/${name}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enabled }),
      })

      if (!response.ok) {
        throw new Error(`Fehler beim Aktualisieren: ${response.statusText}`)
      }

      // Update local state
      setConfigs(prev =>
        prev.map(c => (c.middleware_name === name ? { ...c, enabled } : c))
      )
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Aktualisierung fehlgeschlagen')
    } finally {
      setActionLoading(null)
    }
  }

  const addIP = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newIP.trim()) return

    setActionLoading('add-ip')
    setError(null)

    try {
      const response = await fetch('/api/admin/middleware/rate-limit/ip-list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ip_address: newIP.trim(),
          list_type: newIPType,
          reason: newIPReason.trim() || null,
        }),
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.detail || `Fehler: ${response.statusText}`)
      }

      const newEntry = await response.json()
      setIpList(prev => [newEntry, ...prev])
      setNewIP('')
      setNewIPReason('')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'IP konnte nicht hinzugefuegt werden')
    } finally {
      setActionLoading(null)
    }
  }

  const removeIP = async (id: string) => {
    setActionLoading(`remove-${id}`)
    setError(null)

    try {
      const response = await fetch(`/api/admin/middleware/rate-limit/ip-list/${id}`, {
        method: 'DELETE',
      })

      if (!response.ok) {
        throw new Error(`Fehler beim Loeschen: ${response.statusText}`)
      }

      setIpList(prev => prev.filter(ip => ip.id !== id))
    } catch (err) {
      setError(err instanceof Error ? err.message : 'IP konnte nicht entfernt werden')
    } finally {
      setActionLoading(null)
    }
  }

  const whitelistCount = ipList.filter(ip => ip.list_type === 'whitelist').length
  const blacklistCount = ipList.filter(ip => ip.list_type === 'blacklist').length

  return (
    <div>
      <PagePurpose
        title="Middleware Admin"
        purpose="Verwalten Sie die Middleware-Konfiguration, Rate Limiting und IP-Listen. Ueberwachen Sie Middleware-Events und Statistiken in Echtzeit."
        audience={['DevOps', 'Security', 'System-Admins']}
        gdprArticles={['Art. 32 (Sicherheit der Verarbeitung)']}
        architecture={{
          services: ['FastAPI Middleware Stack', 'PostgreSQL'],
          databases: ['middleware_config', 'rate_limit_ip_list', 'middleware_events'],
        }}
        relatedPages={[
          { name: 'Security', href: '/infrastructure/security', description: 'DevSecOps Dashboard' },
          { name: 'Mac Mini', href: '/infrastructure/mac-mini', description: 'Server-Monitoring' },
          { name: 'Controls', href: '/sdk/controls', description: 'Security Controls' },
        ]}
        collapsible={true}
        defaultCollapsed={true}
      />

      <StatusOverview
        configCount={configs.length}
        whitelistCount={whitelistCount}
        blacklistCount={blacklistCount}
        eventCount={events.length}
        loading={loading}
        onRefresh={fetchData}
      />

      {/* Tabs */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden mb-6">
        <div className="flex border-b border-slate-200 overflow-x-auto">
          {(['overview', 'config', 'ip-list', 'events', 'stats'] as const).map(tab => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`px-6 py-3 text-sm font-medium whitespace-nowrap transition-colors ${
                activeTab === tab
                  ? 'bg-orange-50 text-orange-700 border-b-2 border-orange-600'
                  : 'text-slate-600 hover:bg-slate-50'
              }`}
            >
              {tab === 'overview' && 'Uebersicht'}
              {tab === 'config' && 'Konfiguration'}
              {tab === 'ip-list' && `IP-Listen (${ipList.length})`}
              {tab === 'events' && 'Events'}
              {tab === 'stats' && 'Statistiken'}
            </button>
          ))}
        </div>

        <div className="p-6">
          {error && (
            <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg text-red-700">{error}</div>
          )}

          {loading ? (
            <div className="flex justify-center py-12">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-600" />
            </div>
          ) : (
            <>
              {activeTab === 'overview' && (
                <OverviewTab configs={configs} actionLoading={actionLoading} onToggle={toggleMiddleware} />
              )}
              {activeTab === 'config' && (
                <ConfigTab configs={configs} actionLoading={actionLoading} onToggle={toggleMiddleware} />
              )}
              {activeTab === 'ip-list' && (
                <IpListTab
                  ipList={ipList}
                  actionLoading={actionLoading}
                  newIP={newIP}
                  newIPType={newIPType}
                  newIPReason={newIPReason}
                  onNewIPChange={setNewIP}
                  onNewIPTypeChange={setNewIPType}
                  onNewIPReasonChange={setNewIPReason}
                  onAddIP={addIP}
                  onRemoveIP={removeIP}
                />
              )}
              {activeTab === 'events' && <EventsTab events={events} />}
              {activeTab === 'stats' && <StatsTab stats={stats} />}
            </>
          )}
        </div>
      </div>

      {/* Info Box */}
      <div className="bg-orange-50 border border-orange-200 rounded-xl p-4">
        <div className="flex gap-3">
          <svg className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <div>
            <h4 className="font-semibold text-orange-900">Middleware Stack</h4>
            <p className="text-sm text-orange-800 mt-1">
              Der Middleware Stack verarbeitet alle API-Anfragen in der konfigurierten Reihenfolge.
              Aenderungen an der Konfiguration werden sofort wirksam.
              Verwenden Sie die Whitelist fuer vertrauenswuerdige IPs und die Blacklist fuer bekannte Angreifer.
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
