import { App, Checkbox, Divider, Form, Input, Spin } from "antd";
import { observer } from "mobx-react";
import { useCallback, useState } from "react";

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

import { useStores } from "../../../store/stores.js";
import { __ } from "../../../utils/i18n.js";
import { request, urlBuilder } from "../../../utils/request.js";
import { locationRestExportGet } from "../../../wp-api/export.get.js";

import type {
    ParamsRouteExportGet,
    RequestRouteExportGet,
    ResponseRouteExportGet,
} from "../../../wp-api/export.get.js";
import type { ComponentProps, DOMAttributes, FC } from "react";

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

const ExportForm: FC = observer(() => {
    const { message } = App.useApp();
    const {
        optionStore: {
            isTcf,
            others: {
                hints: { export: exportHints },
            },
        },
    } = useStores();
    const [form] = Form.useForm();
    const [isBusy, setBusy] = useState(false);
    const [result, setResult] = useState("");
    const initialValues = {
        settings: true,
        cookieGroups: true,
        cookies: true,
        blocker: true,
        tcfVendorConfigurations: true,
        customizeBanner: true,
    };

    // Request export data from REST API
    const handleFinish: ComponentProps<typeof Form>["onFinish"] = useCallback(async (values) => {
        setBusy(true);
        try {
            setResult(
                JSON.stringify(
                    await request<RequestRouteExportGet, ParamsRouteExportGet, ResponseRouteExportGet>({
                        location: locationRestExportGet,
                        params: values as ParamsRouteExportGet,
                    }),
                ),
            );
        } finally {
            setBusy(false);
        }
    }, []);

    // Copy the export to clipboard automatically on click textarea
    const handleCopyTextarea: ComponentProps<typeof Input.TextArea>["onClick"] = useCallback(() => {
        copyToClipboard(result);
        message.success(__("Export successfully copied to the clipboard."));
    }, [result]);

    // Download export as JSON
    const handleDownloadButton: DOMAttributes<HTMLInputElement>["onClick"] = useCallback(
        (e) => {
            (async () => {
                setBusy(true);
                window.location.href = urlBuilder({
                    location: locationRestExportGet,
                    params: {
                        ...form.getFieldsValue(),
                        download: true,
                    },
                });
                setBusy(false);
            })();
            e.preventDefault();
            return false;
        },
        [setBusy, form],
    );

    return (
        <Spin spinning={isBusy}>
            <Form name="export" form={form} {...LAYOUT} initialValues={initialValues} onFinish={handleFinish} labelWrap>
                <Form.Item label={__("Content to export")}>
                    <div>
                        <Form.Item name="settings" noStyle valuePropName="checked">
                            <Checkbox>{__("Settings")}</Checkbox>
                        </Form.Item>
                    </div>
                    <div>
                        <Form.Item name="cookieGroups" noStyle valuePropName="checked">
                            <Checkbox>{__("Service groups")}</Checkbox>
                        </Form.Item>
                    </div>
                    <div>
                        <Form.Item name="cookies" noStyle valuePropName="checked">
                            <Checkbox>{__("Services")}</Checkbox>
                        </Form.Item>
                    </div>
                    <div>
                        <Form.Item name="blocker" noStyle valuePropName="checked">
                            <Checkbox>{__("Content Blocker")}</Checkbox>
                        </Form.Item>
                    </div>
                    {isTcf && (
                        <div>
                            <Form.Item name="tcfVendorConfigurations" noStyle valuePropName="checked">
                                <Checkbox>{__("TCF Vendor configurations")}</Checkbox>
                            </Form.Item>
                        </div>
                    )}
                    <div>
                        <Form.Item name="customizeBanner" noStyle valuePropName="checked">
                            <Checkbox>{__("Cookie banner customization")}</Checkbox>
                        </Form.Item>
                    </div>
                </Form.Item>
                <Form.Item>
                    <input
                        type="submit"
                        className="button button-primary"
                        style={{ marginTop: 10 }}
                        value={__("Export")}
                    />
                    <input
                        onClick={handleDownloadButton}
                        type="submit"
                        className="button"
                        style={{ margin: "10px 0 0 10px" }}
                        value={__("Download JSON")}
                    />
                    {exportHints.length > 0 && (
                        <div className="notice notice-info inline below-h2 notice-alt" style={{ margin: "10px 0 0 0" }}>
                            <p>{reactNl2Br(exportHints.join("\n\n"))}</p>
                        </div>
                    )}
                </Form.Item>
                <Form.Item style={{ display: result ? "block" : "none" }}>
                    <Form.Item noStyle>
                        <Divider style={{ marginTop: 0 }}>{__("Result")}</Divider>
                        <Input.TextArea onClick={handleCopyTextarea} value={result} readOnly rows={5} />
                    </Form.Item>
                    <p className="description">
                        {__(
                            'Copy the exported content and paste it into the "Import" text area of your target WordPress installation.',
                        )}
                    </p>
                </Form.Item>
            </Form>
        </Spin>
    );
});

export { ExportForm };
