'use client'

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

import { PagePurpose } from '@/components/common/PagePurpose'
import { useMiddlewareAdmin } from './useMiddlewareAdmin'
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'
import type { TabId } from './types'

const TAB_LABELS: Record<TabId, string> = {
  overview: 'Uebersicht',
  config: 'Konfiguration',
  'ip-list': 'IP-Listen',
  events: 'Events',
  stats: 'Statistiken',
}

export default function MiddlewareAdminPage() {
  const mw = useMiddlewareAdmin()

  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}
      />

      {/* Stats Overview */}
      <div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-semibold text-slate-900">Middleware Status</h2>
          <button
            onClick={mw.fetchData}
            disabled={mw.loading}
            className="px-4 py-2 text-sm bg-orange-600 text-white rounded-lg hover:bg-orange-700 disabled:opacity-50 transition-colors"
          >
            {mw.loading ? 'Laden...' : 'Aktualisieren'}
          </button>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="bg-slate-50 rounded-lg p-4 border border-slate-200">
            <div className="text-2xl font-bold text-slate-900">{mw.configs.length}</div>
            <div className="text-sm text-slate-600">Middleware</div>
          </div>
          <div className="bg-green-50 rounded-lg p-4 border border-green-200">
            <div className="text-2xl font-bold text-green-600">{mw.whitelistCount}</div>
            <div className="text-sm text-slate-600">Whitelist IPs</div>
          </div>
          <div className="bg-red-50 rounded-lg p-4 border border-red-200">
            <div className="text-2xl font-bold text-red-600">{mw.blacklistCount}</div>
            <div className="text-sm text-slate-600">Blacklist IPs</div>
          </div>
          <div className="bg-blue-50 rounded-lg p-4 border border-blue-200">
            <div className="text-2xl font-bold text-blue-600">{mw.events.length}</div>
            <div className="text-sm text-slate-600">Recent Events</div>
          </div>
        </div>
      </div>

      {/* 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={() => mw.setActiveTab(tab)}
              className={`px-6 py-3 text-sm font-medium whitespace-nowrap transition-colors ${
                mw.activeTab === tab
                  ? 'bg-orange-50 text-orange-700 border-b-2 border-orange-600'
                  : 'text-slate-600 hover:bg-slate-50'
              }`}
            >
              {tab === 'ip-list' ? `${TAB_LABELS[tab]} (${mw.ipList.length})` : TAB_LABELS[tab]}
            </button>
          ))}
        </div>

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

          {mw.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>
          ) : (
            <>
              {mw.activeTab === 'overview' && (
                <OverviewTab
                  configs={mw.configs}
                  actionLoading={mw.actionLoading}
                  toggleMiddleware={mw.toggleMiddleware}
                />
              )}
              {mw.activeTab === 'config' && (
                <ConfigTab
                  configs={mw.configs}
                  actionLoading={mw.actionLoading}
                  toggleMiddleware={mw.toggleMiddleware}
                />
              )}
              {mw.activeTab === 'ip-list' && (
                <IpListTab
                  ipList={mw.ipList}
                  actionLoading={mw.actionLoading}
                  newIP={mw.newIP}
                  setNewIP={mw.setNewIP}
                  newIPType={mw.newIPType}
                  setNewIPType={mw.setNewIPType}
                  newIPReason={mw.newIPReason}
                  setNewIPReason={mw.setNewIPReason}
                  addIP={mw.addIP}
                  removeIP={mw.removeIP}
                />
              )}
              {mw.activeTab === 'events' && <EventsTab events={mw.events} />}
              {mw.activeTab === 'stats' && <StatsTab stats={mw.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>
  )
}
