import PropTypes from 'prop-types';
import { FormControlLabel, Switch as MuiSwitch } from '@mui/material';
import { styled } from '../Theme';

// 参考: https://mui.com/material-ui/react-switch/#customization
const IOSSwitch = styled((props) => <MuiSwitch focusVisibleClassName=".Mui-focusVisible" disableRipple {...props} />)(
  ({ theme }) => ({
    width: 42,
    height: 26,
    padding: 0,
    '& .MuiSwitch-switchBase': {
      padding: 0,
      margin: 2,
      transitionDuration: '300ms',
      '&.Mui-checked': {
        transform: 'translateX(16px)',
        color: '#fff',
        '& + .MuiSwitch-track': {
          backgroundColor: theme.palette.primary.main,
          opacity: 1,
          border: 0,
        },
        '&.Mui-disabled + .MuiSwitch-track': {
          opacity: 0.5,
        },
      },
      '&.Mui-focusVisible .MuiSwitch-thumb': {
        color: theme.palette.primary.main,
        border: '6px solid #fff',
      },
      '&.Mui-disabled .MuiSwitch-thumb': {
        color: theme.palette.mode === 'light' ? theme.palette.grey[100] : theme.palette.grey[600],
      },
      '&.Mui-disabled + .MuiSwitch-track': {
        opacity: theme.palette.mode === 'light' ? 0.7 : 0.3,
      },
    },
    '& .MuiSwitch-thumb': {
      boxSizing: 'border-box',
      width: 22,
      height: 22,
    },
    '& .MuiSwitch-track': {
      borderRadius: 26 / 2,
      backgroundColor: theme.palette.grey[200],
      opacity: 1,
      transition: theme.transitions.create(['background-color'], {
        duration: 500,
      }),
    },
  })
);

/**
 * Switch 组件 Props
 * @typedef {{
 *  labelProps?: import('@mui/material').FormControlLabelProps;
 * } & import('@mui/material').SwitchProps } SwitchProps
 */

/**
 * 抽取 blocklet server 中使用的 iOS 风格的 Switch,
 * 该组件把 FormControlLabel 和 MuiSwitch 组合在一起,
 * 兼容 mui Switch props, 使用 labelProps 控制 FormControlLabel
 * @param {SwitchProps} props
 * @returns {JSX.Element}
 */
function Switch({ labelProps = null, ...rest }) {
  if (labelProps) {
    return <FormControlLabel control={<IOSSwitch {...rest} />} {...labelProps} />;
  }
  return <IOSSwitch {...rest} />;
}

Switch.propTypes = {
  labelProps: PropTypes.object,
};

export default Switch;
