"use client";

import {
  type Tenant,
  type TenantDomain,
  type TenantDefaultUser,
  type User,
  type LDAPSyncResult,
} from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { TenantLDAPDialog } from "@/components/admin/TenantLDAPDialog";

interface TenantsTabProps {
  tenants: Tenant[];
  tenantsLoading: boolean;
  tenantsError: string;
  // Create dialog
  tenantDialogOpen: boolean;
  setTenantDialogOpen: (open: boolean) => void;
  newTenantName: string;
  setNewTenantName: (v: string) => void;
  newTenantSlug: string;
  setNewTenantSlug: (v: string) => void;
  tenantCreateLoading: boolean;
  tenantCreateError: string;
  onCreateTenant: (e: React.FormEvent) => void;
  // Credentials dialog
  tenantCredDialogOpen: boolean;
  setTenantCredDialogOpen: (open: boolean) => void;
  tenantCreatedName: string;
  tenantCreatedUsers: TenantDefaultUser[];
  // Delete dialog
  tenantDeleteId: number | null;
  setTenantDeleteId: (id: number | null) => void;
  tenantDeleteLoading: boolean;
  onDeleteTenant: () => void;
  // Domain dialog
  domainDialogTenant: Tenant | null;
  setDomainDialogTenant: (t: Tenant | null) => void;
  tenantDomains: TenantDomain[];
  domainsLoading: boolean;
  newDomain: string;
  setNewDomain: (v: string) => void;
  addDomainLoading: boolean;
  domainError: string;
  onOpenDomainDialog: (t: Tenant) => void;
  onAddDomain: () => void;
  onRemoveDomain: (domainId: number) => void;
  // Users dialog
  tenantUsersDialogId: number | null;
  setTenantUsersDialogId: (id: number | null) => void;
  tenantUsersDialogName: string;
  tenantUsersDialogLdap: boolean;
  tenantUsers: User[];
  tenantUsersLoading: boolean;
  tenantUsersError: string;
  tenantUsersSyncing: boolean;
  tenantUsersSyncResult: LDAPSyncResult | null;
  onOpenUsersDialog: (t: Tenant) => void;
  onSyncLDAPUsers: () => void;
  // Logo dialog
  logoDialogTenant: Tenant | null;
  logoPreviewUrl: string | null;
  logoUploading: boolean;
  logoError: string;
  onOpenLogoDialog: (t: Tenant) => void;
  onLogoUpload: (file: File) => void;
  onLogoDelete: () => void;
  onLogoDialogClose: () => void;
  // Tenant LDAP dialog
  tenantLdapDialogId: number | null;
  setTenantLdapDialogId: (id: number | null) => void;
  onLoadTenants: () => void;
  // Toggle / actions
  onToggleTenant: (t: Tenant) => void;
}

export function TenantsTab({
  tenants,
  tenantsLoading,
  tenantsError,
  tenantDialogOpen,
  setTenantDialogOpen,
  newTenantName,
  setNewTenantName,
  newTenantSlug,
  setNewTenantSlug,
  tenantCreateLoading,
  tenantCreateError,
  onCreateTenant,
  tenantCredDialogOpen,
  setTenantCredDialogOpen,
  tenantCreatedName,
  tenantCreatedUsers,
  tenantDeleteId,
  setTenantDeleteId,
  tenantDeleteLoading,
  onDeleteTenant,
  domainDialogTenant,
  setDomainDialogTenant,
  tenantDomains,
  domainsLoading,
  newDomain,
  setNewDomain,
  addDomainLoading,
  domainError,
  onOpenDomainDialog,
  onAddDomain,
  onRemoveDomain,
  tenantUsersDialogId,
  setTenantUsersDialogId,
  tenantUsersDialogName,
  tenantUsersDialogLdap,
  tenantUsers,
  tenantUsersLoading,
  tenantUsersError,
  tenantUsersSyncing,
  tenantUsersSyncResult,
  onOpenUsersDialog,
  onSyncLDAPUsers,
  logoDialogTenant,
  logoPreviewUrl,
  logoUploading,
  logoError,
  onOpenLogoDialog,
  onLogoUpload,
  onLogoDelete,
  onLogoDialogClose,
  tenantLdapDialogId,
  setTenantLdapDialogId,
  onLoadTenants,
  onToggleTenant,
}: TenantsTabProps) {
  return (
    <div className="mt-4 space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Mandantenverwaltung</h2>
        <Dialog open={tenantDialogOpen} onOpenChange={setTenantDialogOpen}>
          <DialogTrigger asChild>
            <Button size="sm">+ Mandant anlegen</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Neuen Mandanten anlegen</DialogTitle>
              <DialogDescription>Name und URL-Slug für den neuen Mandanten eingeben.</DialogDescription>
            </DialogHeader>
            <form onSubmit={onCreateTenant} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="tenant-name">Name</Label>
                <Input
                  id="tenant-name"
                  value={newTenantName}
                  required
                  onChange={(e) => {
                    setNewTenantName(e.target.value);
                    setNewTenantSlug(e.target.value.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, ""));
                  }}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="tenant-slug">Slug</Label>
                <Input
                  id="tenant-slug"
                  value={newTenantSlug}
                  required
                  onChange={(e) => setNewTenantSlug(e.target.value)}
                />
              </div>
              {tenantCreateError && (
                <p className="text-sm text-destructive">{tenantCreateError}</p>
              )}
              <DialogFooter>
                <Button type="submit" disabled={tenantCreateLoading}>
                  {tenantCreateLoading ? "Erstellen..." : "Erstellen"}
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      {tenantsError && (
        <Alert variant="destructive">
          <AlertDescription>{tenantsError}</AlertDescription>
        </Alert>
      )}

      {tenantsLoading ? (
        <Card>
          <CardContent className="p-4 space-y-3">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-10 w-full" />
            ))}
          </CardContent>
        </Card>
      ) : tenants.length === 0 ? (
        <Card>
          <CardContent className="p-8 text-center text-muted-foreground">
            Keine Mandanten vorhanden. Klicke auf &ldquo;+ Mandant anlegen&rdquo; um den ersten Mandanten zu erstellen.
          </CardContent>
        </Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead className="text-center">Domains</TableHead>
                <TableHead className="text-center">Nutzer</TableHead>
                <TableHead>LDAP</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Aktionen</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {tenants.map((t) => (
                <TableRow key={t.id}>
                  <TableCell className="font-medium">
                    <div>{t.name}</div>
                    <div className="text-xs text-muted-foreground font-mono">{t.slug}</div>
                  </TableCell>
                  <TableCell className="text-center">{t.domain_count ?? 0}</TableCell>
                  <TableCell className="text-center">{t.user_count ?? 0}</TableCell>
                  <TableCell>
                    {t.ldap_enabled === true ? (
                      <div className="space-y-1">
                        <Badge variant="default" className="bg-green-100 text-green-800 hover:bg-green-100">Aktiv</Badge>
                        {t.ldap_url && (
                          <div className="text-xs text-muted-foreground font-mono">
                            {t.ldap_url.replace(/^ldaps?:\/\//, "").split(":")[0]}
                          </div>
                        )}
                      </div>
                    ) : t.ldap_url ? (
                      <Badge variant="secondary" className="bg-yellow-100 text-yellow-800 hover:bg-yellow-100">Deaktiviert</Badge>
                    ) : (
                      <span className="text-sm text-muted-foreground">—</span>
                    )}
                  </TableCell>
                  <TableCell>
                    <Badge variant={t.active ? "default" : "secondary"}>
                      {t.active ? "Aktiv" : "Inaktiv"}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-1">
                      <Button size="sm" variant="outline" onClick={() => onOpenDomainDialog(t)}>
                        Domains
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => onOpenUsersDialog(t)}>
                        Nutzer
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => setTenantLdapDialogId(t.id)}>
                        LDAP
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => onOpenLogoDialog(t)}>
                        Logo
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => onToggleTenant(t)}>
                        {t.active ? "Deaktivieren" : "Aktivieren"}
                      </Button>
                      <Button
                        size="sm"
                        variant="destructive"
                        onClick={() => setTenantDeleteId(t.id)}
                      >
                        Löschen
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}

      {/* Tenant delete confirmation */}
      <Dialog open={tenantDeleteId !== null} onOpenChange={(open) => { if (!open) setTenantDeleteId(null); }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Mandant löschen</DialogTitle>
            <DialogDescription>
              Alle Daten dieses Mandanten (Domains, LDAP-Konfiguration) werden gelöscht. Diese Aktion kann nicht rückgängig gemacht werden.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setTenantDeleteId(null)}>Abbrechen</Button>
            <Button variant="destructive" disabled={tenantDeleteLoading} onClick={onDeleteTenant}>
              {tenantDeleteLoading ? "Löschen..." : "Endgültig löschen"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Logo upload dialog */}
      <Dialog open={logoDialogTenant !== null} onOpenChange={(open) => { if (!open) onLogoDialogClose(); }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Logo — {logoDialogTenant?.name}</DialogTitle>
            <DialogDescription>Logo hochladen (PNG, JPEG, GIF, WebP oder SVG, max. 2 MB).</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {logoPreviewUrl && (
              <div className="flex items-center justify-center rounded border p-4 bg-muted/30">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={logoPreviewUrl} alt="Logo" className="max-h-32 max-w-full object-contain" />
              </div>
            )}
            {!logoPreviewUrl && (
              <div className="flex items-center justify-center rounded border p-8 bg-muted/30 text-sm text-muted-foreground">
                Kein Logo gesetzt
              </div>
            )}
            {logoError && <p className="text-sm text-destructive">{logoError}</p>}
            <div className="flex gap-2">
              <Input
                type="file"
                accept="image/png,image/jpeg,image/gif,image/webp,image/svg+xml"
                disabled={logoUploading}
                onChange={(e) => { const f = e.target.files?.[0]; if (f) onLogoUpload(f); }}
              />
              {logoPreviewUrl && (
                <Button variant="destructive" size="sm" disabled={logoUploading} onClick={onLogoDelete}>
                  Entfernen
                </Button>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={onLogoDialogClose}>Schließen</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Default credentials dialog after tenant creation */}
      <Dialog open={tenantCredDialogOpen} onOpenChange={setTenantCredDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Mandant &bdquo;{tenantCreatedName}&ldquo; erstellt</DialogTitle>
            <DialogDescription>
              Folgende Standard-Benutzer wurden angelegt. Passwörter bitte sofort notieren — sie werden nur einmalig angezeigt.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            {tenantCreatedUsers.map((u) => (
              <div key={u.username} className="rounded border p-3 text-sm font-mono space-y-1">
                <div><span className="text-muted-foreground">Benutzer:</span> {u.username}</div>
                <div><span className="text-muted-foreground">Passwort:</span> {u.password}</div>
                <div><span className="text-muted-foreground">Rolle:</span> {u.role}</div>
              </div>
            ))}
          </div>
          <DialogFooter>
            <Button onClick={() => setTenantCredDialogOpen(false)}>Verstanden</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Domain management dialog */}
      <Dialog open={domainDialogTenant !== null} onOpenChange={(open) => { if (!open) setDomainDialogTenant(null); }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Domains: {domainDialogTenant?.name}</DialogTitle>
            <DialogDescription>E-Mail-Domains diesem Mandanten zuweisen.</DialogDescription>
          </DialogHeader>

          {domainError && (
            <Alert variant="destructive">
              <AlertDescription>{domainError}</AlertDescription>
            </Alert>
          )}

          {domainsLoading ? (
            <Skeleton className="h-24 w-full" />
          ) : (
            <div className="space-y-2">
              {tenantDomains.length === 0 ? (
                <p className="text-sm text-muted-foreground">Keine Domains zugewiesen.</p>
              ) : (
                tenantDomains.map((d) => (
                  <div key={d.id} className="flex items-center justify-between rounded border px-3 py-2">
                    <span className="font-mono text-sm">{d.domain}</span>
                    <Button size="sm" variant="destructive" onClick={() => onRemoveDomain(d.id)}>
                      Entfernen
                    </Button>
                  </div>
                ))
              )}
            </div>
          )}

          <div className="flex gap-2 pt-2">
            <Input
              placeholder="example.com"
              value={newDomain}
              onChange={(e) => setNewDomain(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); onAddDomain(); } }}
            />
            <Button onClick={onAddDomain} disabled={addDomainLoading || !newDomain}>
              {addDomainLoading ? "..." : "Hinzufügen"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Tenant users dialog */}
      <Dialog open={tenantUsersDialogId !== null} onOpenChange={(open) => { if (!open) setTenantUsersDialogId(null); }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Nutzer: {tenantUsersDialogName}</DialogTitle>
            <DialogDescription>Dem Mandanten zugewiesene Benutzerkonten.</DialogDescription>
          </DialogHeader>
          {tenantUsersLoading ? (
            <Skeleton className="h-24 w-full" />
          ) : tenantUsersError ? (
            <Alert variant="destructive">
              <AlertDescription>{tenantUsersError}</AlertDescription>
            </Alert>
          ) : tenantUsers.length === 0 ? (
            <div className="py-4 text-center space-y-2">
              <p className="text-sm text-muted-foreground">Keine lokalen Benutzer diesem Mandanten zugewiesen.</p>
              {tenantUsersDialogLdap && (
                <p className="text-xs text-muted-foreground">LDAP ist aktiv — Benutzer erscheinen hier nach ihrem ersten Login oder nach der Synchronisation.</p>
              )}
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Benutzername</TableHead>
                  <TableHead>E-Mail</TableHead>
                  <TableHead>Rolle</TableHead>
                  <TableHead>Quelle</TableHead>
                  <TableHead>Status</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {tenantUsers.map((u) => (
                  <TableRow key={u.id}>
                    <TableCell className="font-medium">{u.username}</TableCell>
                    <TableCell className="text-sm text-muted-foreground">{u.email}</TableCell>
                    <TableCell><Badge variant="outline">{u.role}</Badge></TableCell>
                    <TableCell><Badge variant="secondary">{u.source || "local"}</Badge></TableCell>
                    <TableCell>
                      <Badge variant={u.active ? "default" : "secondary"}>
                        {u.active ? "Aktiv" : "Inaktiv"}
                      </Badge>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
          {tenantUsersDialogLdap && (
            <div className="border-t pt-3 space-y-2">
              <div className="flex items-center gap-2">
                <Button
                  size="sm"
                  variant="outline"
                  onClick={onSyncLDAPUsers}
                  disabled={tenantUsersSyncing}
                >
                  {tenantUsersSyncing ? "Synchronisiere..." : "LDAP-Benutzer synchronisieren"}
                </Button>
                {tenantUsersSyncResult && (
                  <span className="text-sm text-muted-foreground">
                    {tenantUsersSyncResult.synced} Benutzer synchronisiert
                    {tenantUsersSyncResult.errors.length > 0 && (
                      <span className="text-destructive ml-1">({tenantUsersSyncResult.errors.length} Fehler)</span>
                    )}
                  </span>
                )}
              </div>
              {tenantUsersSyncResult && (tenantUsersSyncResult.errors?.length ?? 0) > 0 && (
                <p className="text-xs text-destructive font-mono">{tenantUsersSyncResult.errors.join(", ")}</p>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Tenant LDAP dialog (superadmin) */}
      {tenantLdapDialogId !== null && (
        <TenantLDAPDialog
          tenantID={tenantLdapDialogId}
          onClose={() => { setTenantLdapDialogId(null); onLoadTenants(); }}
        />
      )}
    </div>
  );
}
