"use client";

import { useState, useCallback } from "react";
import {
  getUsers,
  createUser,
  updateUser,
  deleteUser,
  type User,
} from "@/lib/api";

export function useAdminUsers() {
  const [users, setUsers] = useState<User[]>([]);
  const [usersLoading, setUsersLoading] = useState(true);
  const [usersError, setUsersError] = useState("");

  // Create user dialog
  const [dialogOpen, setDialogOpen] = useState(false);
  const [newUsername, setNewUsername] = useState("");
  const [newEmail, setNewEmail] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [newRole, setNewRole] = useState("user");
  const [createLoading, setCreateLoading] = useState(false);
  const [createError, setCreateError] = useState("");

  // User action state
  const [userActionLoading, setUserActionLoading] = useState<number | null>(null);
  const [resetPasswordUserId, setResetPasswordUserId] = useState<number | null>(null);
  const [resetPasswordValue, setResetPasswordValue] = useState("");
  const [resetPasswordError, setResetPasswordError] = useState("");
  const [resetPasswordLoading, setResetPasswordLoading] = useState(false);

  // Delete confirmation dialog
  const [deleteDialogUser, setDeleteDialogUser] = useState<User | null>(null);
  const [deleteActionLoading, setDeleteActionLoading] = useState<"deactivate" | "delete" | null>(null);
  const [deleteDialogError, setDeleteDialogError] = useState("");

  const loadUsers = useCallback(async () => {
    setUsersLoading(true);
    setUsersError("");
    try {
      const data = await getUsers();
      setUsers(data || []);
    } catch {
      setUsersError("Benutzer konnten nicht geladen werden.");
    } finally {
      setUsersLoading(false);
    }
  }, []);

  async function handleCreateUser(e: React.FormEvent) {
    e.preventDefault();
    setCreateLoading(true);
    setCreateError("");
    try {
      await createUser({
        username: newUsername,
        email: newEmail,
        password: newPassword,
        role: newRole,
      });
      setDialogOpen(false);
      setNewUsername("");
      setNewEmail("");
      setNewPassword("");
      setNewRole("user");
      loadUsers();
    } catch {
      setCreateError("Benutzer konnte nicht erstellt werden.");
    } finally {
      setCreateLoading(false);
    }
  }

  async function handleToggleActive(u: User) {
    setUserActionLoading(u.id);
    try {
      await updateUser(u.id, { active: !u.active });
      loadUsers();
    } catch {
      // ignore
    } finally {
      setUserActionLoading(null);
    }
  }

  async function handleDeactivateConfirmed() {
    if (!deleteDialogUser) return;
    setDeleteActionLoading("deactivate");
    setDeleteDialogError("");
    try {
      await updateUser(deleteDialogUser.id, { active: false });
      setDeleteDialogUser(null);
      loadUsers();
    } catch {
      setDeleteDialogError("Deaktivierung fehlgeschlagen.");
    } finally {
      setDeleteActionLoading(null);
    }
  }

  async function handleDeleteConfirmed() {
    if (!deleteDialogUser) return;
    setDeleteActionLoading("delete");
    setDeleteDialogError("");
    try {
      await deleteUser(deleteDialogUser.id);
      setDeleteDialogUser(null);
      loadUsers();
    } catch (err: unknown) {
      setDeleteDialogError(err instanceof Error ? err.message : "Löschen fehlgeschlagen.");
    } finally {
      setDeleteActionLoading(null);
    }
  }

  async function handleResetPassword(e: React.FormEvent) {
    e.preventDefault();
    if (!resetPasswordUserId) return;
    setResetPasswordLoading(true);
    setResetPasswordError("");
    try {
      await updateUser(resetPasswordUserId, { password: resetPasswordValue });
      setResetPasswordUserId(null);
      setResetPasswordValue("");
    } catch {
      setResetPasswordError("Passwort konnte nicht geändert werden.");
    } finally {
      setResetPasswordLoading(false);
    }
  }

  return {
    users,
    usersLoading,
    usersError,
    dialogOpen,
    setDialogOpen,
    newUsername,
    setNewUsername,
    newEmail,
    setNewEmail,
    newPassword,
    setNewPassword,
    newRole,
    setNewRole,
    createLoading,
    createError,
    userActionLoading,
    resetPasswordUserId,
    setResetPasswordUserId,
    resetPasswordValue,
    setResetPasswordValue,
    resetPasswordError,
    setResetPasswordError,
    resetPasswordLoading,
    deleteDialogUser,
    setDeleteDialogUser,
    deleteActionLoading,
    deleteDialogError,
    setDeleteDialogError,
    loadUsers,
    handleCreateUser,
    handleToggleActive,
    handleDeactivateConfirmed,
    handleDeleteConfirmed,
    handleResetPassword,
  };
}
