import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { isAxiosError } from "axios";
import {
  Badge,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@edr/ui-common";
import { Network, RefreshCw, Search, UserCheck, UserMinus, Users } from "lucide-react";

import { api } from "@/auth/http";
import { useAuth } from "@/auth/useAuth";

interface LocaleText {
  en?: string;
  am?: string;
}

interface OrganizationRecord {
  id: string;
  key: string;
  name: LocaleText;
}

interface EmployeeUserRecord {
  id: string;
  name?: LocaleText;
  email?: string;
  phoneNumber?: string;
  username?: string;
}

interface EmployeePositionSummary {
  id: string;
  position?: {
    id: string;
    name?: LocaleText;
  };
}

interface EmployeeRecord {
  id: string;
  name?: LocaleText;
  user?: EmployeeUserRecord;
  status?: string;
  employeePositions?: EmployeePositionSummary[];
}

interface RoleRecord {
  id: string;
  key: string;
  name: LocaleText;
}

interface UserFormState {
  nameEn: string;
  nameAm: string;
  email: string;
  username: string;
  phoneNumber: string;
  assignOrganizationAdmin: boolean;
}

interface ListResponse<T> {
  items?: T[];
  data?: T[];
}

const RESERVED_ROLE_KEYS = new Set(["super_admin", "organization_admin", "unit_admin"]);

const emptyUserForm: UserFormState = {
  nameEn: "",
  nameAm: "",
  email: "",
  username: "",
  phoneNumber: "",
  assignOrganizationAdmin: false,
};

const inputClassName =
  "w-full rounded-xl border border-border bg-background px-3 py-2.5 text-sm text-foreground outline-none transition focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 dark:focus:ring-emerald-950";
const buttonClassName =
  "inline-flex items-center justify-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60";

const getLocaleLabel = (value?: LocaleText | null, fallback = "Unnamed") => {
  if (!value) {
    return fallback;
  }

  return value.en ?? value.am ?? fallback;
};

const getItems = <T,>(payload: ListResponse<T> | T[] | undefined | null) => {
  if (!payload) {
    return [] as T[];
  }

  if (Array.isArray(payload)) {
    return payload;
  }

  return payload.items ?? payload.data ?? [];
};

const mergeEmployeesByUser = (employees: EmployeeRecord[]) => {
  const employeesByUserId = new Map<string, EmployeeRecord>();

  for (const employee of employees) {
    const userId = employee.user?.id;

    if (!userId) {
      employeesByUserId.set(employee.id, employee);
      continue;
    }

    const existing = employeesByUserId.get(userId);

    if (!existing) {
      employeesByUserId.set(userId, employee);
      continue;
    }

    const existingPositions = existing.employeePositions ?? [];
    const nextPositions = employee.employeePositions ?? [];
    const mergedPositions = Array.from(
      new Map(
        [...existingPositions, ...nextPositions].map((position) => [position.id, position]),
      ).values(),
    );

    employeesByUserId.set(userId, {
      ...existing,
      ...employee,
      id: existing.id,
      name: existing.name ?? employee.name,
      status: existing.status ?? employee.status,
      user: existing.user ?? employee.user,
      employeePositions: mergedPositions,
    });
  }

  return [...employeesByUserId.values()];
};

const getErrorMessage = (error: unknown, fallback: string) => {
  if (isAxiosError(error)) {
    const message = error.response?.data?.message;
    if (typeof message === "string") {
      return message;
    }
    if (Array.isArray(message) && typeof message[0] === "string") {
      return message[0];
    }
  }

  return error instanceof Error ? error.message : fallback;
};

const Field = ({ label, children }: { label: string; children: ReactNode }) => (
  <label className="flex flex-col gap-2 text-sm">
    <span className="font-medium text-foreground">{label}</span>
    {children}
  </label>
);

const ManagementDialog = ({
  open,
  title,
  description,
  onOpenChange,
  children,
}: {
  open: boolean;
  title: string;
  description?: string;
  onOpenChange: (open: boolean) => void;
  children: ReactNode;
}) => (
  <Dialog open={open} onOpenChange={onOpenChange}>
    <DialogContent className="sm:max-w-2xl">
      <DialogHeader>
        <DialogTitle>{title}</DialogTitle>
        {description ? <DialogDescription>{description}</DialogDescription> : null}
      </DialogHeader>
      {children}
    </DialogContent>
  </Dialog>
);

const UsersPage = () => {
  const { user } = useAuth();
  const [organizations, setOrganizations] = useState<OrganizationRecord[]>([]);
  const [orgEmployees, setOrgEmployees] = useState<EmployeeRecord[]>([]);
  const [selectedOrgId, setSelectedOrgId] = useState<string | null>(null);
  const [orgUserSearch, setOrgUserSearch] = useState("");
  const [createUserForm, setCreateUserForm] = useState<UserFormState>(emptyUserForm);
  const [availableRoles, setAvailableRoles] = useState<RoleRecord[]>([]);
  const [roleIds, setRoleIds] = useState<string[]>([]);
  const [selectedRoleUser, setSelectedRoleUser] = useState<EmployeeRecord | null>(null);
  const [loading, setLoading] = useState(true);
  const [orgEmployeesLoading, setOrgEmployeesLoading] = useState(false);
  const [rolesLoading, setRolesLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [actionError, setActionError] = useState<string | null>(null);
  const [actionSuccess, setActionSuccess] = useState<string | null>(null);
  const [isCreateUserOpen, setIsCreateUserOpen] = useState(false);
  const [isManageRolesOpen, setIsManageRolesOpen] = useState(false);

  const isSuperAdmin = Boolean(user?.roles?.some((role) => role.key === "super_admin"));
  const allowedOrgIds = useMemo(
    () => new Set((user?.employee ?? []).map((employee) => employee.organizationId).filter(Boolean)),
    [user?.employee],
  );

  const visibleOrganizations = useMemo(() => {
    if (isSuperAdmin) {
      return organizations;
    }

    return organizations.filter((organization) => allowedOrgIds.has(organization.id));
  }, [allowedOrgIds, isSuperAdmin, organizations]);

  const selectedOrganization = useMemo(
    () => visibleOrganizations.find((item) => item.id === selectedOrgId) ?? null,
    [selectedOrgId, visibleOrganizations],
  );

  const filteredOrgEmployees = useMemo(() => {
    const query = orgUserSearch.trim().toLowerCase();

    return orgEmployees.filter((employee) => {
      const label = getLocaleLabel(
        employee.name ?? employee.user?.name,
        employee.user?.email ?? employee.id,
      ).toLowerCase();
      const email = employee.user?.email?.toLowerCase() ?? "";
      const username = employee.user?.username?.toLowerCase() ?? "";

      if (!query) {
        return true;
      }

      return label.includes(query) || email.includes(query) || username.includes(query);
    });
  }, [orgEmployees, orgUserSearch]);

  const resetMessages = () => {
    setActionError(null);
    setActionSuccess(null);
  };

  const loadOrganizations = useCallback(async () => {
    setLoading(true);
    setLoadError(null);

    try {
      const response = await api.get<ListResponse<OrganizationRecord>>("/organizations");
      setOrganizations(getItems(response.data));
    } catch (error) {
      setLoadError(getErrorMessage(error, "Failed to load organizations."));
    } finally {
      setLoading(false);
    }
  }, []);

  const loadOrgEmployees = useCallback(async (organizationId: string) => {
    setOrgEmployeesLoading(true);

    try {
      const response = await api.get<ListResponse<EmployeeRecord>>(
        `/backoffice/organizations/${organizationId}/employees`,
      );
      setOrgEmployees(mergeEmployeesByUser(getItems(response.data)));
    } catch {
      setOrgEmployees([]);
    } finally {
      setOrgEmployeesLoading(false);
    }
  }, []);

  useEffect(() => {
    void loadOrganizations();
  }, [loadOrganizations]);

  useEffect(() => {
    if (!visibleOrganizations.length) {
      setSelectedOrgId(null);
      setOrgEmployees([]);
      return;
    }

    if (selectedOrgId && visibleOrganizations.some((organization) => organization.id === selectedOrgId)) {
      return;
    }

    setSelectedOrgId(visibleOrganizations[0]?.id ?? null);
  }, [selectedOrgId, visibleOrganizations]);

  useEffect(() => {
    if (!selectedOrgId) {
      setOrgEmployees([]);
      return;
    }

    void loadOrgEmployees(selectedOrgId);
  }, [loadOrgEmployees, selectedOrgId]);

  const handleRefresh = async () => {
    resetMessages();
    await Promise.all([
      loadOrganizations(),
      selectedOrgId ? loadOrgEmployees(selectedOrgId) : Promise.resolve(),
    ]);
  };

  const handleSelectOrganization = async (organizationId: string) => {
    setSelectedOrgId(organizationId);
    setOrgEmployees([]);
    resetMessages();

    try {
      await loadOrgEmployees(organizationId);
    } catch {
      // Loader already handles fallback state.
    }
  };

  const openCreateUserDialog = () => {
    if (!selectedOrgId) {
      setActionError("Select an organization before adding a user.");
      return;
    }

    setCreateUserForm(emptyUserForm);
    resetMessages();
    setIsCreateUserOpen(true);
  };

  const openManageRolesDialog = async (employee: EmployeeRecord) => {
    if (!selectedOrgId || !employee.user?.id) {
      return;
    }

    setRolesLoading(true);
    resetMessages();
    setSelectedRoleUser(employee);
    setIsManageRolesOpen(true);

    try {
      const [rolesResponse, assignedResponse] = await Promise.all([
        api.get<ListResponse<RoleRecord>>("/roles"),
        api.get<RoleRecord[]>(`/backoffice/organizations/${selectedOrgId}/employee-users/${employee.user.id}/roles`),
      ]);
      const roles = getItems(rolesResponse.data).filter((role) => !RESERVED_ROLE_KEYS.has(role.key));
      setAvailableRoles(roles);
      setRoleIds(getItems(assignedResponse.data).map((role) => role.id));
    } catch (error) {
      setActionError(getErrorMessage(error, "Failed to load user roles."));
      setAvailableRoles([]);
      setRoleIds([]);
    } finally {
      setRolesLoading(false);
    }
  };

  const handleCreateUser = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!selectedOrgId) {
      setActionError("Select an organization before adding a user.");
      return;
    }

    setSubmitting(true);
    resetMessages();

    try {
      const response = await api.post<EmployeeRecord>(
        `/backoffice/organizations/${selectedOrgId}/users`,
        {
          username: createUserForm.username.trim(),
          phoneNumber: createUserForm.phoneNumber.trim(),
          email: createUserForm.email.trim(),
          name: {
            am: createUserForm.nameAm.trim(),
            en: createUserForm.nameEn.trim(),
          },
          assignOrganizationAdmin: createUserForm.assignOrganizationAdmin,
        },
      );

      const shouldAssignOrganizationAdmin = createUserForm.assignOrganizationAdmin;
      setCreateUserForm(emptyUserForm);
      setIsCreateUserOpen(false);
      setActionSuccess(
        shouldAssignOrganizationAdmin
          ? "User created as organization admin. Default password: 12345678."
          : "User created. Default password: 12345678.",
      );
      await loadOrgEmployees(selectedOrgId);

      if (!shouldAssignOrganizationAdmin) {
        await openManageRolesDialog(response.data);
      }
    } catch (error) {
      setActionError(getErrorMessage(error, "Failed to create user."));
    } finally {
      setSubmitting(false);
    }
  };

  const handleSaveRoles = async () => {
    if (!selectedOrgId || !selectedRoleUser?.user?.id) {
      return;
    }

    setSubmitting(true);
    resetMessages();

    try {
      await api.put(
        `/backoffice/organizations/${selectedOrgId}/employee-users/${selectedRoleUser.user.id}/roles`,
        { roleIds },
      );
      setActionSuccess("User roles updated.");
      setIsManageRolesOpen(false);
    } catch (error) {
      setActionError(getErrorMessage(error, "Failed to update user roles."));
    } finally {
      setSubmitting(false);
    }
  };

  const handleToggleUserActivation = async (employee: EmployeeRecord) => {
    if (!employee.user?.id) {
      return;
    }

    const isInactive = employee.status?.toLowerCase() === "inactive";
    setSubmitting(true);
    resetMessages();

    try {
      await api.patch(`/users/${isInactive ? "activate-user" : "deactivate-user"}/${employee.user.id}`);
      setActionSuccess(isInactive ? "User activated." : "User deactivated.");
      if (selectedOrgId) {
        await loadOrgEmployees(selectedOrgId);
      }
    } catch (error) {
      setActionError(getErrorMessage(error, "Failed to update user status."));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section className="space-y-6 bg-background p-6 text-foreground">
      <div className="rounded-3xl border border-border bg-linear-to-br from-emerald-100 via-card to-background p-6 shadow-sm dark:from-emerald-950/30 dark:via-card dark:to-background">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div className="flex items-start gap-4">
            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-100 text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300">
              <Network className="h-6 w-6" />
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium uppercase tracking-[0.2em] text-emerald-700 dark:text-emerald-300">
                User management
              </p>
              <h1 className="text-2xl font-semibold text-foreground">Users</h1>
              <p className="max-w-3xl text-sm text-muted-foreground">
                Create organization users, activate or deactivate access, and assign organization-scoped roles.
              </p>
            </div>
          </div>

          <button
            type="button"
            onClick={() => void handleRefresh()}
            className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
          >
            <RefreshCw className="h-4 w-4" />
            Refresh
          </button>
        </div>
      </div>

      {actionSuccess ? (
        <div className="rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-200">
          {actionSuccess}
        </div>
      ) : null}

      {actionError ? (
        <div className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700 dark:border-rose-900/60 dark:bg-rose-950/40 dark:text-rose-200">
          {actionError}
        </div>
      ) : null}

      {loadError ? (
        <div className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700 dark:border-rose-900/60 dark:bg-rose-950/40 dark:text-rose-200">
          {loadError}
        </div>
      ) : null}

      {loading ? (
        <div className="rounded-3xl border border-border bg-card p-6 text-sm text-muted-foreground shadow-sm">
          Loading users workspace...
        </div>
      ) : (
        <div className="grid gap-6 xl:grid-cols-4">
          <aside className="rounded-3xl border border-border bg-card p-5 shadow-sm">
            <div className="mb-5">
              <h2 className="text-lg font-semibold text-card-foreground">Organization</h2>
              <p className="text-sm text-muted-foreground">
                {isSuperAdmin ? "All organizations" : "Assigned organizations"}
              </p>
            </div>

            {visibleOrganizations.length ? (
              <ul className="space-y-2">
                {visibleOrganizations.map((organization) => {
                  const isActive = selectedOrgId === organization.id;
                  const isDisabled = !isSuperAdmin;

                  return (
                    <li key={organization.id}>
                      <button
                        type="button"
                        disabled={isDisabled}
                        onClick={() => void handleSelectOrganization(organization.id)}
                        className={`flex w-full items-center justify-between gap-2 rounded-2xl border px-4 py-3 text-left transition ${
                          isActive
                            ? "border-emerald-300 bg-emerald-50 text-emerald-900 dark:border-emerald-800 dark:bg-emerald-950/40 dark:text-emerald-100"
                            : "border-border bg-card text-card-foreground hover:border-emerald-200 hover:bg-emerald-50/80 dark:hover:bg-slate-900"
                        } ${isDisabled ? "cursor-default" : ""}`}
                      >
                        <div className="min-w-0">
                          <div className="truncate font-medium">
                            {getLocaleLabel(organization.name, organization.key)}
                          </div>
                          <div className="truncate text-xs text-muted-foreground">{organization.key}</div>
                        </div>
                        {!isSuperAdmin ? <Badge className="bg-sky-100 text-sky-700">Assigned</Badge> : null}
                      </button>
                    </li>
                  );
                })}
              </ul>
            ) : (
              <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                No organizations available.
              </div>
            )}

            <button
              type="button"
              disabled={!selectedOrgId || submitting}
              onClick={openCreateUserDialog}
              className={`${buttonClassName} mt-4 w-full bg-emerald-600 text-white hover:bg-emerald-700`}
            >
              Add user to organization
            </button>
          </aside>

          <section className="rounded-3xl border border-border bg-card p-5 shadow-sm xl:col-span-3">
            <div className="mb-5 flex flex-wrap items-center justify-between gap-3">
              <div>
                <h2 className="text-lg font-semibold text-card-foreground">Users</h2>
                <p className="text-sm text-muted-foreground">
                  {selectedOrganization
                    ? `Manage users in ${getLocaleLabel(selectedOrganization.name, selectedOrganization.key)}`
                    : "Select an organization"}
                </p>
              </div>
              <div className="rounded-full border border-border bg-muted px-3 py-1 text-sm font-medium text-muted-foreground">
                {orgEmployees.length} users
              </div>
            </div>

            <div className="relative mb-4">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <input
                className={`${inputClassName} pl-9`}
                value={orgUserSearch}
                onChange={(event) => setOrgUserSearch(event.target.value)}
                placeholder="Search users"
              />
            </div>

            {orgEmployeesLoading ? (
              <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                Loading users...
              </div>
            ) : filteredOrgEmployees.length ? (
              <div className="space-y-3">
                {filteredOrgEmployees.map((employee) => {
                  const userId = employee.user?.id;
                  const displayName = getLocaleLabel(
                    employee.name ?? employee.user?.name,
                    employee.user?.email ?? employee.id,
                  );
                  const assignedPositions = employee.employeePositions
                    ?.map((position) => getLocaleLabel(position.position?.name, position.position?.id ?? ""))
                    .filter(Boolean)
                    .join(", ");

                  return (
                    <article
                      key={employee.id}
                      className="rounded-2xl border border-border bg-background p-4 shadow-sm"
                    >
                      <div className="flex flex-wrap items-start justify-between gap-4">
                        <div className="space-y-2">
                          <div className="flex flex-wrap items-center gap-2">
                            <h3 className="text-base font-semibold text-foreground">{displayName}</h3>
                            {employee.status ? (
                              <Badge className="bg-gray-100 text-gray-700">{employee.status}</Badge>
                            ) : null}
                          </div>
                          <div className="text-sm text-muted-foreground">
                            {employee.user?.email || employee.user?.username || "No contact info"}
                          </div>
                          <div className="text-sm text-muted-foreground">
                            {assignedPositions ? `Current positions: ${assignedPositions}` : "No positions assigned."}
                          </div>
                        </div>

                        <div className="flex flex-wrap gap-2">
                          <button
                            type="button"
                            disabled={!userId || submitting}
                            onClick={() => void handleToggleUserActivation(employee)}
                            className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
                          >
                            {employee.status?.toLowerCase() === "inactive" ? (
                              <>
                                <UserCheck className="h-4 w-4" />
                                Activate
                              </>
                            ) : (
                              <>
                                <UserMinus className="h-4 w-4" />
                                Deactivate
                              </>
                            )}
                          </button>

                          <button
                            type="button"
                            disabled={!userId || !selectedOrgId || submitting}
                            onClick={() => void openManageRolesDialog(employee)}
                            className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
                          >
                            <Users className="h-4 w-4" />
                            Manage roles
                          </button>
                        </div>
                      </div>
                    </article>
                  );
                })}
              </div>
            ) : (
              <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                {selectedOrganization
                  ? "No users found for this organization."
                  : "Select an organization to load users."}
              </div>
            )}
          </section>
        </div>
      )}

      <ManagementDialog
        open={isCreateUserOpen}
        onOpenChange={setIsCreateUserOpen}
        title="Add user"
        description={
          selectedOrganization
            ? `Create a loginable user in ${getLocaleLabel(selectedOrganization.name, selectedOrganization.key)}. Default password: 12345678.`
            : "Create a loginable user in the selected organization."
        }
      >
        <form className="space-y-4" onSubmit={handleCreateUser}>
          <Field label="English name">
            <input
              className={inputClassName}
              value={createUserForm.nameEn}
              onChange={(event) => setCreateUserForm((current) => ({ ...current, nameEn: event.target.value }))}
            />
          </Field>
          <Field label="Amharic name">
            <input
              className={inputClassName}
              value={createUserForm.nameAm}
              onChange={(event) => setCreateUserForm((current) => ({ ...current, nameAm: event.target.value }))}
            />
          </Field>
          <Field label="Email">
            <input
              className={inputClassName}
              type="email"
              value={createUserForm.email}
              onChange={(event) => setCreateUserForm((current) => ({ ...current, email: event.target.value }))}
            />
          </Field>
          <Field label="Username">
            <input
              className={inputClassName}
              value={createUserForm.username}
              onChange={(event) => setCreateUserForm((current) => ({ ...current, username: event.target.value }))}
            />
          </Field>
          <Field label="Phone number">
            <input
              className={inputClassName}
              value={createUserForm.phoneNumber}
              onChange={(event) => setCreateUserForm((current) => ({ ...current, phoneNumber: event.target.value }))}
            />
          </Field>
          <label className="flex items-start gap-3 rounded-2xl border border-border bg-background px-4 py-3 text-sm">
            <input
              type="checkbox"
              checked={createUserForm.assignOrganizationAdmin}
              onChange={(event) =>
                setCreateUserForm((current) => ({
                  ...current,
                  assignOrganizationAdmin: event.target.checked,
                }))
              }
            />
            <div>
              <div className="font-medium text-foreground">Create as organization admin</div>
              <div className="text-xs text-muted-foreground">
                Also assigns built-in org admin access and the freight org manager role.
              </div>
            </div>
          </label>
          <div className="flex justify-end gap-2">
            <button
              type="button"
              onClick={() => setIsCreateUserOpen(false)}
              className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
            >
              Cancel
            </button>
            <button type="submit" disabled={submitting} className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}>
              Create user
            </button>
          </div>
        </form>
      </ManagementDialog>

      <ManagementDialog
        open={isManageRolesOpen}
        onOpenChange={setIsManageRolesOpen}
        title="Manage roles"
        description={
          selectedRoleUser
            ? `Assign organization-scoped roles for ${getLocaleLabel(selectedRoleUser.name ?? selectedRoleUser.user?.name, selectedRoleUser.user?.email ?? selectedRoleUser.id)}.`
            : undefined
        }
      >
        <div className="space-y-4">
          {rolesLoading ? (
            <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
              Loading roles...
            </div>
          ) : (
            <div className="max-h-[420px] space-y-2 overflow-y-auto pr-1">
              {availableRoles.map((role) => (
                <label
                  key={role.id}
                  className="flex items-center gap-3 rounded-2xl border border-border bg-background px-4 py-3 text-sm"
                >
                  <input
                    type="checkbox"
                    checked={roleIds.includes(role.id)}
                    onChange={(event) => {
                      setRoleIds((current) =>
                        event.target.checked
                          ? [...current, role.id]
                          : current.filter((currentRoleId) => currentRoleId !== role.id),
                      );
                    }}
                  />
                  <div>
                    <div className="font-medium text-foreground">{getLocaleLabel(role.name, role.key)}</div>
                    <div className="text-xs text-muted-foreground">{role.key}</div>
                  </div>
                </label>
              ))}
              {!availableRoles.length ? (
                <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                  No assignable roles available.
                </div>
              ) : null}
            </div>
          )}
          <div className="flex justify-end gap-2">
            <button
              type="button"
              onClick={() => setIsManageRolesOpen(false)}
              className={`${buttonClassName} border border-border bg-card text-card-foreground hover:bg-accent hover:text-accent-foreground`}
            >
              Cancel
            </button>
            <button
              type="button"
              disabled={submitting || rolesLoading}
              onClick={() => void handleSaveRoles()}
              className={`${buttonClassName} bg-emerald-600 text-white hover:bg-emerald-700`}
            >
              Save roles
            </button>
          </div>
        </div>
      </ManagementDialog>
    </section>
  );
};

export default UsersPage;
