/* eslint-disable import/prefer-default-export */
import { useEffect, useState } from 'react';
import { useRowValue } from 'stores/tables/payments/hooks';
import { useDebouncedCallback } from 'use-debounce';

export function usePaymentValue(index) {
  const [storeValue, setStoreValue] = useRowValue(index);
  const [value, setValue] = useState(storeValue);

  // eslint-disable-next-line object-curly-newline
  const debouncedSetStoreValue = useDebouncedCallback(setStoreValue, 350, { maxWait: 1000 });

  useEffect(
    () => {
      if (storeValue !== value) {
        debouncedSetStoreValue(value);
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [value]
  );

  useEffect(() => {
    setValue(storeValue);
  }, [storeValue]);

  return [value, setValue];
}
