import React, { useState, useCallback } from "react";
import { Switch } from "react-native";
import { useActions } from "@applicaster/zapp-react-native-utils/reactHooks/actions";

type Props = {
  item: ZappEntry | ZappFeed;
  action: {
    identifier: string;
    type?: string;
  };
  style: Styles;
  cellState: CellState;
};

export const Toggle = (props: Props) => {
  const { style, item, action, cellState } = props;

  const {
    trackColor,
    trackColorActive,
    thumbColor,
    thumbColorActive,
    iosBackgroundColor,
  } = style;

  const isSelected = React.useMemo(
    () => cellState === "selected",
    [item?.id, cellState]
  );

  const actionContext = useActions(action?.identifier);

  const [actionState, setActionState] = useState(
    actionContext.initialEntryState(item)
  );

  const onPress = useCallback(() => {
    actionContext.invokeAction(item, {
      updateState: setActionState,
    });
  }, [actionState, actionContext?.state]);

  return (
    <Switch
      trackColor={{ false: trackColor, true: trackColorActive }}
      thumbColor={isSelected ? thumbColorActive : thumbColor}
      ios_backgroundColor={iosBackgroundColor}
      onValueChange={onPress}
      value={isSelected}
    />
  );
};
