import React, { useState, useEffect } from 'react';
import Styled from 'styled-components/native';
import { Switch as NativeSwitch } from 'react-native';
import { usePrevious } from '../Hooks';

export default Switch = ({
    initialValue=false,
    onChange=()=>{}, 
    onValueChange=()=>{},
    thumbColor="white", 
    activeTrackColor="#0b83e6",
    deactiveTrackColor="#dedede",
    ios_backgroundColor="#dedede",
    editable=true,
    ...rest
}) => {

    const [value, setValue] = useState(initialValue);
    //console.log('initialValue:', initialValue, ',value:', value);

    const prevEditable = usePrevious(editable);

    useEffect(() => {
        setValue(initialValue);
        if(typeof prevValue !== 'undefined' && editable != prevEditable) {
            onChange();
        }
    }, [initialValue, editable]);

    return (
        <NativeSwitch value={value}
            onChange={() => { setValue(!value); onChange(); }} 
            onValueChange={onValueChange}
            thumbColor={thumbColor}  
            trackColor={{true:activeTrackColor, false:deactiveTrackColor}}
            ios_backgroundColor={ios_backgroundColor}
            disabled={!editable}
            {...rest} 
        />
    )
};