'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useAuth } from '@/components/providers/auth-provider'
import {
  ArrowLeft, MapPin, Shield, Map, Image as ImageIcon, Layers, BookOpen,
  Users, Settings, Building2, AlertTriangle, ClipboardList, Heart, ShieldCheck, Loader2,
} from 'lucide-react'
import { TenantsTab } from '@/components/admin/tenants-tab'
import { UsersTab } from '@/components/admin/users-tab'
import { ProjectsTab } from '@/components/admin/projects-tab'
import { IconsTab } from '@/components/admin/icons-tab'
import { CategoriesTab } from '@/components/admin/categories-tab'
import { SettingsTab } from '@/components/admin/settings-tab'
import { SomaTab } from '@/components/admin/soma-tab'
import { SuggestionsTab } from '@/components/admin/suggestions-tab'
import { DictionaryTab } from '@/components/admin/dictionary-tab'
import { SymbolManager } from '@/components/admin/symbol-manager'
import { OrgTab } from '@/components/admin/org-tab'
import { HoseSettingsDialog } from '@/components/dialogs/hose-settings-dialog'

export default function AdminPage() {
  const { user, tenant, loading: authLoading } = useAuth()
  const router = useRouter()

  const [activeTab, setActiveTab] = useState<string>('')
  const [isHoseSettingsOpen, setIsHoseSettingsOpen] = useState(false)

  // Redirect: nur eingeloggte Admins
  useEffect(() => {
    if (authLoading) return
    if (!user) router.push('/login')
    else if (user.role !== 'SERVER_ADMIN' && user.role !== 'TENANT_ADMIN') router.push('/app')
  }, [authLoading, user, router])

  // Standard-Tab setzen, sobald die Rolle bekannt ist
  useEffect(() => {
    if (!activeTab && user?.role) {
      setActiveTab(user.role === 'SERVER_ADMIN' ? 'tenants' : 'org')
    }
  }, [user?.role, activeTab])

  if (authLoading || !user || (user.role !== 'SERVER_ADMIN' && user.role !== 'TENANT_ADMIN')) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      </div>
    )
  }

  const isServerAdmin = user.role === 'SERVER_ADMIN'

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="h-14 border-b border-border bg-card flex items-center justify-between px-6">
        <div className="flex items-center gap-4">
          <Link href="/app">
            <Button variant="ghost" size="sm">
              <ArrowLeft className="w-4 h-4 mr-2" />
              Zurück zur App
            </Button>
          </Link>
          <div className="h-6 w-px bg-border" />
          <div className="flex items-center gap-2">
            <MapPin className="w-5 h-5 text-primary" />
            <h1 className="font-semibold text-lg">Administration</h1>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2 text-sm">
            <Shield className="w-4 h-4 text-primary" />
            <span className="font-medium">{user.name}</span>
            <span className="text-xs bg-primary/10 text-primary px-2 py-0.5 rounded-full">{user.role}</span>
          </div>
        </div>
      </header>

      <div className="container mx-auto py-6 px-4 max-w-7xl">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          {isServerAdmin ? (
            <TabsList className="grid w-full grid-cols-7 max-w-4xl">
              <TabsTrigger value="tenants" className="gap-2"><Shield className="w-4 h-4" />Mandanten</TabsTrigger>
              <TabsTrigger value="projects" className="gap-2"><Map className="w-4 h-4" />Einsätze</TabsTrigger>
              <TabsTrigger value="icons" className="gap-2"><ImageIcon className="w-4 h-4" />Symbole</TabsTrigger>
              <TabsTrigger value="categories" className="gap-2"><Layers className="w-4 h-4" />Kategorien</TabsTrigger>
              <TabsTrigger value="dictionary" className="gap-2"><BookOpen className="w-4 h-4" />Wörterbuch</TabsTrigger>
              <TabsTrigger value="users" className="gap-2"><Users className="w-4 h-4" />Benutzer</TabsTrigger>
              <TabsTrigger value="settings" className="gap-2"><Settings className="w-4 h-4" />System</TabsTrigger>
            </TabsList>
          ) : (
            <TabsList className="grid w-full grid-cols-7 max-w-4xl">
              <TabsTrigger value="org" className="gap-2"><Building2 className="w-4 h-4" />Organisation</TabsTrigger>
              <TabsTrigger value="users" className="gap-2"><Users className="w-4 h-4" />Benutzer</TabsTrigger>
              <TabsTrigger value="icons" className="gap-2"><ImageIcon className="w-4 h-4" />Symbole</TabsTrigger>
              <TabsTrigger value="soma" className="gap-2"><AlertTriangle className="w-4 h-4" />SOMA</TabsTrigger>
              <TabsTrigger value="suggestions" className="gap-2"><ClipboardList className="w-4 h-4" />Wörterliste</TabsTrigger>
              <TabsTrigger value="hose-types" className="gap-2"><Settings className="w-4 h-4" />Schläuche</TabsTrigger>
              <TabsTrigger value="donate" className="gap-2"><Heart className="w-4 h-4" />Spenden</TabsTrigger>
            </TabsList>
          )}

          {/* ===== SERVER_ADMIN ===== */}
          {isServerAdmin && (
            <TabsContent value="tenants"><TenantsTab /></TabsContent>
          )}
          {isServerAdmin && (
            <TabsContent value="projects"><ProjectsTab /></TabsContent>
          )}
          {isServerAdmin && (
            <TabsContent value="categories"><CategoriesTab /></TabsContent>
          )}
          {isServerAdmin && (
            <TabsContent value="dictionary"><DictionaryTab /></TabsContent>
          )}
          {isServerAdmin && (
            <TabsContent value="settings" className="space-y-6">
              <SettingsTab onNavigateTab={setActiveTab} />
            </TabsContent>
          )}

          {/* ===== Geteilt: Benutzer ===== */}
          <TabsContent value="users"><UsersTab /></TabsContent>

          {/* ===== Symbole: Super-Admin = globale Verwaltung, sonst SymbolManager ===== */}
          <TabsContent value="icons">
            {isServerAdmin ? <IconsTab /> : <SymbolManager />}
          </TabsContent>

          {/* ===== TENANT_ADMIN ===== */}
          {!isServerAdmin && (
            <TabsContent value="org"><OrgTab tenantId={tenant?.id} /></TabsContent>
          )}
          {!isServerAdmin && (
            <TabsContent value="soma" className="space-y-6"><SomaTab /></TabsContent>
          )}

          <TabsContent value="suggestions"><SuggestionsTab tenantId={tenant?.id} /></TabsContent>

          <TabsContent value="hose-types" className="space-y-4">
            <div className="border rounded-lg p-6">
              <h3 className="font-semibold text-lg mb-2 flex items-center gap-2">
                <Settings className="w-5 h-5" />
                Schlauchtypen verwalten
              </h3>
              <p className="text-sm text-muted-foreground mb-4">
                Konfiguriere die Schlauchtypen für die Druckberechnung im Messwerkzeug. Der Standard-Schlauch wird automatisch für neue Berechnungen verwendet.
              </p>
              <Button variant="outline" onClick={() => setIsHoseSettingsOpen(true)}>
                <Settings className="w-4 h-4 mr-2" />
                Schlauchtypen bearbeiten
              </Button>
            </div>
            <HoseSettingsDialog open={isHoseSettingsOpen} onOpenChange={setIsHoseSettingsOpen} />
          </TabsContent>

          {!isServerAdmin && tenant && (
            <TabsContent value="donate" className="space-y-6">
              <div className="border rounded-lg p-6">
                <div className="flex items-start gap-4 mb-6">
                  <div className="w-12 h-12 rounded-full bg-gradient-to-br from-red-500 to-red-700 flex items-center justify-center shrink-0">
                    <Heart className="w-6 h-6 text-white" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-lg">Lageplan unterstützen</h3>
                    <p className="text-sm text-muted-foreground mt-1">
                      Lageplan ist ein kostenloses Projekt — entwickelt von einem aktiven Feuerwehrmann
                      in seiner Freizeit. Ohne Firma, ohne Investoren. Deine Spende hilft, den Betrieb und die
                      Weiterentwicklung zu finanzieren.
                    </p>
                  </div>
                </div>

                <div className="bg-muted/50 rounded-lg p-4 mb-6">
                  <p className="text-sm font-medium mb-2">Wohin fliesst deine Spende?</p>
                  <ul className="text-sm text-muted-foreground space-y-1">
                    <li className="flex items-center gap-2"><Shield className="w-3.5 h-3.5 text-primary shrink-0" /> Server-Hosting in der Schweiz (monatliche Kosten)</li>
                    <li className="flex items-center gap-2"><Settings className="w-3.5 h-3.5 text-primary shrink-0" /> Entwicklung neuer Features und Bugfixes</li>
                    <li className="flex items-center gap-2"><ShieldCheck className="w-3.5 h-3.5 text-primary shrink-0" /> Domain, SSL-Zertifikate und Infrastruktur</li>
                  </ul>
                </div>

                <div className="flex flex-wrap gap-3">
                  <Button asChild>
                    <a href="/spenden" target="_blank" rel="noopener noreferrer">
                      <Heart className="w-4 h-4 mr-2" />
                      Jetzt spenden
                    </a>
                  </Button>
                  <Button variant="outline" asChild>
                    <a href="/" target="_blank" rel="noopener noreferrer">
                      Mehr über Lageplan erfahren
                    </a>
                  </Button>
                </div>
              </div>
              <div className="border rounded-lg p-6">
                <h3 className="font-semibold text-lg mb-4">Dein Mandant</h3>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                  <div>
                    <p className="text-sm text-muted-foreground">Organisation</p>
                    <p className="font-semibold">{tenant.name}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Benutzer</p>
                    <p className="font-semibold">Unbegrenzt</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Projekte</p>
                    <p className="font-semibold">Unbegrenzt</p>
                  </div>
                </div>
              </div>
            </TabsContent>
          )}
        </Tabs>
      </div>
    </div>
  )
}
