import React, { FC, useState, useEffect } from 'react';
import SwitchComponent from 'react-switch';
import { BoxProps } from '../Box';
import { theme } from '../../styles/theme';

export type SwitchProps = {
  checked?: boolean;
  width?: number;
  height?: number;
  diameter?: number;
  onColor?: string;
  offColor?: string;
  onChange?: (event: any) => void;
} & BoxProps;

export const Switch: FC<SwitchProps> = ({
  checked: checkedProp,
  width = 48,
  height = 24,
  diameter = 18,
  onColor = theme.colors.success,
  offColor = theme.colors.gray[3],
  onChange,
  ...restProps
}) => {
  const initialChecked = checkedProp === undefined ? false : checkedProp;
  const [checked, setChecked] = useState(initialChecked);

  const handleChange = (state: any) => {
    if (onChange) {
      onChange(state);
    } else if (checkedProp === undefined) {
      setChecked(!checked);
    }
  };

  useEffect(() => {
    if (checkedProp !== undefined) {
      setChecked(checkedProp);
    }
  }, [checkedProp]);

  const switchProps = {
    checked,
    width,
    height,
    handleDiameter: diameter,
    onColor,
    offColor,
    checkedIcon: false,
    uncheckedIcon: false,
    onChange: handleChange,
  };

  return <SwitchComponent {...switchProps} {...restProps} />;
};
