import { Box, Typography, useTheme } from '@mui/material';
import { useMemoizedFn } from 'ahooks';
import { AppBadgeDefaultProps, BadgeContainer } from './app-badge-default';

export interface AppBadgeSwitchProps extends Omit<AppBadgeDefaultProps, 'value' | 'onChange'> {
  value?: unknown;
  trueValue?: unknown;
  falseValue?: unknown;
  onChange?: (checked: boolean) => void;
}

export function AppBadgeSwitch({
  label = '',
  value = undefined,
  trueValue = true,
  falseValue = false,
  loading = false,
  onChange = undefined,
  ...rest
}: AppBadgeSwitchProps) {
  const theme = useTheme();
  let checked = false;
  const handleClick = useMemoizedFn(() => onChange?.(!checked));

  if (value === trueValue) {
    checked = true;
  } else if (value === falseValue) {
    checked = false;
  } else {
    checked = Boolean(value);
  }

  return (
    <BadgeContainer
      loading={loading}
      sx={{
        cursor: 'pointer',
        backgroundColor: checked ? 'primary.main' : 'grey.100',
        borderColor: checked ? 'primary.main' : 'divider',
        transition: 'background-color 0.3s ease',
      }}
      onClick={handleClick}
      {...rest}>
      {/* 内容 */}
      <Typography
        sx={{
          fontWeight: 400,
          paddingLeft: checked ? 0 : theme.spacing(2.5),
          paddingRight: checked ? theme.spacing(2.5) : 0,
          color: checked ? 'common.white' : 'text.secondary',
          transition: 'color 0.3s ease',
        }}>
        {label}
      </Typography>
      {/* 滑块 */}
      <Box
        sx={{
          width: theme.spacing(2.5),
          height: theme.spacing(2.5),
          borderRadius: `${(theme.shape.borderRadius as number) * 0.5}px`,
          backgroundColor: 'common.white',
          position: 'absolute',
          top: '50%',
          left: checked ? `calc(100% - ${theme.spacing(3)})` : theme.spacing(0.5),
          transform: 'translateY(-50%)',
          transition: 'left 0.3s ease',
          boxShadow: 1,
        }}
      />
    </BadgeContainer>
  );
}
