"use client";

import { useState, useCallback } from "react";
import {
  getTenantLDAPConfig,
  saveTenantLDAPConfig,
  deleteTenantLDAPConfig,
  testTenantLDAPConfig,
  type TenantLDAPConfig,
  type LDAPTestResult,
} from "@/lib/api";

const defaultTenantLDAPForm = (): TenantLDAPConfig => ({
  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 useTenantLDAPConfig() {
  const [tenantLdapConfig, setTenantLdapConfig] = useState<TenantLDAPConfig | null>(null);
  const [tenantLdapLoading, setTenantLdapLoading] = useState(false);
  const [tenantLdapSaving, setTenantLdapSaving] = useState(false);
  const [tenantLdapTesting, setTenantLdapTesting] = useState(false);
  const [tenantLdapError, setTenantLdapError] = useState("");
  const [tenantLdapTestResult, setTenantLdapTestResult] = useState<LDAPTestResult | null>(null);
  const [tenantLdapForm, setTenantLdapForm] = useState<TenantLDAPConfig>(defaultTenantLDAPForm());
  const [tenantLdapChangePassword, setTenantLdapChangePassword] = useState(false);

  // Own tenant logo state (lives here because it's loaded together with tenant LDAP)
  const [ownLogoPreviewUrl, setOwnLogoPreviewUrl] = useState<string | null>(null);
  const [ownLogoUploading, setOwnLogoUploading] = useState(false);
  const [ownLogoError, setOwnLogoError] = useState("");

  const loadTenantLDAP = useCallback(async () => {
    setTenantLdapLoading(true);
    setTenantLdapError("");
    try {
      const cfg = await getTenantLDAPConfig();
      if (cfg) {
        setTenantLdapConfig(cfg);
        setTenantLdapForm({ ...cfg, bind_password: "" });
        setTenantLdapChangePassword(false);
      }
    } catch {
      setTenantLdapError("LDAP-Konfiguration konnte nicht geladen werden.");
    } finally {
      setTenantLdapLoading(false);
    }
    // Load own tenant logo preview
    try {
      const res = await fetch("/api/tenant/logo", { credentials: "include" });
      if (res.ok) {
        const blob = await res.blob();
        setOwnLogoPreviewUrl(URL.createObjectURL(blob));
      }
    } catch {
      // no logo or not available
    }
  }, []);

  async function handleSaveTenantLDAP(e: React.FormEvent) {
    e.preventDefault();
    setTenantLdapSaving(true);
    setTenantLdapError("");
    try {
      const payload: Partial<TenantLDAPConfig> = { ...tenantLdapForm };
      if (!tenantLdapChangePassword) {
        delete payload.bind_password;
      }
      await saveTenantLDAPConfig(payload);
      await loadTenantLDAP();
    } catch (err: unknown) {
      setTenantLdapError(err instanceof Error ? err.message : "Speichern fehlgeschlagen.");
    } finally {
      setTenantLdapSaving(false);
    }
  }

  async function handleTestTenantLDAP() {
    setTenantLdapTesting(true);
    setTenantLdapError("");
    setTenantLdapTestResult(null);
    try {
      const payload = tenantLdapConfig
        ? { use_saved: true }
        : { use_saved: false, ...tenantLdapForm };
      const result = await testTenantLDAPConfig(payload as Parameters<typeof testTenantLDAPConfig>[0]);
      setTenantLdapTestResult(result);
    } catch (err: unknown) {
      setTenantLdapError(err instanceof Error ? err.message : "Test fehlgeschlagen.");
    } finally {
      setTenantLdapTesting(false);
    }
  }

  async function handleDeleteTenantLDAP() {
    setTenantLdapSaving(true);
    setTenantLdapError("");
    try {
      await deleteTenantLDAPConfig();
      setTenantLdapConfig(null);
      setTenantLdapForm(defaultTenantLDAPForm());
      setTenantLdapTestResult(null);
    } catch (err: unknown) {
      setTenantLdapError(err instanceof Error ? err.message : "Löschen fehlgeschlagen.");
    } finally {
      setTenantLdapSaving(false);
    }
  }

  return {
    tenantLdapConfig,
    tenantLdapLoading,
    tenantLdapSaving,
    tenantLdapTesting,
    tenantLdapError,
    tenantLdapTestResult,
    tenantLdapForm,
    setTenantLdapForm,
    tenantLdapChangePassword,
    setTenantLdapChangePassword,
    ownLogoPreviewUrl,
    setOwnLogoPreviewUrl,
    ownLogoUploading,
    setOwnLogoUploading,
    ownLogoError,
    setOwnLogoError,
    loadTenantLDAP,
    handleSaveTenantLDAP,
    handleTestTenantLDAP,
    handleDeleteTenantLDAP,
  };
}
