import React, { FC, PropsWithChildren } from 'react';

import { useSwitch, UseSwitchParameters } from '@mui/base/SwitchUnstyled';

import { bem } from 'utils/bem';

import { THEME } from '../../constants';
import { Typography, TYPOGRAPHY_TYPE } from '../Typography';

import styles from './switch.scss';

const classes = bem(styles, 'switch');

interface ILabel {
  label?: string;
  labelPosition: string;
}

export enum LABEL_POSITION {
  left = 'left',
  right = 'right',
}

const Label: FC<PropsWithChildren<ILabel>> = ({ label, labelPosition, children }): JSX.Element => {
  return (
    <span className={classes('label-holder', { reverse: labelPosition === LABEL_POSITION.left })}>
      {children}
      {!!label && (
        <Typography
          type={TYPOGRAPHY_TYPE.body2}
          hasPadding={false}
          className={classes('label', { [labelPosition]: true })}
        >
          {label}
        </Typography>
      )}
    </span>
  );
};

export const Switch: FC<
  UseSwitchParameters & {
    label?: string;
    className?: string;
    theme?: THEME;
    labelPosition?: LABEL_POSITION;
    dataAttributes?: Record<`data-${string}`, string>;
  }
> = (props) => {
  const { label, theme = THEME.dark, labelPosition = LABEL_POSITION.right, className, dataAttributes } = props;
  const { getInputProps, checked, disabled } = useSwitch(props);

  return (
    <span className={classes(null, { checked, disabled, [theme]: true }, className)}>
      <Label
        label={label}
        labelPosition={labelPosition}
      >
        <span className={classes('track')}>
          <span className={classes('thumb')} />
        </span>
      </Label>

      <input
        {...dataAttributes}
        className={classes('input')}
        {...getInputProps()}
      />
    </span>
  );
};
