import { styled, Switch, switchClasses } from '@mui/material';

import { blue, gray } from '@/themes/common';

// A check glyph as a data URI, used inside the switch thumb
const thumbCheck = (color: string) =>
  `url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24"><path fill="${encodeURIComponent(
    color
  )}" d="M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>')`;

const THUMB_WHITE = '#fff';

// Blue track + white thumb with a check glyph. The absolute input position
// undoes the global `input[type=checkbox] { position: relative }` that broke the overlay.
export const CheckSwitch = styled(Switch)(({ theme }) => ({
  height: 26,
  padding: 0,
  width: 42,
  [`& .${switchClasses.input}`]: { position: 'absolute' },
  [`& .${switchClasses.switchBase}`]: {
    color: THUMB_WHITE,
    margin: 2,
    padding: 0,
    transitionDuration: '300ms',
    [`&.${switchClasses.checked}`]: {
      color: THUMB_WHITE,
      transform: 'translateX(16px)',
      [`& + .${switchClasses.track}`]: { backgroundColor: blue[500], border: 0, opacity: 1 },
      [`& .${switchClasses.thumb}::before`]: { backgroundImage: thumbCheck(blue[500]) },
      [`&.${switchClasses.disabled} + .${switchClasses.track}`]: { opacity: 0.5 }
    },
    [`&.${switchClasses.disabled} .${switchClasses.thumb}`]: { color: THUMB_WHITE },
    [`&.${switchClasses.disabled} + .${switchClasses.track}`]: { opacity: 0.7 }
  },
  [`& .${switchClasses.thumb}`]: {
    boxShadow: 'none',
    boxSizing: 'border-box',
    height: 22,
    position: 'relative',
    width: 22,
    '&::before': {
      backgroundImage: thumbCheck(gray[300]),
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat',
      content: '""',
      inset: 0,
      position: 'absolute'
    }
  },
  [`& .${switchClasses.track}`]: {
    backgroundColor: gray[300],
    borderRadius: 26 / 2,
    opacity: 1,
    transition: theme.transitions.create(['background-color'], { duration: 500 })
  }
}));
