import { useCallback, useEffect, useState } from "react";
import { KeyRound, UserCheck, UserX } from "lucide-react";
import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";
import ResetUserPasswordDialog from "./ResetUserPasswordDialog";

export default function UsersPanel() {
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("Users", "Edit");

  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [savingUserId, setSavingUserId] = useState(null);
  const [resetPasswordUser, setResetPasswordUser] = useState(null);

  const loadUsers = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    const [usersResult, rolesResult] = await Promise.all([
      window.omsorg.users.list(),
      window.omsorg.roles.list(),
    ]);

    if (usersResult.ok) {
      setUsers(usersResult.data ?? []);
    } else {
      setError("Nutzer konnten nicht geladen werden.");
    }

    if (rolesResult.ok) {
      setRoles(rolesResult.data ?? []);
    }

    setIsLoading(false);
  }, []);

  useEffect(() => {
    loadUsers();
  }, [loadUsers]);

  function roleIdForName(roleName) {
    return roles.find((role) => role.name === roleName)?.id ?? "";
  }

  async function handleRoleChange(user, roleId) {
    setSavingUserId(user.id);
    const result = await window.omsorg.users.update(user.id, { roleId, isActive: user.isActive });
    setSavingUserId(null);
    if (!result.ok) {
      setError("Rolle konnte nicht geändert werden.");
      return;
    }
    await loadUsers();
  }

  async function handleToggleActive(user) {
    setSavingUserId(user.id);
    const result = await window.omsorg.users.update(user.id, {
      roleId: roleIdForName(user.roleName),
      isActive: !user.isActive,
    });
    setSavingUserId(null);
    if (!result.ok) {
      setError("Status konnte nicht geändert werden.");
      return;
    }
    await loadUsers();
  }

  return (
    <div className="settings-users-panel">
      {isLoading && <p>Lädt...</p>}
      {error && <p className="login-error">{error}</p>}

      {!isLoading && !error && users.length === 0 && <p>Noch keine Benutzerkonten angelegt.</p>}

      {!isLoading && users.length > 0 && (
        <ul className="debug-sessions-list">
          {users.map((user) => (
            <li key={user.id} className="debug-sessions-row">
              <div>
                <strong>{user.username}</strong>
                <p className="debug-sessions-meta">
                  {user.isActive ? "Aktiv" : "Inaktiv"}
                  {user.mustChangePassword ? " · Passwortwechsel beim nächsten Login" : ""}
                </p>
              </div>

              {canEdit ? (
                <select
                  value={roleIdForName(user.roleName)}
                  onChange={(event) => handleRoleChange(user, event.target.value)}
                  disabled={savingUserId === user.id}
                >
                  {roles.map((role) => (
                    <option key={role.id} value={role.id}>
                      {role.name}
                    </option>
                  ))}
                </select>
              ) : (
                <span>{user.roleName}</span>
              )}

              {canEdit && (
                <div className="debug-sessions-actions">
                  <OmsorgButton
                    icon={user.isActive ? UserX : UserCheck}
                    variant={user.isActive ? "danger" : "secondary"}
                    disabled={savingUserId === user.id}
                    onClick={() => handleToggleActive(user)}
                  >
                    {user.isActive ? "Deaktivieren" : "Aktivieren"}
                  </OmsorgButton>

                  <OmsorgButton icon={KeyRound} variant="secondary" onClick={() => setResetPasswordUser(user)}>
                    Passwort zurücksetzen
                  </OmsorgButton>
                </div>
              )}
            </li>
          ))}
        </ul>
      )}

      {resetPasswordUser && (
        <ResetUserPasswordDialog
          user={resetPasswordUser}
          onClose={() => setResetPasswordUser(null)}
          onDone={() => {
            setResetPasswordUser(null);
            loadUsers();
          }}
        />
      )}
    </div>
  );
}
