import { RollbackOutlined } from "@ant-design/icons";
import { Form, Input } from "antd";

import { useFormServiceGroup } from "../../../../contexts/formServiceGroup.js";
import { useI18n } from "../../../../contexts/i18n.js";

import type { FormServiceGroupValueProps } from "../../../../types/formServiceGroup.js";
import type { FC } from "react";

const FormServiceGroupFieldDescription: FC = () => {
    const { __ } = useI18n();
    const {
        defaultTemplateValues: { description: defaultDescription },
    } = useFormServiceGroup();

    return (
        <Form.Item<FormServiceGroupValueProps>
            label={
                <>
                    {__("Description")}
                    {!!defaultDescription && (
                        <Form.Item<FormServiceGroupValueProps>
                            shouldUpdate={(prevValues, nextValues) => prevValues.name !== nextValues.name}
                            noStyle
                        >
                            {({ getFieldValue, setFieldsValue }) =>
                                getFieldValue("description") !== defaultDescription && (
                                    <a
                                        style={{ marginLeft: 10 }}
                                        onClick={() => setFieldsValue({ description: defaultDescription })}
                                    >
                                        <RollbackOutlined />
                                    </a>
                                )
                            }
                        </Form.Item>
                    )}
                </>
            }
            name="description"
            required
            style={{ marginBottom: 12 }}
            rules={[{ required: true, message: __("Please enter a description!") }]}
        >
            <Input.TextArea
                autoSize
                onKeyDown={(e) =>
                    /**
                     * `rc-tabs` defines an `onKeyDown` event which causes issues with enter and spaces and avoids
                     * input fields in the tab to get filled correctly.
                     *
                     * @see https://git.io/JUZZO
                     */
                    e.stopPropagation()
                }
            />
        </Form.Item>
    );
};

export { FormServiceGroupFieldDescription };
