import React from 'react';
import { observer } from 'mobx-react-lite';
import { Box, InfoIcon, Text, ToggleSwitch } from '@wix/design-system';
import type { StringLengthRange } from '../../../types/SchemaConfig';
import type { CmsFormState } from '../CmsFormState';
import type { ValidationRule } from '../types';
import { RequiredToggle } from '../formFields/RequiredToggle';
import { CharactersLimitInput } from '../formFields/CharactersLimitInput';

interface Props {
  state: CmsFormState;
}

const _ValidationSubSection = ({ state }: Props) => {
  const { supportedValidationRules, fieldRules } = state;

  return (
    <Box direction="vertical" gap="SP3">
      {supportedValidationRules.map((rule: ValidationRule) => {
        if (rule === 'required') {
          return (
            <RequiredToggle
              key="required"
              label="Make this a required field"
              checked={Boolean(fieldRules.validationRules.required)}
              onChange={(v) => state.setValidationRule('required', v)}
            />
          );
        }
        if (rule === 'charactersLimit') {
          const isEnabled =
            fieldRules.validationRules.charactersLimit !== undefined;
          return (
            <Box key="charactersLimit" direction="vertical" gap="SP3">
              <Box verticalAlign="middle" gap="SP2">
                <ToggleSwitch
                  checked={isEnabled}
                  onChange={() =>
                    state.setValidationRule(
                      'charactersLimit',
                      isEnabled ? undefined : {},
                    )
                  }
                />
                <Text size="small">Limit character count</Text>
                <InfoIcon content="Set minimum and maximum character limits for this field." />
              </Box>
              {isEnabled && (
                <CharactersLimitInput
                  minLabel="Min characters"
                  maxLabel="Max characters"
                  value={
                    (fieldRules.validationRules.charactersLimit as
                      | StringLengthRange
                      | undefined) ?? {}
                  }
                  onChange={(v) =>
                    state.setValidationRule('charactersLimit', v)
                  }
                />
              )}
            </Box>
          );
        }
        return null;
      })}
    </Box>
  );
};

export const ValidationSubSection = observer(_ValidationSubSection);
