import { App, Divider, Form, Input, Radio } from "antd";
import { useCallback, useEffect, useState } from "react";

import { copyToClipboard } from "@devowl-wp/react-utils";

import { __, _x } from "../../../../utils/i18n.js";

import type { DOMAttributes, FC } from "react";

const LAYOUT = {
    labelCol: { span: 24 },
    wrapperCol: { span: 24 },
};

/**
 * A generic generator for three types of shortcode links. For more details see `LinkShortcode.php`.
 */
const LinkShortcodeForm: FC<{ type: "history" | "revoke" | "change" }> = ({ type }) => {
    const { message } = App.useApp();
    const [result, setResult] = useState("");
    const initialValues = {
        tag: "a",
        id: "",
        text:
            type === "history"
                ? _x("Privacy settings history", "legal-text")
                : type === "revoke"
                  ? _x("Revoke consents", "legal-text")
                  : _x("Change privacy settings", "legal-text"),
        successmessage:
            type === "revoke"
                ? _x(
                      "You have successfully revoked consent for services with its cookies and personal data processing. The page will be reloaded now!",
                      "legal-text",
                  )
                : "",
    };
    const [form] = Form.useForm<typeof initialValues>();

    // Generate the shortcode and hold the result in state
    const handleValuesChange = useCallback(
        (changedValues, values: typeof initialValues) => {
            const attr: string[] = [];
            for (const key of Object.keys(values)) {
                const value = (values as any)[key];
                if (value) {
                    attr.push(`${key}="${value.replace('"', '\\"')}"`);
                }
            }

            setResult(`[rcb-consent type="${type}" ${attr.join(" ")}]`);
        },
        [setResult],
    );

    // Generate once
    useEffect(() => {
        handleValuesChange(
            initialValues as Parameters<typeof handleValuesChange>[0],
            initialValues as Parameters<typeof handleValuesChange>[1],
        );
    }, []);

    // Copy the shortcode to clipboard
    const handleCopyTextarea: DOMAttributes<HTMLButtonElement>["onClick"] = useCallback(() => {
        copyToClipboard(result);
        message.success(__("Successfully copied shortcode to clipboard!"));
    }, [result]);

    return (
        <Form
            name={`link-shortcode-${type}`}
            form={form}
            {...LAYOUT}
            initialValues={initialValues}
            onValuesChange={handleValuesChange}
        >
            <Form.Item label={__("Appearance")}>
                <Form.Item name="tag" noStyle>
                    <Radio.Group>
                        <Radio.Button value="a">{__("Link")}</Radio.Button>
                        <Radio.Button value="button">{__("Button")}</Radio.Button>
                    </Radio.Group>
                </Form.Item>
                <p className="description">
                    {__(
                        "It is recommended to use a simple link in your footer instead of a button to avoid visual misunderstandings.",
                    )}
                </p>
            </Form.Item>
            <Form.Item label={__("HTML ID")}>
                <Form.Item name="id" noStyle>
                    <Input />
                </Form.Item>
                <p className="description">
                    {__(
                        "If you want to apply a custom style to the link/button, the shortcode output should be tagged with an ID attribute.",
                    )}
                </p>
            </Form.Item>
            <Form.Item label={__("Text")}>
                <Form.Item name="text" noStyle>
                    <Input />
                </Form.Item>
                <p className="description">
                    {__("The user must be able to clearly understand the behaviour of the link/button from the name.")}
                </p>
            </Form.Item>
            {type === "revoke" && (
                <Form.Item label={__("Success message")}>
                    <Form.Item name="successmessage" noStyle>
                        <Input.TextArea autoSize />
                    </Form.Item>
                    <p className="description">
                        {__(
                            "After the consent is revoked, the page will be reloaded. Let the user know what happened with a success message.",
                        )}
                    </p>
                </Form.Item>
            )}
            <Form.Item>
                <Form.Item noStyle>
                    <Divider style={{ marginTop: 0 }}>{__("Result")}</Divider>
                    <Input.TextArea value={result} readOnly autoSize />
                </Form.Item>
                <p className="description">{__("Copy the generated shortcode and paste it into your website.")}</p>
                <button className="button alignright" onClick={handleCopyTextarea}>
                    {__("Copy to clipboard")}
                </button>
            </Form.Item>
        </Form>
    );
};

export { LinkShortcodeForm };
