import { type Dispatch, type SetStateAction } from 'react';

import { IconArrowRight } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { type SxProps } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuUserAvatar from '@material-hu/components/composed-components/UserAvatar';
import HuFormCheckbox from '@material-hu/components/design-system/Checkbox/Checkbox/form';
import HuPills from '@material-hu/components/design-system/Pills';
import { type PillsProps as HuPillsProps } from '@material-hu/components/design-system/Pills/types';
import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';

import { useAuth } from 'src/contexts/JWTContext';
import { useGetManagerTypes } from 'src/hooks/queryHooks/vacations';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  RequestActionsMenu,
  type RequestTableActionsMenu,
} from 'src/pages/dashboard/timeOff/components/requestReport';
import {
  type ResponseRequestTimeOff,
  VacationStatus,
} from 'src/types/vacations';
import { formatDateInVacations } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  formatVacationDuration,
  getCorrectState,
  isDisabledCheckboxRequest,
} from 'src/utils/vacations';

import {
  ellipsisCellStyle,
  ellipsisTypographyStyle,
  stickyLeftCellStyle,
  stickyRightCellStyle,
} from '../../constant';

export type RequestRowContentProps = {
  isManagerView?: boolean;
  vacations: ResponseRequestTimeOff;
  onSetSelectAllRequest: Dispatch<SetStateAction<boolean>>;
  sx?: SxProps;
  onOpenRequestDetailDrawer: (requestId: number) => void;
  actionsMenu: RequestTableActionsMenu;
  onOpenActionsMenu: (requestId: number) => void;
  onCloseActionsMenu: () => void;
};

type StatusProps = {
  label: string;
  size?: HuPillsProps['size'];
  type: VacationStatus;
  sx?: SxProps;
};

export const Status = ({ label, size, type, sx }: StatusProps) => {
  const pillsColors: Record<VacationStatus, HuPillsProps['type']> = {
    [VacationStatus.IN_PROGRESS]: 'neutral',
    [VacationStatus.PENDING]: 'warning',
    [VacationStatus.APPROVED]: 'success',
    [VacationStatus.REJECTED]: 'error',
    [VacationStatus.CANCELLED]: 'error',
  };

  return (
    <HuPills
      label={label}
      size={size || 'small'}
      type={pillsColors[type]}
      sx={sx}
      hasIcon={false}
    />
  );
};

const RequestRowContent = (props: RequestRowContentProps) => {
  const {
    vacations,
    isManagerView = false,
    onSetSelectAllRequest,
    onOpenRequestDetailDrawer,
    actionsMenu,
    onOpenActionsMenu,
    onCloseActionsMenu,
  } = props;
  const HuGoThemeProvider = useHuGoTheme();
  const { isAdmin } = useGetManagerTypes();
  const { t } = useLokaliseTranslation('time_off');
  const { user } = useAuth();

  const handleOnClickCheckbox = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    onSetSelectAllRequest(false);
  };

  const isThisRowActionsMenu =
    actionsMenu != null && actionsMenu.requestId === vacations.id;

  return (
    <HuGoThemeProvider>
      <HuTableRow
        onClick={() => onOpenRequestDetailDrawer(vacations.id)}
        sx={{ cursor: 'pointer' }}
      >
        {isManagerView && (
          <>
            <HuTableCell
              align="center"
              sx={{
                ...stickyLeftCellStyle,
                backgroundColor: theme =>
                  theme.palette.new.background.elements.default,
              }}
            >
              <HuFormCheckbox
                checkBoxProps={{
                  label: '',
                  onClick: handleOnClickCheckbox,
                  disabled: isDisabledCheckboxRequest(vacations, isAdmin),
                }}
                name={`requests.${vacations.id}`}
              />
            </HuTableCell>
            <HuTableCell align="left">
              <HuUserAvatar
                user={vacations?.issuer!}
                sx={{
                  p: 0,
                  '& .MuiTypography-root': {
                    fontWeight: 'fontWeightRegular',
                    ...ellipsisTypographyStyle,
                  },
                  '& .MuiListItem-root': {
                    p: 0,
                  },
                }}
              />
            </HuTableCell>
            <HuTableCell sx={ellipsisCellStyle}>
              <Typography>{vacations?.issuer?.employeeInternalId}</Typography>
            </HuTableCell>
          </>
        )}
        <HuTableCell align="left">
          <Typography
            sx={{
              ...ellipsisTypographyStyle,
              maxWidth: isManagerView ? 200 : 700,
            }}
          >
            {vacations?.policyType.name}
          </Typography>
        </HuTableCell>
        <HuTableCell align="left">
          <Status
            label={t(`VACATIONS_STATUS_${getCorrectState(vacations)}`)}
            size="small"
            type={getCorrectState(vacations)}
          />
        </HuTableCell>
        <HuTableCell align="left">
          <Typography>
            {formatDateInVacations({
              date: vacations?.createdAt,
              user: user!,
              isUtc: true,
              type: 'PP',
            })}
          </Typography>
        </HuTableCell>
        <HuTableCell
          align="left"
          sx={{ minWidth: 300 }}
        >
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 2,
            }}
          >
            <Typography>
              {formatDateInVacations({
                date: vacations?.from.date,
                user: user!,
                type: 'PP',
              })}
            </Typography>
            <IconArrowRight size={16} />
            <Typography>
              {formatDateInVacations({
                date: vacations?.to.date,
                user: user!,
                type: 'PP',
              })}
            </Typography>
          </Stack>
        </HuTableCell>
        {isManagerView && (
          <HuTableCell
            align="left"
            sx={{ minWidth: 150 }}
          >
            <Typography>
              {formatVacationDuration(
                vacations.amountRequested!,
                vacations.policyType.unit,
                t,
              )}
            </Typography>
          </HuTableCell>
        )}
        <HuTableCell
          align="center"
          onClick={e => e.stopPropagation()}
          sx={{
            p: 1,
            backgroundColor: theme => theme.palette.background.paper,
            ...stickyRightCellStyle,
          }}
        >
          <RequestActionsMenu
            vacations={vacations}
            onOpenDrawer={onOpenRequestDetailDrawer}
            isManagerView={isManagerView}
            menuOpen={isThisRowActionsMenu}
            onOpenMenu={() => onOpenActionsMenu(vacations.id)}
            onCloseMenu={onCloseActionsMenu}
          />
        </HuTableCell>
      </HuTableRow>
    </HuGoThemeProvider>
  );
};

export default RequestRowContent;
