import { useNavigate } from 'react-router-dom';

import {
  IconEdit,
  IconListDetails,
  IconRefresh,
  IconTrash,
  IconUsersPlus,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';
import { appearFromBottom } from '@material-hu/utils/animations';

import MenuList from '@material-hu/components/composed-components/MenuList';
import TypographyOverflowTooltip from '@material-hu/components/composed-components/TypographyOverflowTooltip';
import Pills from '@material-hu/components/design-system/Pills';
import TableCell from '@material-hu/components/design-system/Table/components/TableCell';
import TableRow from '@material-hu/components/design-system/Table/components/TableRow';
import Tooltip from '@material-hu/components/design-system/Tooltip';

import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';
import { namedFormatUTCDate } from 'src/utils/timeUtils';

import {
  COLUMN_MIN_WIDTHS,
  STICKY_ACTIONS_CELL_SX,
  STICKY_NAME_CELL_SX,
  roleStatusConfig,
} from '../constants';
import useRolesPermissions from '../hooks/useRolesPermissions';
import { rolesAndPermissionsRoutes } from '../routes';
import { type RoleListItem, RoleState, RoleType } from '../types';

type RolesAndPermissionsRowProps = {
  role: RoleListItem;
  onDelete: () => void;
  onViewDetail: () => void;
};

const RolesAndPermissionsRow = ({
  role,
  onDelete,
  onViewDetail,
}: RolesAndPermissionsRowProps) => {
  const { t } = useLokaliseTranslation('rolesAndPermissions');
  const { canManageOrDefineRoles, onlyCanAssignUsersActiveRole } =
    useRolesPermissions();
  const navigate = useNavigate();
  const theme = useTheme();

  const isActive = role.state === RoleState.ACTIVE;
  const showEditMenuEntry = !onlyCanAssignUsersActiveRole || isActive;

  const handleEdit = () => {
    logEvent(LogEvents.ROLE_EDITION_STARTED, {
      roleId: role.id,
      type: role.type,
      state: role.state,
    });
    const url = onlyCanAssignUsersActiveRole
      ? `${rolesAndPermissionsRoutes.edit(role.id)}?type=${role.type}&step=assignment`
      : `${rolesAndPermissionsRoutes.edit(role.id)}?type=${role.type}`;
    navigate(url);
  };

  const editMenuEntry = onlyCanAssignUsersActiveRole
    ? {
        title: t('table.actions.assign_members'),
        Icon: IconUsersPlus,
        onClick: handleEdit,
      }
    : {
        title: t('GENERAL:EDIT'),
        Icon: IconEdit,
        onClick: handleEdit,
      };

  const menuOptions = [
    ...(isActive
      ? [
          {
            title: t('role_details.view'),
            Icon: IconListDetails,
            onClick: onViewDetail,
          },
        ]
      : []),
    ...(showEditMenuEntry ? [editMenuEntry] : []),
    ...(role?.type === RoleType.CUSTOM && canManageOrDefineRoles
      ? [
          {
            title: t('GENERAL:DELETE'),
            Icon: IconTrash,
            onClick: onDelete,
          },
        ]
      : []),
  ];

  return (
    <TableRow
      key={role.id}
      hover
      onClick={showEditMenuEntry ? handleEdit : undefined}
      sx={{
        animation: `${appearFromBottom} 0.3s ease`,
        cursor: showEditMenuEntry ? 'pointer' : 'default',
      }}
    >
      <TableCell
        sx={{
          ...STICKY_NAME_CELL_SX,
          zIndex: 1,
          backgroundColor: theme =>
            theme.palette.new.background.elements.default,
          'tr:hover > &': {
            backgroundColor: theme =>
              theme.palette.new.background.elements.grey,
          },
          borderBottom: 'inherit',
          overflow: 'hidden',
          textWrap: 'nowrap',
          textOverflow: 'ellipsis',
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            gap: 1,
            alignItems: 'center',
            minWidth: 0,
          }}
        >
          <Typography
            variant="globalS"
            noWrap
          >
            {role.name}
          </Typography>
          {role.type !== RoleType.CUSTOM && (
            <Tooltip
              description={t('type.role_predefined_tooltip', {
                role: role.name,
              })}
              slotProps={{
                popper: {
                  modifiers: [
                    {
                      name: 'offset',
                      options: {
                        offset: [0, -4],
                      },
                    },
                  ],
                },
              }}
            >
              <span>
                <Pills
                  label={t('type.predefined')}
                  type="neutral"
                  hasIcon={false}
                  size="small"
                />
              </span>
            </Tooltip>
          )}
        </Stack>
        <TypographyOverflowTooltip
          tooltipProps={{
            description: role.description || '',
            direction: 'bottom',
          }}
          typographyProps={{
            variant: 'globalXS',
            sx: {
              color: theme.palette.textColors?.neutralTextLighter,
            },
          }}
        >
          {role.description}
        </TypographyOverflowTooltip>
      </TableCell>
      <TableCell sx={{ minWidth: COLUMN_MIN_WIDTHS.members }}>
        {role.state === RoleState.IN_PROGRESS && (
          <Tooltip
            description={t('tooltip.in_progress')}
            direction="bottom"
          >
            <IconRefresh color={theme.palette.textColors?.neutralTextLighter} />
          </Tooltip>
        )}
        {role.state !== RoleState.IN_PROGRESS && (
          <Typography variant="globalS">
            {role.state === RoleState.DRAFT ? '-' : role.userCount}
          </Typography>
        )}
      </TableCell>
      <TableCell sx={{ minWidth: COLUMN_MIN_WIDTHS.state }}>
        <Tooltip
          description={t('tooltip.in_progress')}
          disableTooltip={role.state !== RoleState.IN_PROGRESS}
          direction="bottom"
        >
          <span>
            <Pills
              label={t(`general:states.${role.state}`)}
              type={roleStatusConfig[role.state]?.color || 'neutral'}
              hasIcon={false}
              size="small"
            />
          </span>
        </Tooltip>
      </TableCell>
      <TableCell sx={{ minWidth: COLUMN_MIN_WIDTHS.updated_at }}>
        <Typography variant="globalS">
          {role.updatedAt && role.state !== RoleState.IN_PROGRESS
            ? namedFormatUTCDate(role.updatedAt)
            : '-'}
        </Typography>
      </TableCell>
      <TableCell
        variant="shortField"
        align="right"
        onClick={e => e.stopPropagation()}
        sx={{
          ...STICKY_ACTIONS_CELL_SX,
          zIndex: 1,
          backgroundColor: theme =>
            theme.palette.new.background.elements.default,
          'tr:hover > &': {
            backgroundColor: theme =>
              theme.palette.new.background.elements.grey,
          },
          borderBottom: 'inherit',
          whiteSpace: 'nowrap',
        }}
      >
        <MenuList
          position="right"
          options={menuOptions}
        />
      </TableCell>
    </TableRow>
  );
};

export default RolesAndPermissionsRow;
