"use client";

import { useState } from "react";

import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import HistoryIcon from "@mui/icons-material/History";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import ToggleOffIcon from "@mui/icons-material/ToggleOff";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";

import { AppStatusBadge } from "@/components/ui/badge";
import type { UserRow } from "@/features/admin/user-management/hook/use-user-management";
import type { AdminUserStatus } from "@/features/admin/user-management/service/user-management-service";

type UserActionLabels = {
  editUser: string;
  deleteUser: string;
  loginTrails: string;
  activate: string;
  deactivate: string;
};

type UserActionCellProps = {
  user: UserRow;
  labels: UserActionLabels;
  isProtected: boolean;
  onEdit: (user: UserRow) => void;
  onOpenLoginTrails: (user: UserRow) => void;
  onToggleStatus: (user: UserRow) => void;
  onDelete: (user: UserRow) => void;
};

function getAvatarText(name: string) {
  const cleanName = name.trim();

  if (!cleanName) {
    return "US";
  }

  return cleanName.slice(0, 2).toUpperCase();
}

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",
  });
}

export function UserNameCell({ user }: { user: UserRow }) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box
      sx={{
        minWidth: 0,
        width: "100%",
        display: "flex",
        alignItems: "center",
        gap: 1.5,
      }}
    >
      <Avatar
        src={user.avatar}
        alt={user.name}
        sx={{
          width: 40,
          height: 40,
          bgcolor: isDark ? alpha("#ffffff", 0.08) : "#f5f7fa",
          color: isDark ? alpha("#ffffff", 0.72) : "#154e82",
          fontSize: 13,
          fontWeight: 700,
        }}
      >
        {getAvatarText(user.name)}
      </Avatar>

      <Typography
        noWrap
        sx={{
          minWidth: 0,
          color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
          fontSize: 14,
          fontWeight: 600,
        }}
      >
        {user.name || "-"}
      </Typography>
    </Box>
  );
}

export function UserTextCell({
  align = "left",
  value,
}: {
  align?: "left" | "center";
  value: string;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Typography
      noWrap
      sx={{
        width: "100%",
        color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
        fontSize: 14,
        fontWeight: 500,
        textAlign: align,
      }}
    >
      {value || "-"}
    </Typography>
  );
}

export function UserStatusBadgeCell({
  status,
  label,
}: {
  status: AdminUserStatus;
  label: string;
}) {
  return (
    <Box
      title={label}
      aria-label={label}
      sx={{
        width: "100%",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <AppStatusBadge status={status} label={label} sx={{ minWidth: 80 }} />
    </Box>
  );
}

export function UserLogDeviceCell({
  align = "left",
  deviceName,
  activityDate,
  ipAddress,
  deviceType,
}: {
  align?: "left" | "center";
  deviceName: string;
  activityDate?: string | null;
  ipAddress?: string | null;
  deviceType?: string | null;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  // Hover tooltip: show the device type and IP when we have them,
  // e.g. "desktop • IP: 203.0.113.5".
  const tooltipParts: string[] = [];
  if (deviceType) tooltipParts.push(deviceType);
  if (ipAddress) tooltipParts.push(`IP: ${ipAddress}`);
  const tooltipText = tooltipParts.length > 0 ? tooltipParts.join(" • ") : undefined;

  return (
    <Box
      title={tooltipText}
      sx={{ minWidth: 0, width: "100%", textAlign: align }}
    >
      <Typography
        noWrap
        sx={{
          color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
          fontSize: 14,
          fontWeight: 500,
        }}
      >
        {deviceName}
      </Typography>

      <Typography
        noWrap
        sx={{
          mt: 0.5,
          color: isDark ? alpha("#ffffff", 0.58) : "#717680",
          fontSize: 12,
          fontWeight: 400,
        }}
      >
        {formatDateTime(activityDate)}
      </Typography>
    </Box>
  );
}

export function UserActionCell({
  user,
  labels,
  isProtected,
  onEdit,
  onOpenLoginTrails,
  onToggleStatus,
  onDelete,
}: UserActionCellProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const [menuAnchorEl, setMenuAnchorEl] = useState<HTMLElement | null>(null);

  function closeMenu() {
    setMenuAnchorEl(null);
  }

  const menuItemSx = {
    height: 40,
    gap: 1,
    color: isDark ? alpha("#ffffff", 0.75) : "#717680",
    fontSize: 13,
    fontWeight: 400,
    "&:hover": {
      backgroundColor: isDark ? alpha("#ffffff", 0.06) : "#f9fafb",
    },
  };

  return (
    <>
      <IconButton
        onClick={(event) => setMenuAnchorEl(event.currentTarget)}
        size="small"
        sx={{
          width: 28,
          height: 28,
          borderRadius: "4px",
          color: isDark ? alpha("#ffffff", 0.72) : "#717680",
        }}
      >
        <MoreVertIcon sx={{ fontSize: 18 }} />
      </IconButton>

      <Menu
        anchorEl={menuAnchorEl}
        open={Boolean(menuAnchorEl)}
        onClose={closeMenu}
        anchorOrigin={{ vertical: "center", horizontal: "left" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        slotProps={{
          paper: {
            sx: {
              width: 180,
              borderRadius: "8px",
              border: `1px solid ${isDark ? alpha("#ffffff", 0.1) : "#f5f5f5"}`,
              backgroundColor: isDark ? "#101828" : "#ffffff",
              boxShadow: isDark
                ? "0px 0px 20px rgba(0,0,0,0.45)"
                : "0px 0px 10.6px rgba(0, 0, 0, 0.1)",
              mt: 0.5,
            },
          },
          list: {
            disablePadding: true,
          },
        }}
      >
        <MenuItem
          onClick={() => {
            closeMenu();
            onEdit(user);
          }}
          sx={menuItemSx}
        >
          <EditIcon sx={{ fontSize: 18 }} />
          {labels.editUser}
        </MenuItem>

        <MenuItem
          onClick={() => {
            closeMenu();
            onOpenLoginTrails(user);
          }}
          sx={menuItemSx}
        >
          <HistoryIcon sx={{ fontSize: 18 }} />
          {labels.loginTrails}
        </MenuItem>

        {!isProtected ? (
          <>
            <MenuItem
              onClick={() => {
                closeMenu();
                onToggleStatus(user);
              }}
              sx={menuItemSx}
            >
              {user.status === "Inactive" ? (
                <ToggleOnIcon sx={{ fontSize: 18 }} />
              ) : (
                <ToggleOffIcon sx={{ fontSize: 18 }} />
              )}
              {user.status === "Inactive" ? labels.activate : labels.deactivate}
            </MenuItem>

            <MenuItem
              onClick={() => {
                closeMenu();
                onDelete(user);
              }}
              sx={{
                ...menuItemSx,
                color: "#f04438",
                borderTop: `1px solid ${isDark ? alpha("#ffffff", 0.08) : "#f5f5f5"}`,
                "&:hover": {
                  backgroundColor: isDark ? alpha("#ffffff", 0.06) : "#fef3f2",
                },
              }}
            >
              <DeleteIcon sx={{ fontSize: 18 }} />
              {labels.deleteUser}
            </MenuItem>
          </>
        ) : null}
      </Menu>
    </>
  );
}
