import { FC } from 'react';
import { useFormContext } from 'react-hook-form';

import CheckOutlinedIcon from '@material-hu/icons/material/CheckOutlined';
import { alpha } from '@material-hu/mui/styles';

import Button, {
  ButtonProps,
} from '@material-hu/components/design-system/Buttons/Button';

import { logEvent } from 'src/config/logging';
import { EventName } from 'src/types/amplitude';
import { CriteriaSortBy, VacationsRequestSort } from 'src/types/vacations';

type Props = {
  orderByValue: VacationsRequestSort;
  orderValue: string;
  onClick: () => void;
} & ButtonProps;

export const SortOptionButton: FC<Props> = ({
  orderValue,
  orderByValue,
  onClick,
  ...props
}) => {
  const form = useFormContext();
  const isSelected =
    form.watch('order') === orderValue &&
    form.watch('orderBy') === orderByValue;

  return (
    <Button
      variant="tertiary"
      endIcon={isSelected && <CheckOutlinedIcon />}
      onClick={() => {
        form.setValue('order', orderValue);
        form.setValue('orderBy', orderByValue);
        logEvent(EventName.TIME_OFF_REQUESTS_SORTED, {
          criteria: CriteriaSortBy[`${orderValue}_${orderByValue}`],
        });
        onClick();
      }}
      sx={{
        pl: 1,
        py: 0.5,
        textWrap: 'nowrap',
        fontSize: 16,
        fontWeight: 500,
        color: isSelected ? 'primary' : 'text.primary',
        backgroundColor: theme =>
          isSelected && alpha(theme.palette.primary.main, 0.04),
      }}
      {...props}
    />
  );
};
