import { ComponentPropsWithRef, forwardRef, ForwardedRef } from 'react';
import { styled } from '../../stitches.config';

import { SwitchTrack } from './SwitchTrack';
import { SwitchButton } from './SwitchButton';

import { InputOptions } from '../../utility';
import { useValue } from '../../hooks';

const Flex = styled('div', { display: 'flex' });

export interface SwitchProps
    extends InputOptions<boolean>,
        Omit<
            ComponentPropsWithRef<'div'>,
            'value' | 'defaultValue' | 'defaultChecked' | 'onChange'
        > {}

/**
 * Switch component
 */
const _Switch = (
    props: SwitchProps,
    ref: ForwardedRef<HTMLDivElement>,
): JSX.Element => {
    const {
        id,
        value,
        defaultValue,
        onChange = () => null,
        disabled = false,
        valid = true,
        ...otherProps
    } = props;

    // manage the internal value
    const [internalValue, setInternalValue] = useValue({
        initialValue: false,
        value: value,
        defaultValue: defaultValue,
        onChange: onChange,
    });

    return (
        <Flex ref={ref} {...otherProps}>
            <SwitchTrack
                id={id}
                checked={internalValue}
                onCheckedChange={setInternalValue}
                disabled={disabled}
                valid={valid}
            >
                <SwitchButton checked={internalValue} valid={valid} />
            </SwitchTrack>
        </Flex>
    );
};

export const Switch = forwardRef(_Switch) as (
    props: SwitchProps & {
        ref?: ForwardedRef<HTMLDivElement>;
    },
) => ReturnType<typeof _Switch>;
