import { INVALID_INPUT as INVALID_INPUT_MESSAGE } from 'core/constants/errorMessages';
import { useEffect, useState } from 'react';
import { useStores } from '../useStores';

export const useValidation = ({ elementName, value }) => {
  const [isValid, setValidation] = useState(undefined);
  const { calculationStore } = useStores();

  // get value from store
  const validationStatus = calculationStore.validations[elementName];
  useEffect(() => {
    setValidation(validationStatus);
  }, [validationStatus]);

  useEffect(() => {
    if (value === undefined || value === '') {
      calculationStore.setValidation(elementName, undefined);
    }
  }, [value]);

  return {
    validateStatus: isValid === false ? 'error' : undefined,
    message: isValid === false ? INVALID_INPUT_MESSAGE : undefined,
  };
};

export const useTableValidation = ({
  tableName,
  rowIndex,
  propName,
  value,
}) => {
  const [isValid, setValidation] = useState(undefined);
  const { calculationStore } = useStores();

  const validationStatus =
    calculationStore?.tables?.[tableName]?.rows?.[rowIndex]?.[propName]
      ?.validation;
  useEffect(() => {
    setValidation(validationStatus);
  }, [validationStatus]);

  useEffect(() => {
    if (value === undefined || value === '') {
      calculationStore.setTableRows(
        tableName,
        rowIndex,
      )([
        {
          [propName]: {
            validation: undefined,
          },
        },
      ]);
    }
  }, [value]);

  return {
    validateStatus: isValid === false ? 'error' : undefined,
    message: isValid === false ? INVALID_INPUT_MESSAGE : undefined,
  };
};
