"use client";

import { useState, useCallback } from "react";
import {
  getLDAPConfig,
  saveLDAPConfig,
  deleteLDAPConfig,
  testLDAPConfig,
  type LDAPConfig,
  type LDAPTestResult,
} from "@/lib/api";

const defaultLDAPForm = (): LDAPConfig => ({
  enabled: false,
  url: "ldap://",
  bind_dn: "",
  bind_password: "",
  base_dn: "",
  user_filter: "(sAMAccountName=%s)",
  tls: false,
  tls_skip_verify: false,
  default_role: "user",
  group_mappings: [],
});

export function useLDAPConfig() {
  const [ldapConfig, setLdapConfig] = useState<LDAPConfig | null>(null);
  const [ldapLoading, setLdapLoading] = useState(false);
  const [ldapSaving, setLdapSaving] = useState(false);
  const [ldapTesting, setLdapTesting] = useState(false);
  const [ldapError, setLdapError] = useState("");
  const [ldapTestResult, setLdapTestResult] = useState<LDAPTestResult | null>(null);
  const [ldapForm, setLdapForm] = useState<LDAPConfig>(defaultLDAPForm());
  const [ldapChangePassword, setLdapChangePassword] = useState(false);

  const loadLDAP = useCallback(async () => {
    setLdapLoading(true);
    setLdapError("");
    try {
      const cfg = await getLDAPConfig();
      if (cfg) {
        setLdapConfig(cfg);
        setLdapForm({ ...cfg, bind_password: "" });
        setLdapChangePassword(false);
      }
    } catch {
      setLdapError("LDAP-Konfiguration konnte nicht geladen werden.");
    } finally {
      setLdapLoading(false);
    }
  }, []);

  async function handleSaveLDAP(e: React.FormEvent) {
    e.preventDefault();
    setLdapSaving(true);
    setLdapError("");
    try {
      const payload: Partial<LDAPConfig> = { ...ldapForm };
      if (!ldapChangePassword) {
        delete payload.bind_password;
      }
      await saveLDAPConfig(payload);
      await loadLDAP();
    } catch (err: unknown) {
      setLdapError(err instanceof Error ? err.message : "Speichern fehlgeschlagen.");
    } finally {
      setLdapSaving(false);
    }
  }

  async function handleTestLDAP() {
    setLdapTesting(true);
    setLdapError("");
    setLdapTestResult(null);
    try {
      const payload = ldapConfig
        ? { use_saved: true }
        : { use_saved: false, ...ldapForm };
      const result = await testLDAPConfig(payload as Parameters<typeof testLDAPConfig>[0]);
      setLdapTestResult(result);
    } catch (err: unknown) {
      setLdapError(err instanceof Error ? err.message : "Test fehlgeschlagen.");
    } finally {
      setLdapTesting(false);
    }
  }

  async function handleDeleteLDAP() {
    setLdapSaving(true);
    setLdapError("");
    try {
      await deleteLDAPConfig();
      setLdapConfig(null);
      setLdapForm(defaultLDAPForm());
      setLdapTestResult(null);
    } catch (err: unknown) {
      setLdapError(err instanceof Error ? err.message : "Löschen fehlgeschlagen.");
    } finally {
      setLdapSaving(false);
    }
  }

  return {
    ldapConfig,
    ldapLoading,
    ldapSaving,
    ldapTesting,
    ldapError,
    ldapTestResult,
    ldapForm,
    setLdapForm,
    ldapChangePassword,
    setLdapChangePassword,
    loadLDAP,
    handleSaveLDAP,
    handleTestLDAP,
    handleDeleteLDAP,
  };
}
