"use client";

import { useState, useCallback, type Dispatch, type SetStateAction } from "react";
import {
  getTenants,
  createTenant,
  updateTenant,
  deleteTenant,
  getTenantDomains,
  addTenantDomain,
  removeTenantDomain,
  type Tenant,
  type TenantDefaultUser,
  type TenantDomain,
} from "@/lib/api";

export function useAdminTenants() {
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [tenantsLoading, setTenantsLoading] = useState(false);
  const [tenantsError, setTenantsError] = useState("");
  const [tenantDialogOpen, setTenantDialogOpen] = useState(false);
  const [newTenantName, setNewTenantName] = useState("");
  const [newTenantSlug, setNewTenantSlug] = useState("");
  const [tenantCreateLoading, setTenantCreateLoading] = useState(false);
  const [tenantCreateError, setTenantCreateError] = useState("");
  const [tenantCreatedUsers, setTenantCreatedUsers] = useState<TenantDefaultUser[]>([]);
  const [tenantCreatedName, setTenantCreatedName] = useState("");
  const [tenantCredDialogOpen, setTenantCredDialogOpen] = useState(false);
  const [tenantDeleteId, setTenantDeleteId] = useState<number | null>(null);
  const [tenantDeleteLoading, setTenantDeleteLoading] = useState(false);
  const [domainDialogTenant, setDomainDialogTenant] = useState<Tenant | null>(null);
  const [tenantDomains, setTenantDomains] = useState<TenantDomain[]>([]);
  const [domainsLoading, setDomainsLoading] = useState(false);
  const [newDomain, setNewDomain] = useState("");
  const [addDomainLoading, setAddDomainLoading] = useState(false);
  const [domainError, setDomainError] = useState("");

  // Superadmin: tenant LDAP dialog
  const [tenantLdapDialogId, setTenantLdapDialogId] = useState<number | null>(null);

  const loadTenants = useCallback(async () => {
    setTenantsLoading(true);
    setTenantsError("");
    try {
      const data = await getTenants();
      setTenants(data || []);
    } catch {
      setTenantsError("Mandanten konnten nicht geladen werden.");
    } finally {
      setTenantsLoading(false);
    }
  }, []);

  async function handleCreateTenant(e: React.FormEvent) {
    e.preventDefault();
    setTenantCreateLoading(true);
    setTenantCreateError("");
    try {
      const result = await createTenant(newTenantName, newTenantSlug);
      setTenantDialogOpen(false);
      setTenantCreatedName(result.name);
      setTenantCreatedUsers(result.default_users ?? []);
      setTenantCredDialogOpen(true);
      setNewTenantName("");
      setNewTenantSlug("");
      await loadTenants();
    } catch (err: unknown) {
      setTenantCreateError(err instanceof Error ? err.message : "Erstellen fehlgeschlagen.");
    } finally {
      setTenantCreateLoading(false);
    }
  }

  async function handleToggleTenant(t: Tenant) {
    try {
      await updateTenant(t.id, { active: !t.active });
      await loadTenants();
    } catch { /* ignore */ }
  }

  async function handleDeleteTenant() {
    if (!tenantDeleteId) return;
    setTenantDeleteLoading(true);
    try {
      await deleteTenant(tenantDeleteId);
      setTenantDeleteId(null);
      await loadTenants();
    } catch { /* ignore */ } finally {
      setTenantDeleteLoading(false);
    }
  }

  async function openDomainDialog(t: Tenant) {
    setDomainDialogTenant(t);
    setDomainsLoading(true);
    setDomainError("");
    setNewDomain("");
    try {
      const domains = await getTenantDomains(t.id);
      setTenantDomains(domains || []);
    } catch { setDomainError("Domains konnten nicht geladen werden."); }
    finally { setDomainsLoading(false); }
  }

  async function handleAddDomain() {
    if (!domainDialogTenant || !newDomain) return;
    setAddDomainLoading(true);
    setDomainError("");
    try {
      await addTenantDomain(domainDialogTenant.id, newDomain);
      setNewDomain("");
      const domains = await getTenantDomains(domainDialogTenant.id);
      setTenantDomains(domains || []);
    } catch (err: unknown) {
      setDomainError(err instanceof Error ? err.message : "Domain konnte nicht hinzugefügt werden.");
    } finally {
      setAddDomainLoading(false);
    }
  }

  async function handleRemoveDomain(domainId: number) {
    if (!domainDialogTenant) return;
    setDomainError("");
    try {
      await removeTenantDomain(domainDialogTenant.id, domainId);
      const domains = await getTenantDomains(domainDialogTenant.id);
      setTenantDomains(domains || []);
    } catch (err: unknown) {
      setDomainError(err instanceof Error ? err.message : "Domain konnte nicht entfernt werden.");
    }
  }

  return {
    tenants,
    setTenants: setTenants as Dispatch<SetStateAction<Tenant[]>>,
    tenantsLoading,
    tenantsError,
    tenantDialogOpen,
    setTenantDialogOpen,
    newTenantName,
    setNewTenantName,
    newTenantSlug,
    setNewTenantSlug,
    tenantCreateLoading,
    tenantCreateError,
    tenantCreatedUsers,
    tenantCreatedName,
    tenantCredDialogOpen,
    setTenantCredDialogOpen,
    tenantDeleteId,
    setTenantDeleteId,
    tenantDeleteLoading,
    domainDialogTenant,
    setDomainDialogTenant,
    tenantDomains,
    domainsLoading,
    newDomain,
    setNewDomain,
    addDomainLoading,
    domainError,
    tenantLdapDialogId,
    setTenantLdapDialogId,
    loadTenants,
    handleCreateTenant,
    handleToggleTenant,
    handleDeleteTenant,
    openDomainDialog,
    handleAddDomain,
    handleRemoveDomain,
  };
}
