import { Form, Select } from "antd";
import { useState } from "react";

import { getManagerDependingVariables } from "@devowl-wp/cookie-consent-web-client";

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

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

const FormServiceFieldGeneralGroup: FC = () => {
    const { __ } = useI18n();
    const { template, setCookiesViaManager, essentialGroupId, groups, preselectGroup, isGcm } = useFormService();
    const [ref, setRef] = useState<HTMLParagraphElement>();

    const { managerLabel, serviceIsManager } = getManagerDependingVariables(setCookiesViaManager, {
        isGcm,
        presetId: template?.identifier,
    });

    return (
        <Form.Item<FormServiceValueProps> label={__("Group")} required>
            <Form.Item<FormServiceValueProps>
                name="group"
                noStyle
                rules={[{ required: true, message: __("Please provide a group!") }]}
            >
                <Select>
                    {groups.map(({ id, name }) => (
                        <Select.Option key={id} value={id}>
                            {name}
                        </Select.Option>
                    ))}
                </Select>
            </Form.Item>
            <p className="description" ref={setRef}>
                <FormValueDifferFromTemplateTag
                    form="service"
                    valueName="group"
                    widthOfRef={ref}
                    style={{ marginBottom: 3 }}
                    ignoreEmptyDefaultValue
                    renderDiff={(value) => (
                        <Select value={value} disabled>
                            {groups.map(({ id, name }) => (
                                <Select.Option key={id} value={id}>
                                    {name}
                                </Select.Option>
                            ))}
                        </Select>
                    )}
                />
                {__(
                    "Each service must be assigned to a group. All services that do not belong to the group of essential services can (but do not have to) be accepted by visitors. According to the ePrivacy Directive, only services without which the website would not work are considered as essential services if the visitor has explicitly requested the service used. A possible economic interest of the website operator in using a tool, e.g. Google Analytics, is irrelevant.",
                )}
            </p>
            <Form.Item<FormServiceValueProps>
                noStyle
                shouldUpdate={(prevValues, curValues) => prevValues.group !== curValues.group}
            >
                {({ getFieldValue }) => (
                    <Notices
                        notices={[
                            {
                                message:
                                    serviceIsManager &&
                                    managerLabel &&
                                    (getFieldValue("group") as number) !== essentialGroupId
                                        ? __(
                                              "You have defined %1$s in a non-essential service group. In our legal opinion, this is the only way to use %1$s legally. However, please note that if a user doesn't consent to load %1$s, opt-in and opt-out events will not be sent to %1$s. Real Cookie Banner offers you the possibility to specify a fallback HTML/JavaScript for this case.",
                                              managerLabel,
                                          )
                                        : undefined,
                                severity: "warning",
                            },
                            {
                                message:
                                    preselectGroup === "preset-group-not-found"
                                        ? __(
                                              "The service group in which this service is normally placed (%s) has been deleted by you. Please group the service yourself.",
                                              template.group,
                                          )
                                        : undefined,
                                severity: "warning",
                            },
                            {
                                message: (
                                    <Form.Item<FormServiceValueProps>
                                        noStyle
                                        key="groupDiff"
                                        shouldUpdate={(prevValues, nextValues) => prevValues.group !== nextValues.group}
                                    >
                                        {({ getFieldValue }) => (
                                            <Notices
                                                notices={[
                                                    {
                                                        message:
                                                            template &&
                                                            typeof preselectGroup === "number" &&
                                                            (getFieldValue("group") as number) !== preselectGroup
                                                                ? __(
                                                                      "The groups specified in service templates were chosen wisely. Are you sure that this service should be assigned to another group for your case?",
                                                                  )
                                                                : undefined,
                                                        severity: "warning",
                                                    },
                                                ]}
                                            />
                                        )}
                                    </Form.Item>
                                ),
                            },
                            {
                                message: template?.groupNotice,
                                severity: "info",
                            },
                        ]}
                    />
                )}
            </Form.Item>
        </Form.Item>
    );
};

export { FormServiceFieldGeneralGroup };
