'use client'

import React, { useCallback, useEffect, useState } from 'react'
import {
  Activity,
  AlertTriangle,
  BarChart3,
  Globe,
  GraduationCap,
  Loader2,
  Plus,
  Settings,
  Shield,
  Truck,
  Users,
} from 'lucide-react'
import type { CreateNamespaceForm, TenantNamespace, TenantOverview } from '../_types'
import { DATA_CLASSIFICATIONS, EMPTY_NAMESPACE_FORM, ISOLATION_LEVELS } from './constants'
import { apiFetch, formatDate, getRiskBadgeClasses, getScoreColor, getStatusBadge, slugify } from './helpers'
import { ComplianceRing } from './ComplianceRing'
import { Modal } from './Modal'

export function TenantDetailModal({
  open,
  onClose,
  tenant,
  onSwitchTenant,
}: {
  open: boolean
  onClose: () => void
  tenant: TenantOverview | null
  onSwitchTenant: (t: TenantOverview) => void
}) {
  const [namespaces, setNamespaces] = useState<TenantNamespace[]>([])
  const [namespacesLoading, setNamespacesLoading] = useState(false)
  const [namespacesError, setNamespacesError] = useState<string | null>(null)
  const [showCreateNs, setShowCreateNs] = useState(false)
  const [nsForm, setNsForm] = useState<CreateNamespaceForm>({ ...EMPTY_NAMESPACE_FORM })
  const [nsCreating, setNsCreating] = useState(false)
  const [nsError, setNsError] = useState<string | null>(null)

  const loadNamespaces = useCallback(async () => {
    if (!tenant) return
    setNamespacesLoading(true)
    setNamespacesError(null)
    try {
      const data = await apiFetch<{ namespaces: TenantNamespace[]; total: number }>(
        `/tenants/${tenant.id}/namespaces`
      )
      setNamespaces(data.namespaces || [])
    } catch (err) {
      setNamespacesError(err instanceof Error ? err.message : 'Fehler beim Laden')
    } finally {
      setNamespacesLoading(false)
    }
  }, [tenant])

  useEffect(() => {
    if (open && tenant) {
      loadNamespaces()
      setShowCreateNs(false)
      setNsForm({ ...EMPTY_NAMESPACE_FORM })
      setNsError(null)
    }
  }, [open, tenant, loadNamespaces])

  const handleNsNameChange = (name: string) => {
    setNsForm((prev) => ({
      ...prev,
      name,
      slug: slugify(name),
    }))
  }

  const handleCreateNamespace = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!tenant || nsForm.name.trim().length < 2) return
    setNsCreating(true)
    setNsError(null)
    try {
      await apiFetch(`/tenants/${tenant.id}/namespaces`, {
        method: 'POST',
        body: JSON.stringify({
          name: nsForm.name.trim(),
          slug: nsForm.slug.trim(),
          isolation_level: nsForm.isolation_level,
          data_classification: nsForm.data_classification,
        }),
      })
      setNsForm({ ...EMPTY_NAMESPACE_FORM })
      setShowCreateNs(false)
      loadNamespaces()
    } catch (err) {
      setNsError(err instanceof Error ? err.message : 'Fehler beim Erstellen')
    } finally {
      setNsCreating(false)
    }
  }

  if (!tenant) return null

  const statusInfo = getStatusBadge(tenant.status)
  const scoreColor = getScoreColor(tenant.compliance_score)

  return (
    <Modal open={open} onClose={onClose} title={`Mandant: ${tenant.name}`} maxWidth="max-w-2xl">
      <div className="space-y-6">
        {/* Overview Section */}
        <div className="flex items-start gap-5">
          <ComplianceRing score={tenant.compliance_score} size={80} />
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-2">
              <h3 className="text-lg font-semibold text-slate-900">{tenant.name}</h3>
              <span className={`inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full ${statusInfo.bg} ${statusInfo.text}`}>
                {statusInfo.icon}
                {statusInfo.label}
              </span>
            </div>
            <p className="text-sm text-slate-400 font-mono mb-2">{tenant.slug}</p>
            <div className="flex items-center gap-3 text-xs text-slate-500">
              <span className={`inline-flex items-center gap-1 px-2 py-0.5 font-semibold rounded-full ${getRiskBadgeClasses(tenant.risk_level)}`}>
                {tenant.risk_level}
              </span>
              <span>Erstellt: {formatDate(tenant.created_at)}</span>
            </div>
          </div>
        </div>

        {/* Compliance Breakdown */}
        <div>
          <h4 className="text-sm font-semibold text-slate-700 mb-3 flex items-center gap-2">
            <BarChart3 className="w-4 h-4 text-indigo-500" />
            Compliance-Uebersicht
          </h4>
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            <div className="bg-slate-50 rounded-lg p-3">
              <div className="flex items-center gap-1.5 text-xs text-slate-500 mb-1">
                <AlertTriangle className="w-3.5 h-3.5 text-orange-500" />
                Offene Vorfaelle
              </div>
              <p className="text-lg font-bold text-slate-900">{tenant.open_incidents}</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <div className="flex items-center gap-1.5 text-xs text-slate-500 mb-1">
                <Shield className="w-3.5 h-3.5 text-indigo-500" />
                Hinweisgebermeldungen
              </div>
              <p className="text-lg font-bold text-slate-900">{tenant.open_reports}</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <div className="flex items-center gap-1.5 text-xs text-slate-500 mb-1">
                <Users className="w-3.5 h-3.5 text-blue-500" />
                Ausstehende DSRs
              </div>
              <p className="text-lg font-bold text-slate-900">{tenant.pending_dsrs}</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <div className="flex items-center gap-1.5 text-xs text-slate-500 mb-1">
                <GraduationCap className="w-3.5 h-3.5 text-green-500" />
                Schulungsquote
              </div>
              <p className="text-lg font-bold text-slate-900">{tenant.training_completion_rate}%</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <div className="flex items-center gap-1.5 text-xs text-slate-500 mb-1">
                <Truck className="w-3.5 h-3.5 text-orange-500" />
                Hochrisiko-Dienstleister
              </div>
              <p className="text-lg font-bold text-slate-900">{tenant.vendor_risk_high}</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <div className="flex items-center gap-1.5 text-xs text-slate-500 mb-1">
                <Activity className="w-3.5 h-3.5" style={{ color: scoreColor }} />
                Compliance-Score
              </div>
              <p className="text-lg font-bold" style={{ color: scoreColor }}>
                {tenant.compliance_score}/100
              </p>
            </div>
          </div>
        </div>

        {/* Settings */}
        <div>
          <h4 className="text-sm font-semibold text-slate-700 mb-3 flex items-center gap-2">
            <Settings className="w-4 h-4 text-indigo-500" />
            Mandanten-Einstellungen
          </h4>
          <div className="grid grid-cols-2 gap-3">
            <div className="bg-slate-50 rounded-lg p-3">
              <span className="text-xs text-slate-400">Max. Benutzer</span>
              <p className="text-base font-semibold text-slate-800">{tenant.max_users.toLocaleString('de-DE')}</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <span className="text-xs text-slate-400">LLM Kontingent / Monat</span>
              <p className="text-base font-semibold text-slate-800">{tenant.llm_quota_monthly.toLocaleString('de-DE')}</p>
            </div>
          </div>
        </div>

        {/* Namespaces */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <h4 className="text-sm font-semibold text-slate-700 flex items-center gap-2">
              <Globe className="w-4 h-4 text-indigo-500" />
              Namespaces ({namespaces.length})
            </h4>
            <button
              onClick={() => setShowCreateNs(!showCreateNs)}
              className="flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-indigo-600 bg-indigo-50 hover:bg-indigo-100 rounded-lg transition-colors"
            >
              <Plus className="w-3.5 h-3.5" />
              Neuer Namespace
            </button>
          </div>

          {/* Create Namespace Form */}
          {showCreateNs && (
            <form onSubmit={handleCreateNamespace} className="mb-4 p-4 bg-indigo-50/50 rounded-lg border border-indigo-100 space-y-3">
              {nsError && (
                <div className="flex items-center gap-2 p-2 text-xs text-red-700 bg-red-50 rounded-lg border border-red-200">
                  <AlertTriangle className="w-3.5 h-3.5 shrink-0" />
                  {nsError}
                </div>
              )}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">Name</label>
                  <input
                    type="text"
                    value={nsForm.name}
                    onChange={(e) => handleNsNameChange(e.target.value)}
                    placeholder="z.B. Produktion"
                    className="w-full px-2.5 py-1.5 border border-slate-300 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    autoFocus
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">Slug</label>
                  <input
                    type="text"
                    value={nsForm.slug}
                    readOnly
                    className="w-full px-2.5 py-1.5 border border-slate-200 rounded-lg text-xs bg-slate-50 font-mono"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">Isolationsebene</label>
                  <select
                    value={nsForm.isolation_level}
                    onChange={(e) => setNsForm((prev) => ({ ...prev, isolation_level: e.target.value }))}
                    className="w-full px-2.5 py-1.5 border border-slate-300 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-white"
                  >
                    {ISOLATION_LEVELS.map((opt) => (
                      <option key={opt.value} value={opt.value}>{opt.label}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-medium text-slate-600 mb-1">Datenklassifikation</label>
                  <select
                    value={nsForm.data_classification}
                    onChange={(e) => setNsForm((prev) => ({ ...prev, data_classification: e.target.value }))}
                    className="w-full px-2.5 py-1.5 border border-slate-300 rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 bg-white"
                  >
                    {DATA_CLASSIFICATIONS.map((opt) => (
                      <option key={opt.value} value={opt.value}>{opt.label}</option>
                    ))}
                  </select>
                </div>
              </div>
              <div className="flex items-center justify-end gap-2">
                <button
                  type="button"
                  onClick={() => { setShowCreateNs(false); setNsError(null) }}
                  className="px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-100 rounded-lg transition-colors"
                >
                  Abbrechen
                </button>
                <button
                  type="submit"
                  disabled={nsForm.name.trim().length < 2 || nsCreating}
                  className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-white bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors"
                >
                  {nsCreating && <Loader2 className="w-3 h-3 animate-spin" />}
                  Erstellen
                </button>
              </div>
            </form>
          )}

          {/* Namespaces List */}
          {namespacesLoading ? (
            <div className="space-y-2 animate-pulse">
              {Array.from({ length: 3 }).map((_, i) => (
                <div key={i} className="h-12 bg-slate-100 rounded-lg" />
              ))}
            </div>
          ) : namespacesError ? (
            <div className="flex items-center gap-2 p-3 text-sm text-red-700 bg-red-50 rounded-lg border border-red-200">
              <AlertTriangle className="w-4 h-4 shrink-0" />
              {namespacesError}
            </div>
          ) : namespaces.length === 0 ? (
            <div className="text-center py-6 text-sm text-slate-400">
              Noch keine Namespaces vorhanden.
            </div>
          ) : (
            <div className="space-y-2">
              {namespaces.map((ns) => (
                <div
                  key={ns.id}
                  className="flex items-center gap-3 px-3 py-2.5 bg-white rounded-lg border border-slate-200 text-sm"
                >
                  <Globe className="w-4 h-4 text-indigo-400 shrink-0" />
                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-slate-800 truncate">{ns.name}</p>
                    <p className="text-xs text-slate-400 font-mono">{ns.slug}</p>
                  </div>
                  <span className="px-2 py-0.5 text-xs font-medium bg-slate-100 text-slate-600 rounded-full">
                    {ns.isolation_level}
                  </span>
                  <span className="px-2 py-0.5 text-xs font-medium bg-blue-50 text-blue-600 rounded-full">
                    {ns.data_classification}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Switch Tenant Action */}
        <div className="pt-4 border-t border-slate-200">
          <button
            onClick={() => {
              onSwitchTenant(tenant)
              onClose()
            }}
            className="w-full flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg transition-colors"
          >
            <Globe className="w-4 h-4" />
            Zu diesem Mandanten wechseln
          </button>
        </div>
      </div>
    </Modal>
  )
}
