"use client";

import { useMemo, useState, type ChangeEvent } from "react";

import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import InputAdornment from "@mui/material/InputAdornment";
import OutlinedInput from "@mui/material/OutlinedInput";
import Snackbar from "@mui/material/Snackbar";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import SearchIcon from "@mui/icons-material/Search";
import ToggleOffIcon from "@mui/icons-material/ToggleOff";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";

import { Heading } from "@/components/ui/heading";
import { useAppLanguage } from "@/components/providers/app-language-provider";
import { isAdminRole } from "@/features/auth/auth-data";
import {
  useUserManagement,
  type UserRow,
} from "@/features/admin/user-management/hook/use-user-management";
import {
  UserFormDialog,
  type UserFormState,
} from "@/features/admin/user-management/components/user-form-dialog";
import { UserTable } from "@/features/admin/user-management/components/table/user-table";
import type { LoginTrail } from "@/features/admin/user-management/service/user-management-service";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";

const GRAY_50 = "#F9FAFB";
const GRAY_200 = "#E5E7EB";
const GRAY_500 = "#6B7280";

const emptyForm: UserFormState = {
  avatar: "",
  avatarFile: null,
  name: "",
  email: "",
  password: "",
  roleIds: [],
  position: "",
  status: "Active",
};

const pageText = {
  en: {
    title: "All User",
    subtitle: "Manage all user",
    addUser: "Add New User",
    searchPlaceholder: "Search by name, email, or position",
    editUserTitle: "Edit User",
    addUserTitle: "Add User",
    createUser: "Create User",
    saveChanges: "Save Changes",
    cancel: "Cancel",
    close: "Close",
    loading: "Loading users...",
    previous: "Previous",
    next: "Next",
    noUsersFound: "No users found.",
    editUser: "Edit user",
    deleteUser: "Delete user",
    loginTrails: "Login trails",
    deactivate: "Deactivate",
    activate: "Activate",
    adminActionBlocked: "Admin account cannot be deleted or deactivated.",
    nameRequired: "Name is required.",
    emailRequired: "Email is required.",
    passwordRequired: "Password is required.",
    positionRequired: "Position is required.",
    apiError: "Something went wrong. Please try again.",
    noLoginTrails: "No login trails yet.",
    noDevice: "No device",
    passwordCannotEdit: "Password cannot be changed here",
    invalidImage: "Please upload JPG, PNG, or WEBP image.",
    imageTooLarge: "Image must be smaller than 5MB.",
    deleteConfirm: (name: string) => `Delete user "${name}"?`,
    deleteTitle: "Delete User",
    deleteQuestion: "Are you sure you want to delete",
    deleteUndone: "This action cannot be undone.",
    deactivateConfirm: (name: string) => `Deactivate user "${name}"?`,
    activateConfirm: (name: string) => `Activate user "${name}"?`,
    deactivateTitle: "Deactivate User",
    deactivateQuestion: "Are you sure you want to deactivate",
    deactivateNote: "They will be signed out and cannot log in until reactivated.",
    activateTitle: "Activate User",
    activateQuestion: "Are you sure you want to activate",
    activateNote: "They will be able to log in again.",
    columns: {
      id: "ID",
      user: "User Name",
      email: "Email",
      position: "Position",
      status: "Status",
      logDevice: "Log Device",
      action: "",
    },
    fields: {
      profile: "Profile",
      uploadProfile: "Upload profile",
      changeProfile: "Change profile",
      name: "Name",
      email: "Gmail",
      password: "Password",
      role: "Role",
      position: "Position",
      status: "Status",
      created: "Created",
    },
    roles: {
      PRIVATE_SECTOR: "Private Sector",
      MINISTRY: "Ministry",
      ADMIN: "Admin",
    },
    statuses: {
      Active: "Active",
      Inactive: "Inactive",
    },
    success: {
      created: "User created successfully.",
      updated: "User updated successfully.",
      deleted: "User deleted successfully.",
      activated: "User activated successfully.",
      deactivated: "User deactivated successfully.",
    },
  },
  kh: {
    title: "អ្នកប្រើប្រាស់ទាំងអស់",
    subtitle: "មើល និងតាមដានអ្នកប្រើប្រាស់តាមមុខតំណែង ស្ថានភាព និងការចូលប្រើ។",
    addUser: "បន្ថែមអ្នកប្រើថ្មី",
    searchPlaceholder: "ស្វែងរកតាមឈ្មោះ អ៊ីមែល ឬមុខតំណែង",
    editUserTitle: "កែប្រែអ្នកប្រើ",
    addUserTitle: "បន្ថែមអ្នកប្រើ",
    createUser: "បង្កើតអ្នកប្រើ",
    saveChanges: "រក្សាទុក",
    cancel: "បោះបង់",
    close: "បិទ",
    loading: "កំពុងទាញយកអ្នកប្រើ...",
    previous: "ថយក្រោយ",
    next: "បន្ទាប់",
    noUsersFound: "រកមិនឃើញអ្នកប្រើប្រាស់។",
    editUser: "កែប្រែអ្នកប្រើ",
    deleteUser: "លុបអ្នកប្រើ",
    loginTrails: "ប្រវត្តិចូលប្រើ",
    deactivate: "បិទដំណើរការ",
    activate: "បើកដំណើរការ",
    adminActionBlocked: "មិនអាចលុប ឬបិទដំណើរការ Admin បានទេ។",
    nameRequired: "សូមបញ្ចូលឈ្មោះ។",
    emailRequired: "សូមបញ្ចូលអ៊ីមែល។",
    passwordRequired: "សូមបញ្ចូលពាក្យសម្ងាត់។",
    positionRequired: "សូមបញ្ចូលមុខតំណែង។",
    apiError: "មានបញ្ហា សូមព្យាយាមម្ដងទៀត។",
    noLoginTrails: "មិនទាន់មានប្រវត្តិចូលប្រើ។",
    noDevice: "មិនមានឧបករណ៍",
    passwordCannotEdit: "មិនអាចកែពាក្យសម្ងាត់នៅទីនេះ",
    invalidImage: "សូមបញ្ចូលរូបភាពប្រភេទ JPG, PNG ឬ WEBP។",
    imageTooLarge: "រូបភាពត្រូវតែតូចជាង 5MB។",
    deleteConfirm: (name: string) => `តើបងចង់លុបអ្នកប្រើ "${name}" មែនទេ?`,
    deleteTitle: "លុបអ្នកប្រើ",
    deleteQuestion: "តើបងពិតជាចង់លុប",
    deleteUndone: "សកម្មភាពនេះមិនអាចត្រឡប់វិញបានទេ។",
    deactivateConfirm: (name: string) =>
      `តើបងចង់បិទដំណើរការអ្នកប្រើ "${name}" មែនទេ?`,
    activateConfirm: (name: string) =>
      `តើបងចង់បើកដំណើរការអ្នកប្រើ "${name}" មែនទេ?`,
    deactivateTitle: "បិទដំណើរការអ្នកប្រើ",
    deactivateQuestion: "តើបងពិតជាចង់បិទដំណើរការ",
    deactivateNote:
      "អ្នកប្រើនឹងត្រូវចាកចេញ ហើយមិនអាចចូលប្រើបានទេ រហូតដល់បើកដំណើរការឡើងវិញ។",
    activateTitle: "បើកដំណើរការអ្នកប្រើ",
    activateQuestion: "តើបងពិតជាចង់បើកដំណើរការ",
    activateNote: "អ្នកប្រើនឹងអាចចូលប្រើបានម្ដងទៀត។",
    columns: {
      id: "លេខសម្គាល់",
      user: "ឈ្មោះអ្នកប្រើ",
      email: "អ៊ីមែល",
      position: "មុខតំណែង",
      status: "ស្ថានភាព",
      logDevice: "ឧបករណ៍ចូលប្រើ",
      action: "",
    },
    fields: {
      profile: "ប្រូហ្វាល់",
      uploadProfile: "បញ្ចូលរូបភាព",
      changeProfile: "ប្ដូររូបភាព",
      name: "ឈ្មោះ",
      email: "Gmail",
      password: "ពាក្យសម្ងាត់",
      role: "តួនាទី",
      position: "មុខតំណែង",
      status: "ស្ថានភាព",
      created: "បានបង្កើត",
    },
    roles: {
      PRIVATE_SECTOR: "ផ្នែកឯកជន",
      MINISTRY: "ក្រសួង",
      ADMIN: "អ្នកគ្រប់គ្រង",
    },
    statuses: {
      Active: "កំពុងដំណើរការ",
      Inactive: "បានបិទ",
    },
    success: {
      created: "បានបង្កើតអ្នកប្រើដោយជោគជ័យ។",
      updated: "បានកែប្រែអ្នកប្រើដោយជោគជ័យ។",
      deleted: "បានលុបអ្នកប្រើដោយជោគជ័យ។",
      activated: "បានបើកដំណើរការអ្នកប្រើដោយជោគជ័យ។",
      deactivated: "បានបិទដំណើរការអ្នកប្រើដោយជោគជ័យ។",
    },
  },
};

function formatDate(value?: string) {
  if (!value) {
    return "-";
  }

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return "-";
  }

  return date.toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

function formatDateTime(value?: string | null) {
  if (!value) {
    return "-";
  }

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return "-";
  }

  return date.toLocaleString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

// Combine the parsed device columns (deviceType • browser • OS) into one line
// for the login-trails dialog. Returns "-" when none of them are available.
function formatDeviceSummary(trail: LoginTrail) {
  const deviceParts: string[] = [];
  if (trail.deviceType) deviceParts.push(trail.deviceType);
  if (trail.browser) deviceParts.push(trail.browser);
  if (trail.os) deviceParts.push(trail.os);

  return deviceParts.length > 0 ? deviceParts.join(" • ") : "-";
}

// Localized label for the known seed roles; custom/new roles show their raw name.
const roleLabels: Record<string, { en: string; kh: string }> = {
  admin: { en: "Admin", kh: "អ្នកគ្រប់គ្រង" },
  private_sector: { en: "Private Sector", kh: "ផ្នែកឯកជន" },
  ministry: { en: "Ministry", kh: "ក្រសួង" },
};

function getRoleLabel(roleName: string, isKhmer: boolean) {
  const entry = roleLabels[roleName.trim().toLowerCase()];

  if (entry) {
    return isKhmer ? entry.kh : entry.en;
  }

  return roleName;
}

function isProtectedAdminUser(user: UserRow | null | undefined) {
  return user?.roles?.some((role) => isAdminRole(role.name)) ?? false;
}

export function UserManagementPage() {
  const theme = useTheme();
  const { language } = useAppLanguage();

  const isKhmer = language === "kh";
  const text = isKhmer ? pageText.kh : pageText.en;

  const {
    users,
    availableRoles,
    loading,
    saving,
    error,
    setError,
    createUser,
    updateUser,
    activateUser,
    deactivateUser,
    deleteUser,
    loginTrails,
    loginTrailsUser,
    loadingLoginTrails,
    openLoginTrails,
    closeLoginTrails,
  } = useUserManagement();

  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogKey, setDialogKey] = useState(0);
  const [editingUser, setEditingUser] = useState<UserRow | null>(null);
  const [form, setForm] = useState<UserFormState>({ ...emptyForm });
  const [formError, setFormError] = useState("");
  const [successMessage, setSuccessMessage] = useState("");
  const [searchTerm, setSearchTerm] = useState("");
  // The user the admin is about to delete. null = the confirm dialog is closed.
  const [deleteTarget, setDeleteTarget] = useState<UserRow | null>(null);
  // The user whose status (active/inactive) is about to change. null = closed.
  const [statusTarget, setStatusTarget] = useState<UserRow | null>(null);

  // Keep only the rows that match the search box. We search across name, email,
  // position, id, and role names (case-insensitive). Empty search = show all.
  const filteredUsers = useMemo(() => {
    const term = searchTerm.trim().toLowerCase();
    if (!term) return users;

    return users.filter((user) => {
      const searchableText = [
        user.name,
        user.email,
        user.position,
        user.id,
        ...user.roles.map((role) => role.name),
      ]
        .filter(Boolean)
        .join(" ")
        .toLowerCase();

      return searchableText.includes(term);
    });
  }, [users, searchTerm]);

  function getFriendlyCreateError(message: string) {
    const normalizedMessage = message.toLowerCase();

    if (
      normalizedMessage.includes("bad request") ||
      normalizedMessage.includes("400")
    ) {
      return isKhmer
        ? "បង្កើត ឬកែប្រែអ្នកប្រើមិនបាន។ សូមពិនិត្យ Gmail, Password, Role ឬរូបភាពម្ដងទៀត។"
        : "Cannot create or update user. Please check Gmail, Password, Role, or image again.";
    }

    if (
      normalizedMessage.includes("email") &&
      (normalizedMessage.includes("exist") ||
        normalizedMessage.includes("duplicate") ||
        normalizedMessage.includes("unique"))
    ) {
      return isKhmer
        ? "អ៊ីមែលនេះមានរួចហើយ សូមប្រើអ៊ីមែលផ្សេង។"
        : "This Gmail already exists. Please use another Gmail.";
    }

    return message || text.apiError;
  }

  function openCreateDialog() {
    setEditingUser(null);
    setForm({
      avatar: "",
      avatarFile: null,
      name: "",
      email: "",
      password: "",
      roleIds: [],
      position: "",
      status: "Active",
    });
    setFormError("");
    setError("");
    setDialogKey((previousKey) => previousKey + 1);
    setDialogOpen(true);
  }

  function openEditDialog(user: UserRow) {
    setEditingUser(user);
    setForm({
      avatar: user.avatar ?? "",
      avatarFile: null,
      name: user.name,
      email: user.email,
      password: "",
      roleIds: user.roles.map((role) => role.id),
      position: user.position,
      status: user.status,
    });
    setFormError("");
    setError("");
    setDialogKey((previousKey) => previousKey + 1);
    setDialogOpen(true);
  }

  function closeDialog() {
    setDialogOpen(false);
    setEditingUser(null);
    setForm({ ...emptyForm });
    setFormError("");
    setDialogKey((previousKey) => previousKey + 1);
  }

  function handleProfileUpload(event: ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];

    if (!file) {
      return;
    }

    const allowedTypes = ["image/png", "image/jpeg", "image/jpg", "image/webp"];

    if (!allowedTypes.includes(file.type)) {
      setFormError(text.invalidImage);
      event.target.value = "";
      return;
    }

    const maxSize = 5 * 1024 * 1024;

    if (file.size > maxSize) {
      setFormError(text.imageTooLarge);
      event.target.value = "";
      return;
    }

    const reader = new FileReader();

    reader.onload = () => {
      setForm((previousForm) => ({
        ...previousForm,
        avatar:
          typeof reader.result === "string"
            ? reader.result
            : previousForm.avatar,
        avatarFile: file,
      }));

      setFormError("");
    };

    reader.onerror = () => {
      setFormError(text.apiError);
    };

    reader.readAsDataURL(file);
    event.target.value = "";
  }

  async function saveUser() {
    const name = form.name.trim();
    const email = editingUser
      ? editingUser.email.trim().toLowerCase()
      : form.email.trim().toLowerCase();
    const password = form.password.trim();
    const position = form.position.trim();

    if (!name) {
      setFormError(text.nameRequired);
      return;
    }

    if (!email) {
      setFormError(text.emailRequired);
      return;
    }

    const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

    if (!validEmail) {
      setFormError(
        isKhmer
          ? "សូមបញ្ចូល Gmail ឲ្យបានត្រឹមត្រូវ។"
          : "Please enter a valid Gmail.",
      );
      return;
    }

    if (!editingUser && !password) {
      setFormError(text.passwordRequired);
      return;
    }

    if (!editingUser && password.length < 8) {
      setFormError(
        isKhmer
          ? "ពាក្យសម្ងាត់ត្រូវមានយ៉ាងតិច 8 តួអក្សរ។"
          : "Password must be at least 8 characters.",
      );
      return;
    }

    if (!position) {
      setFormError(text.positionRequired);
      return;
    }

    if (!editingUser) {
      const emailAlreadyExists = users.some((user) => {
        return user.email.trim().toLowerCase() === email;
      });

      if (emailAlreadyExists) {
        setFormError(
          isKhmer
            ? "អ៊ីមែលនេះមានរួចហើយ សូមប្រើអ៊ីមែលផ្សេង។"
            : "This Gmail already exists. Please use another Gmail.",
        );
        return;
      }
    }

    setError("");
    setFormError("");

    const isEditing = Boolean(editingUser);

    try {
      if (editingUser) {
        await updateUser(editingUser.id, {
          name,
          roleIds: form.roleIds,
          position,
          isActive: form.status === "Active",
          avatarFile: form.avatarFile,
        });
      } else {
        await createUser({
          name,
          email,
          password,
          roleIds: form.roleIds,
          position,
          avatarFile: form.avatarFile,
        });
      }

      closeDialog();
      setError("");
      setSuccessMessage(
        isEditing ? text.success.updated : text.success.created,
      );
    } catch (requestError) {
      const message =
        requestError instanceof Error ? requestError.message : text.apiError;

      setError("");
      setFormError(getFriendlyCreateError(message));
    }
  }

  // Step 1: open the confirm dialog (unless the user is a protected admin).
  function requestDeleteUser(user: UserRow) {
    if (isProtectedAdminUser(user)) {
      setError(text.adminActionBlocked);
      return;
    }

    setDeleteTarget(user);
  }

  // Step 2: actually delete once the admin confirms in the dialog.
  async function confirmDeleteUser() {
    if (!deleteTarget) {
      return;
    }

    try {
      await deleteUser(deleteTarget.id);
      setError("");
      setSuccessMessage(text.success.deleted);
    } catch (requestError) {
      setError(
        requestError instanceof Error ? requestError.message : text.apiError,
      );
    } finally {
      setDeleteTarget(null);
    }
  }

  // Step 1: open the confirm dialog for activate/deactivate.
  function requestToggleStatus(user: UserRow) {
    if (isProtectedAdminUser(user)) {
      setError(text.adminActionBlocked);
      return;
    }

    setStatusTarget(user);
  }

  // Step 2: run deactivate or activate once confirmed, based on current status.
  async function confirmToggleStatus() {
    if (!statusTarget) {
      return;
    }

    try {
      if (statusTarget.status === "Active") {
        await deactivateUser(statusTarget.id);
        setSuccessMessage(text.success.deactivated);
      } else {
        await activateUser(statusTarget.id);
        setSuccessMessage(text.success.activated);
      }
      setError("");
    } catch (requestError) {
      setError(
        requestError instanceof Error ? requestError.message : text.apiError,
      );
    } finally {
      setStatusTarget(null);
    }
  }

  async function openLoginTrailsAction(user: UserRow) {
    try {
      await openLoginTrails(user);
    } catch (requestError) {
      setError(
        requestError instanceof Error ? requestError.message : text.apiError,
      );
    }
  }

  // True when the pending status change is a deactivate (user is currently Active).
  const isDeactivating = statusTarget?.status === "Active";

  return (
    <Box
      sx={{
        width: "100%",
        minWidth: 0,
        overflowX: "hidden",
        minHeight: "calc(100dvh - 64px)",
        display: "flex",
        flexDirection: "column",
        bgcolor:
          theme.palette.mode === "dark"
            ? theme.palette.background.default
            : GRAY_50,
        px: { xs: 2, md: 3 },
        py: { xs: 2.5, md: 3 },
        fontFamily: isKhmer
          ? '"Kantumruy Pro", Inter, Arial, sans-serif'
          : "Inter, Arial, sans-serif",
      }}
    >
      <Heading
        title={text.title}
        description={text.subtitle}
        titleSx={{
          fontSize: { xs: 30, md: isKhmer ? 34 : 36 },
          fontWeight: 800,
          letterSpacing: 0,
        }}
        descriptionSx={{
          fontSize: 15,
          color: theme.palette.text.secondary,
        }}
        action={
          <Button
            variant="contained"
            onClick={openCreateDialog}
            sx={{
              height: 40,
              px: 2.25,
              borderRadius: "6px",
              bgcolor: "#154E82",
              color: "#FFFFFF",
              textTransform: "none",
              fontSize: 13,
              fontWeight: 700,
              boxShadow: "none",
              whiteSpace: "nowrap",
              "&:hover": {
                bgcolor: "#0F416E",
                boxShadow: "none",
              },
            }}
          >
            {text.addUser}
          </Button>
        }
      />

      <Box sx={{ height: 1, bgcolor: GRAY_200, mb: 2.5 }} />

      <OutlinedInput
        value={searchTerm}
        onChange={(event) => setSearchTerm(event.target.value)}
        placeholder={text.searchPlaceholder}
        startAdornment={
          <InputAdornment position="start">
            <SearchIcon sx={{ fontSize: 20, color: GRAY_500 }} />
          </InputAdornment>
        }
        sx={{
          mb: 2.5,
          width: { xs: "100%", sm: 360 },
          height: 40,
          borderRadius: "8px",
          backgroundColor:
            theme.palette.mode === "dark" ? alpha("#ffffff", 0.04) : "#ffffff",
          fontSize: 14,
        }}
      />

      <UserTable
        users={filteredUsers}
        isLoading={loading}
        error={error || null}
        emptyMessage={text.noUsersFound}
        labels={{
          columns: {
            id: text.columns.id,
            user: text.columns.user,
            email: text.columns.email,
            position: text.columns.position,
            status: text.columns.status,
            logDevice: text.columns.logDevice,
          },
          noDevice: text.noDevice,
          statuses: text.statuses,
          actions: {
            editUser: text.editUser,
            deleteUser: text.deleteUser,
            loginTrails: text.loginTrails,
            activate: text.activate,
            deactivate: text.deactivate,
          },
        }}
        isProtectedUser={isProtectedAdminUser}
        onEdit={openEditDialog}
        onOpenLoginTrails={openLoginTrailsAction}
        onToggleStatus={requestToggleStatus}
        onDelete={requestDeleteUser}
      />

      <UserFormDialog
        createdAtLabel={
          editingUser
            ? formatDate(editingUser.createdAt)
            : formatDate(new Date().toISOString())
        }
        dialogKey={dialogKey}
        error={formError}
        form={form}
        isEditing={Boolean(editingUser)}
        labels={{
          addUserTitle: text.addUserTitle,
          editUserTitle: text.editUserTitle,
          cancel: text.cancel,
          createUser: text.createUser,
          saveChanges: text.saveChanges,
          passwordCannotEdit: text.passwordCannotEdit,
          fields: {
            profile: text.fields.profile,
            uploadProfile: text.fields.uploadProfile,
            changeProfile: text.fields.changeProfile,
            name: text.fields.name,
            email: text.fields.email,
            password: text.fields.password,
            role: text.fields.role,
            position: text.fields.position,
            status: text.fields.status,
            created: text.fields.created,
          },
          statuses: text.statuses,
        }}
        onChange={setForm}
        onClose={closeDialog}
        onProfileUpload={handleProfileUpload}
        onSave={saveUser}
        open={dialogOpen}
        roleOptions={availableRoles.map((role) => ({
          id: role.id,
          label: getRoleLabel(role.name, isKhmer),
        }))}
        saving={saving}
      />

      <Dialog
        open={Boolean(loginTrailsUser)}
        onClose={closeLoginTrails}
        fullWidth
        maxWidth="md"
        slotProps={{
          paper: {
            sx: {
              borderRadius: "18px",
            },
          },
        }}
      >
        <DialogTitle sx={{ fontSize: 20, fontWeight: 800 }}>
          {text.loginTrails}

          {loginTrailsUser ? (
            <Typography sx={{ mt: 0.5, fontSize: 14, color: GRAY_500 }}>
              {loginTrailsUser.name} • {loginTrailsUser.email}
            </Typography>
          ) : null}
        </DialogTitle>

        <DialogContent>
          {loadingLoginTrails ? (
            <Box sx={{ py: 6, textAlign: "center" }}>
              <CircularProgress size={24} />
              <Typography sx={{ mt: 1.5, color: GRAY_500 }}>
                {text.loading}
              </Typography>
            </Box>
          ) : loginTrails.length === 0 ? (
            <Box
              sx={{
                py: 5,
                textAlign: "center",
                borderRadius: "14px",
                border: `1px solid ${GRAY_200}`,
                bgcolor: theme.palette.background.paper,
              }}
            >
              <Typography sx={{ color: GRAY_500, fontSize: 14 }}>
                {text.noLoginTrails}
              </Typography>
            </Box>
          ) : (
            <Box sx={{ display: "grid", gap: 1.5 }}>
              {loginTrails.map((trail: LoginTrail, index: number) => (
                <Box
                  key={String(trail.id ?? index)}
                  sx={{
                    p: 2,
                    borderRadius: "14px",
                    border: `1px solid ${GRAY_200}`,
                    bgcolor:
                      theme.palette.mode === "dark"
                        ? alpha(theme.palette.common.white, 0.03)
                        : GRAY_50,
                  }}
                >
                  <Typography sx={{ fontSize: 14, fontWeight: 800 }}>
                    Login: {formatDateTime(trail.createdAt)}
                  </Typography>

                  <Typography sx={{ mt: 0.5, fontSize: 13, color: GRAY_500 }}>
                    Logout: {formatDateTime(trail.loggedOutAt)}
                  </Typography>

                  <Typography sx={{ mt: 0.5, fontSize: 13, color: GRAY_500 }}>
                    Device: {formatDeviceSummary(trail)}
                  </Typography>

                  <Typography sx={{ mt: 0.5, fontSize: 13, color: GRAY_500 }}>
                    IP: {trail.ipAddress ?? "-"}
                  </Typography>

                  <Typography
                    sx={{
                      mt: 0.5,
                      fontSize: 13,
                      color: GRAY_500,
                      wordBreak: "break-word",
                    }}
                  >
                    Agent: {trail.userAgent ?? "-"}
                  </Typography>
                </Box>
              ))}
            </Box>
          )}
        </DialogContent>

        <DialogActions sx={{ px: 3, pb: 3 }}>
          <Button
            variant="contained"
            onClick={closeLoginTrails}
            sx={{
              borderRadius: "12px",
              bgcolor: "#111111",
              textTransform: "none",
              fontWeight: 800,
              boxShadow: "none",
              "&:hover": {
                bgcolor: "#000000",
                boxShadow: "none",
              },
            }}
          >
            {text.close}
          </Button>
        </DialogActions>
      </Dialog>

      <ConfirmDialog
        open={Boolean(deleteTarget)}
        title={text.deleteTitle}
        description={
          <>
            {text.deleteQuestion}{" "}
            <Box
              component="strong"
              sx={{ fontWeight: 700, color: "text.primary" }}
            >
              {deleteTarget?.name || deleteTarget?.email}
            </Box>
            ?
            <br />
            {text.deleteUndone}
          </>
        }
        confirmLabel={text.deleteUser}
        cancelLabel={text.cancel}
        loading={saving}
        onConfirm={confirmDeleteUser}
        onCancel={() => setDeleteTarget(null)}
      />

      <ConfirmDialog
        open={Boolean(statusTarget)}
        title={isDeactivating ? text.deactivateTitle : text.activateTitle}
        description={
          <>
            {isDeactivating ? text.deactivateQuestion : text.activateQuestion}{" "}
            <Box
              component="strong"
              sx={{ fontWeight: 700, color: "text.primary" }}
            >
              {statusTarget?.name || statusTarget?.email}
            </Box>
            ?
            <br />
            {isDeactivating ? text.deactivateNote : text.activateNote}
          </>
        }
        confirmLabel={isDeactivating ? text.deactivate : text.activate}
        cancelLabel={text.cancel}
        tone={isDeactivating ? "danger" : "primary"}
        confirmIcon={
          isDeactivating ? (
            <ToggleOffIcon sx={{ fontSize: 20 }} />
          ) : (
            <ToggleOnIcon sx={{ fontSize: 20 }} />
          )
        }
        loading={saving}
        onConfirm={confirmToggleStatus}
        onCancel={() => setStatusTarget(null)}
      />

      <Snackbar
        open={Boolean(successMessage)}
        autoHideDuration={3000}
        onClose={() => setSuccessMessage("")}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
      >
        <Alert
          severity="success"
          variant="filled"
          onClose={() => setSuccessMessage("")}
          sx={{ fontWeight: 700 }}
        >
          {successMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
}
