import React, { useState } from 'react';
import { observer } from 'mobx-react-lite';
import { Box, Divider, FormField, Input, Text } from '@wix/design-system';
import { ChevronDown, ChevronRight } from '@wix/wix-ui-icons-common';
import type { CmsFormState } from '../CmsFormState';
import { ValidationSubSection } from './ValidationSubSection';

interface Props {
  state: CmsFormState;
}

const _ValidationAndDefaultsSection = ({ state }: Props) => {
  const [isOpen, setIsOpen] = useState(false);
  const hasValidation = state.supportedValidationRules.length > 0;

  return (
    <Box direction="vertical">
      <div
        role="button"
        tabIndex={0}
        style={{
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          padding: '16px 0',
        }}
        onClick={() => setIsOpen((v) => !v)}
        onKeyDown={(e: React.KeyboardEvent) =>
          e.key === 'Enter' && setIsOpen((v) => !v)
        }
      >
        {isOpen ? <ChevronDown size="18px" /> : <ChevronRight size="18px" />}
        <Text>Validation and defaults</Text>
      </div>

      {isOpen && (
        <Box direction="vertical" gap="SP6" paddingBottom="SP4">
          {hasValidation && (
            <Box direction="vertical" gap="SP2">
              <Text weight="bold">Validation</Text>
              <ValidationSubSection state={state} />
            </Box>
          )}

          <Divider />

          <FormField
            label="Help text"
            infoContent="Descriptive text shown below the field in forms."
          >
            <Input
              value={state.properties.helpText}
              onChange={(e) => state.setHelpText(e.target.value)}
            />
          </FormField>
        </Box>
      )}
    </Box>
  );
};

export const ValidationAndDefaultsSection = observer(
  _ValidationAndDefaultsSection,
);
