"use client";

import { useState } from "react";
import {
  getTenantUsers,
  syncAdminTenantLDAP,
  type User,
  type Tenant,
  type LDAPSyncResult,
} from "@/lib/api";

export function useTenantUsers() {
  const [tenantUsersDialogId, setTenantUsersDialogId] = useState<number | null>(null);
  const [tenantUsersDialogName, setTenantUsersDialogName] = useState("");
  const [tenantUsersDialogLdap, setTenantUsersDialogLdap] = useState(false);
  const [tenantUsers, setTenantUsers] = useState<User[]>([]);
  const [tenantUsersLoading, setTenantUsersLoading] = useState(false);
  const [tenantUsersError, setTenantUsersError] = useState("");
  const [tenantUsersSyncing, setTenantUsersSyncing] = useState(false);
  const [tenantUsersSyncResult, setTenantUsersSyncResult] = useState<LDAPSyncResult | null>(null);

  async function openUsersDialog(t: Tenant) {
    setTenantUsersDialogId(t.id);
    setTenantUsersDialogName(t.name);
    setTenantUsersDialogLdap(t.ldap_enabled === true);
    setTenantUsersLoading(true);
    setTenantUsers([]);
    setTenantUsersError("");
    setTenantUsersSyncResult(null);
    try {
      const users = await getTenantUsers(t.id);
      setTenantUsers(users || []);
    } catch (err: unknown) {
      setTenantUsersError(err instanceof Error ? err.message : "Nutzer konnten nicht geladen werden.");
    } finally {
      setTenantUsersLoading(false);
    }
  }

  async function handleSyncLDAPUsers() {
    if (!tenantUsersDialogId) return;
    setTenantUsersSyncing(true);
    setTenantUsersSyncResult(null);
    try {
      const result = await syncAdminTenantLDAP(tenantUsersDialogId);
      setTenantUsersSyncResult(result);
      const users = await getTenantUsers(tenantUsersDialogId);
      setTenantUsers(users || []);
    } catch (err: unknown) {
      setTenantUsersSyncResult({ synced: 0, errors: [err instanceof Error ? err.message : "Sync fehlgeschlagen"] });
    } finally {
      setTenantUsersSyncing(false);
    }
  }

  return {
    tenantUsersDialogId,
    setTenantUsersDialogId,
    tenantUsersDialogName,
    tenantUsersDialogLdap,
    tenantUsers,
    tenantUsersLoading,
    tenantUsersError,
    tenantUsersSyncing,
    tenantUsersSyncResult,
    openUsersDialog,
    handleSyncLDAPUsers,
  };
}
