import { Form, Input } from "antd";

import { DYNAMICS_VARIABLE_REGEXP } from "@devowl-wp/headless-content-unblocker";

import { useFormService } from "../../../../../contexts/formService.js";
import { useI18n } from "../../../../../contexts/i18n.js";
import { Notices } from "../../../../common/notices.js";

import type { FormServiceValueProps } from "../../../../../types/formService.js";
import type { FC } from "react";

const DYNAMICS_SEARCH_IN: (keyof FormServiceValueProps)[] = ["codeOptIn", "codeOptOut", "codeOnPageLoad"];

type FormServiceFieldHandlingDynamicFieldProps = {
    name: string;
    label?: string;
    expression?: string;
    invalidMessage?: string;
    example?: string;
    hint?: string;
};

const FormServiceFieldHandlingDynamicField: FC = () => {
    const { __ } = useI18n();
    const { template } = useFormService();

    return (
        <Form.Item<FormServiceValueProps>
            noStyle
            shouldUpdate={(prevValues, nextValues) =>
                DYNAMICS_SEARCH_IN.map((k) => prevValues[k] !== nextValues[k]).filter(Boolean).length > 0
            }
        >
            {({ getFieldValue }) => {
                const searchInResolved = DYNAMICS_SEARCH_IN.map((k) => getFieldValue(k)).join("");
                const matches = Array.from(searchInResolved.matchAll(DYNAMICS_VARIABLE_REGEXP)).map(([, m]) => m);
                const added: string[] = [];

                return matches
                    ? matches.map((name) => {
                          const formName = ["codeDynamics", name];
                          const {
                              label,
                              invalidMessage = __("Please fill in a value!"),
                              example,
                              expression,
                              hint,
                          } = template?.dynamicFields?.find((dynamicField) => dynamicField.name === name) || {};

                          if (added.indexOf(name) > -1) {
                              return null;
                          }
                          added.push(name);

                          return (
                              <Form.Item<FormServiceValueProps>
                                  key={name}
                                  label={label || <code>{name}</code>}
                                  required
                              >
                                  <Form.Item
                                      noStyle
                                      name={formName}
                                      rules={[
                                          {
                                              required: true,
                                              pattern: expression ? new RegExp(expression) : undefined,
                                              message: invalidMessage,
                                          },
                                      ]}
                                      normalize={(value) => value.trim()}
                                  >
                                      <Input placeholder={example} />
                                  </Form.Item>
                                  <Notices
                                      notices={[
                                          {
                                              message: hint,
                                              severity: "info",
                                          },
                                      ]}
                                  />
                              </Form.Item>
                          );
                      })
                    : null;
            }}
        </Form.Item>
    );
};

export { FormServiceFieldHandlingDynamicField, type FormServiceFieldHandlingDynamicFieldProps };
