import { useMutation, useQueryClient } from 'react-query';
import api from '../../services/api';
import { AlertType, createToastProps } from '../../components/ui';
import { Toast } from 'native-base';
import useGetHeatPumpConfig from './useGetHeatPumpConfig';
import { HeatPumpConfig, HPDefrostingConfig, UpdateConfig } from '../../models/heatpump';

/**
 * Updates heat pump defrost mode configuration and updates cached heat pump configuration
 */
const useUpdateDefrostingConfig = (options?: UpdateConfig<HPDefrostingConfig>) => {
  const client = useQueryClient();

  return useMutation({
    mutationFn: api.HeatPumpApi.updateDefrostingConfiguration,
    ...options,
    onMutate: async newConfig => {
      // Cancel any outgoing refetches
      // (so they don't overwrite our optimistic update)
      await client.cancelQueries(useGetHeatPumpConfig.key).catch(() => null);

      // Snapshot the previous configuration
      const oldConfiguration = client.getQueryData<HeatPumpConfig>(useGetHeatPumpConfig.key);

      // Optimistically update to the new configuration
      client.setQueryData(useGetHeatPumpConfig.key, {
        ...oldConfiguration,
        ...newConfig,
      });

      return { oldConfiguration };
    },
    onError: (error, variables, ctx) => {
      if (ctx?.oldConfiguration) {
        client.setQueryData(useGetHeatPumpConfig.key, ctx.oldConfiguration);
      }
      Toast.show(createToastProps(AlertType.Error, 'Failed to change defrosting configuration'));
      options?.onError && options.onError(error, variables, ctx);
    },
    onSuccess: (result, requestData, ctx) => {
      Toast.show(
        createToastProps(AlertType.Success, 'Defrosting configuration successfully changed'),
      );
      options?.onSuccess && options.onSuccess(result, requestData, ctx);
    },
  });
};

export default useUpdateDefrostingConfig;
