import * as RadixSwitch from '@radix-ui/react-switch';
import { styled } from '../../stitches.config';

import { SwitchProps } from './';

const buildSwitchButton = (
    checked: NonNullable<SwitchProps['value']>,
    valid: NonNullable<SwitchProps['valid']>,
) => {
    let css = {};
    if (checked) {
        css = {
            ...css,
            cursor: 'pointer',
            transform: 'translateX(100%)',
        };

        if (valid) {
            css = {
                ...css,
                backgroundColor: '$primary-1',
                '&:hover': {
                    backgroundColor: '$primary-2',
                },
            };
        } else {
            css = {
                ...css,
                backgroundColor: '$error-1',
                '&:hover': {
                    backgroundColor: '$error-2',
                },
            };
        }
    } else {
        css = {
            ...css,
            cursor: 'pointer',
            transform: 'translateX(0px)',
        };

        if (valid) {
            css = {
                ...css,
                backgroundColor: '$grey-1',
                '&:hover': {
                    backgroundColor: '$grey-2',
                },
            };
        } else {
            css = {
                ...css,
                backgroundColor: '$error-2',
                '&:hover': {
                    backgroundColor: '$error-3',
                },
            };
        }
    }
    return {
        checked,
        valid,
        css,
    };
};

export const SwitchButton = styled(RadixSwitch.Thumb, {
    left: '0',
    top: '-0.375rem',
    width: '$space$6',
    height: '$space$6',
    position: 'absolute',
    marginBottom: '$2',
    borderRadius: '$full',
    transitionProperty: 'transform',
    transitionDuration: '100ms',
    transitionTimingFunction: 'linear',
    variants: {
        checked: {
            true: {},
            false: {},
        },
        valid: {
            true: {},
            false: {},
        },
    },
    compoundVariants: [
        buildSwitchButton(true, true),
        buildSwitchButton(true, false),
        buildSwitchButton(false, true),
        buildSwitchButton(false, false),
    ],
});
