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

import * as colors from '@material-hu/mui/colors';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import { useLokaliseTranslation } from 'src/utils/i18n';

import FormSwitch, {
  type FormSwitchProps,
} from 'src/components/FormInputs/FormSwitch';

export type SecondaryActionProps = ButtonProps & { label: string };

export type SwitchProps = FormSwitchProps & {
  label?: string;
  helperText: string;
  secondaryAction?: SecondaryActionProps;
};

export const Switch = ({
  name,
  label,
  helperText,
  secondaryAction,
  ...switchProps
}: SwitchProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { watch } = useFormContext();

  const isChecked = !!watch(name || '');

  const { label: secondaryActionLabel, ...secondaryActionProps } =
    secondaryAction || ({} as SecondaryActionProps);

  return (
    <Stack sx={{ gap: 1, width: '100%' }}>
      {label && <Typography variant="subtitle1">{label}</Typography>}
      <Stack
        sx={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          px: 3,
          py: 1,
          backgroundColor: colors.grey[50],
          borderRadius: 1,
          gap: 1,
        }}
      >
        <Stack
          sx={{
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'flex-start',
          }}
        >
          <Typography
            variant="body1"
            sx={{ display: 'flex', alignItems: 'center' }}
          >
            {helperText}
          </Typography>
          {secondaryAction && (
            <Button
              {...secondaryActionProps}
              sx={{
                px: 1,
                py: 0.5,
                ml: -1,
                ...secondaryActionProps?.sx,
              }}
            >
              {secondaryActionLabel}
            </Button>
          )}
        </Stack>
        <FormSwitch
          {...switchProps}
          sx={{ m: 0, ml: 2, ...switchProps?.sx }}
          name={name}
          label={t(isChecked ? 'general:yes' : 'general:no')}
        />
      </Stack>
    </Stack>
  );
};

export default Switch;
