import React, { useState, useCallback } from 'react';
import { Button, CheckBall } from './style';
import { useSpring, animated } from 'react-spring';
import { ISwitch } from './types';

const Ball = animated(CheckBall);

const Switch = function({ checked, defaultChecked, onChange, disabled, ...rest }: ISwitch) {
    const [internalCheckState, setInternalCheck] = useState(false);
    const [hasDefaultValueSet, setDefaultSet] = useState(false);
    const [props, setSpring] = useSpring(() => ({
        left: internalCheckState ? 18 : -6,
        config: { mass: 5, friction: 180, tension: 3000, clamp: true },
    }));

    if (defaultChecked !== undefined && !hasDefaultValueSet) {
        setInternalCheck(defaultChecked);
        setSpring({
            left: defaultChecked ? 18 : -6,
        });
        setDefaultSet(true);
    }

    if (checked !== undefined && checked !== internalCheckState) {
        setInternalCheck(checked);
        setSpring({
            left: checked ? 18 : -6,
        });
    }

    const onClick = useCallback(() => {
        setInternalCheck(v => {
            onChange && onChange(!v);
            setSpring({
                left: !v ? 18 : -6,
            });
            return !v;
        });
    }, []);
    return (
        <Button onClick={onClick} checked={internalCheckState} disabled={disabled} {...rest}>
            <Ball style={props} checked={internalCheckState} />
        </Button>
    );
};
Switch.defaultProps = {};
export default Switch;
