import { TAB_FORM_DETAILS } from '../../constants';
import { FIELD_MAX_LENGTH_DESCRIPTION, FIELD_MAX_LENGTH_TITLE } from '@/modules/forms/editor/constants';

import { getCharacterCount } from '@/modules/forms/helpers';

export const validationScheme = [
  {
    fieldName: 'name',
    tabId: TAB_FORM_DETAILS,
    validation: (title) => {
      const value = title?.trim();

      if (!value) {
        return 'Field cannot be empty';
      }
      if (value.length < 2) {
        return 'Field cannot be less then 2 symbols';
      }

      return '';
    },
  },
  {
    fieldName: 'title',
    tabId: TAB_FORM_DETAILS,
    validation: (value) => {
      const length = getCharacterCount(value);

      if (!length) {
        return 'Field cannot be empty';
      }

      if (length > FIELD_MAX_LENGTH_TITLE) {
        return `Field can’t exceed ${FIELD_MAX_LENGTH_TITLE} characters`;
      }

      return '';
    },
  },
  {
    fieldName: 'description',
    tabId: TAB_FORM_DETAILS,
    validation: (value) => {
      if (getCharacterCount(value) > FIELD_MAX_LENGTH_DESCRIPTION) {
        return `Field can’t exceed ${FIELD_MAX_LENGTH_DESCRIPTION} characters`;
      }

      return '';
    },
  },
  // dynamic fields
  {
    fieldName: 'dynamicFields',
    dynamic: true,
    tabId: TAB_FORM_DETAILS,
    validation: (dynamicFields) =>
      dynamicFields.reduce((acc, field) => {
        acc[field.id] = {
          value: !field.value ? 'Field cannot be empty' : '',
          options: field.options?.reduce((acc$, option) => {
            acc$[option.id] = {
              name: !option.name ? 'Field cannot be empty' : '',
            };

            return acc$;
          }, {}),
        };

        return acc;
      }, {}),
  },
  {
    fieldName: 'submitButton.title',
    tabId: TAB_FORM_DETAILS,
    validation: (value) => {
      if (!value) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
  {
    fieldName: 'privacyPolicy.title',
    tabId: TAB_FORM_DETAILS,
    validation: (value) => {
      if (!value) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
  {
    fieldName: 'termsConditions.title',
    tabId: TAB_FORM_DETAILS,
    validation: (value) => {
      if (!value) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
  {
    fieldName: 'skipButton.title',
    tabId: TAB_FORM_DETAILS,
    validation: (value) => {
      if (!value) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
];
