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

export function useInsuranceValue(key, valueName) {
  const row = useRow(key);

  const storeValue = row.getValue(valueName);

  function setStoreValue(value) {
    return row.setValue(valueName, value);
  }

  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];
}
