1import React, { FC, useState } from 'react';
2import { NotificationChannelOption } from 'app/types';
3import { FieldError, DeepMap, useFormContext } from 'react-hook-form';
4import { OptionField } from './OptionField';
5import { Button, useStyles2 } from '@grafana/ui';
6import { ActionIcon } from '../../../rules/ActionIcon';
7import { getReceiverFormFieldStyles } from './styles';
8
9interface Props {
10  defaultValue: any;
11  option: NotificationChannelOption;
12  pathPrefix: string;
13  errors?: DeepMap<any, FieldError>;
14  readOnly?: boolean;
15}
16
17export const SubformField: FC<Props> = ({ option, pathPrefix, errors, defaultValue, readOnly = false }) => {
18  const styles = useStyles2(getReceiverFormFieldStyles);
19  const name = `${pathPrefix}${option.propertyName}`;
20  const { watch } = useFormContext();
21  const _watchValue = watch(name);
22  const value = _watchValue === undefined ? defaultValue : _watchValue;
23
24  const [show, setShow] = useState(!!value);
25
26  return (
27    <div className={styles.wrapper} data-testid={`${name}.container`}>
28      <h6>{option.label}</h6>
29      {option.description && <p className={styles.description}>{option.description}</p>}
30      {show && (
31        <>
32          {!readOnly && (
33            <ActionIcon
34              data-testid={`${name}.delete-button`}
35              icon="trash-alt"
36              tooltip="delete"
37              onClick={() => setShow(false)}
38              className={styles.deleteIcon}
39            />
40          )}
41          {(option.subformOptions ?? []).map((subOption) => {
42            return (
43              <OptionField
44                readOnly={readOnly}
45                defaultValue={defaultValue?.[subOption.propertyName]}
46                key={subOption.propertyName}
47                option={subOption}
48                pathPrefix={`${name}.`}
49                error={errors?.[subOption.propertyName]}
50              />
51            );
52          })}
53        </>
54      )}
55      {!show && !readOnly && (
56        <Button
57          className={styles.addButton}
58          type="button"
59          variant="secondary"
60          icon="plus"
61          size="sm"
62          onClick={() => setShow(true)}
63          data-testid={`${name}.add-button`}
64        >
65          Add
66        </Button>
67      )}
68    </div>
69  );
70};
71