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

import { SwitchProps } from './';

const buildSwitchTrack = (
    checked: NonNullable<SwitchProps['value']>,
    valid: NonNullable<SwitchProps['valid']>,
) => {
    let css = {};
    if (checked) {
        css = {
            ...css,
            cursor: 'pointer',
            // span is the element that radix uses for switch button
            '&:focus span': {
                outline: '2px solid $primary-1',
                outlineOffset: '2px',
            },
            '&:disabled': {
                cursor: 'default',
                backgroundColor: '$grey-3',
            },
            '&:disabled span': {
                cursor: 'default',
                backgroundColor: '$grey-1',
            },
        };

        if (valid) {
            css = {
                ...css,
                backgroundColor: '$primary-3',
            };
        } else {
            css = {
                ...css,
                backgroundColor: '$error-3',
            };
        }
    } else {
        css = {
            ...css,
            cursor: 'pointer',
            // span is the element that radix uses for switch button
            '&:focus span': {
                outline: '2px solid $primary-1',
                outlineOffset: '2px',
            },
            '&:disabled': {
                cursor: 'default',
                backgroundColor: '$grey-3',
            },
            '&:disabled span': {
                cursor: 'default',
                backgroundColor: '$grey-1',
            },
        };

        if (valid) {
            css = {
                ...css,
                backgroundColor: '$grey-4',
            };
        } else {
            css = {
                ...css,
                backgroundColor: '$grey-4',
            };
        }
    }

    return {
        checked,
        valid,
        css,
    };
};

export const SwitchTrack = styled(RadixSwitch.Root, {
    display: 'inline-block',
    borderRadius: '$full',
    position: 'relative',
    width: '$space$12',
    height: '$space$3',
    top: '$2',
    transitionDuration: '200ms',
    transitionTimingFunction: 'linear',
    outline: 'none',
    variants: {
        checked: {
            true: {},
            false: {},
        },
        valid: {
            true: {},
            false: {},
        },
    },
    compoundVariants: [
        buildSwitchTrack(true, true),
        buildSwitchTrack(true, false),
        buildSwitchTrack(false, true),
        buildSwitchTrack(false, false),
    ],
});
