import { Form, Input, Radio, Spin } from "antd";
import { observer } from "mobx-react";
import moment from "moment";
import { useCallback, useState } from "react";

import { __ } from "../../../utils/i18n.js";
import { urlBuilder } from "../../../utils/request.js";
import { locationRestExportConsentsGet } from "../../../wp-api/exportConsents.get.js";
import { DateRangePicker } from "../../dateRangePicker.js";

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

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

type FormValues = {
    by: "" | "date" | "uuid";
    date: moment.Moment[];
    uuid: string;
};

const ExportConsentsForm: FC = observer(() => {
    const [form] = Form.useForm();
    const [isBusy, setBusy] = useState(false);
    const [showSizeHint, setShowSizeHint] = useState(false);
    const initialValues: FormValues = {
        by: "",
        date: [],
        uuid: "",
    };

    // Download export as CSV
    const handleDownloadButton: ComponentProps<typeof Form>["onFinish"] = useCallback(() => {
        (async () => {
            setBusy(true);
            setShowSizeHint(true);
            const { uuid, date } = form.getFieldsValue() as FormValues;
            const url = urlBuilder({
                location: locationRestExportConsentsGet,
                params: {
                    uuid: uuid || "",
                    from: date?.[0].format("YYYY-MM-DD") || "",
                    to: date?.[1].format("YYYY-MM-DD") || "",
                },
            });
            window.open(url, "_blank");
            setBusy(false);
        })();
    }, [setBusy, setShowSizeHint, form]);

    return (
        <Spin spinning={isBusy}>
            <Form
                name="export"
                form={form}
                {...LAYOUT}
                initialValues={initialValues}
                onFinish={handleDownloadButton}
                labelWrap
            >
                <Form.Item label={__("Export by")} required>
                    <Form.Item name="by" noStyle rules={[{ required: true, message: __("Please select an option!") }]}>
                        <Radio.Group>
                            <Radio.Button value="date">{__("Date range")}</Radio.Button>
                            <Radio.Button value="uuid">{__("UUID")}</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                </Form.Item>
                <Form.Item noStyle shouldUpdate={(prevValues, nextValues) => prevValues.by !== nextValues.by}>
                    {({ getFieldValue }) =>
                        (getFieldValue("by") as FormValues["by"]) === "date" && (
                            <Form.Item
                                name="date"
                                label={__("Date range")}
                                required
                                rules={[
                                    {
                                        type: "array",
                                        required: true,
                                        message: __("Please provide a valid date range!"),
                                    },
                                ]}
                            >
                                <DateRangePicker disabledDate={(d) => !d || d.isAfter(moment())} />
                            </Form.Item>
                        )
                    }
                </Form.Item>
                <Form.Item noStyle shouldUpdate={(prevValues, nextValues) => prevValues.by !== nextValues.by}>
                    {({ getFieldValue }) =>
                        (getFieldValue("by") as FormValues["by"]) === "uuid" && (
                            <Form.Item
                                name="uuid"
                                label={__("UUID")}
                                required
                                rules={[
                                    {
                                        required: true,
                                        pattern: /^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/,
                                        message: __("Please provide a valid UUID!"),
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>
                        )
                    }
                </Form.Item>
                <Form.Item>
                    <input
                        type="submit"
                        className="button button-primary"
                        style={{ marginTop: 10 }}
                        value={__("Download CSV")}
                    />
                </Form.Item>
                {showSizeHint && (
                    <div className="notice notice-info inline below-h2 notice-alt" style={{ margin: "10px 0 0 0" }}>
                        <p>
                            {__(
                                "The CSV file can be very large because data in this format is redundant per line. In your WordPress database the consents are much smaller.",
                            )}
                        </p>
                    </div>
                )}
            </Form>
        </Spin>
    );
});

export { ExportConsentsForm };
