import { App, Form, Spin } from "antd";
import { observer } from "mobx-react";
import { useNavigate } from "react-router-dom";

import { createCopy } from "@devowl-wp/multilingual";
import {
    FormServiceGroup,
    useFormServiceGroupHandler,
    useFormServiceGroupProvider,
} from "@devowl-wp/react-cookie-banner-admin";

import { CookieGroupModel } from "../../../../models/cookieGroupModel.js";
import { useStores } from "../../../../store/stores.js";
import { __ } from "../../../../utils/i18n.js";

import type { FC } from "react";

const CookieGroupEditForm: FC<{
    onClose?: () => void;
    edit?: CookieGroupModel;
    navigateAfterCreation?: boolean;
}> = observer(({ onClose, edit, navigateAfterCreation = true }) => {
    const { message } = App.useApp();
    const navigate = useNavigate();
    const {
        cookieStore,
        optionStore: {
            others: {
                defaultCookieGroupTexts: { [edit?.data.name || ""]: defaultDescription },
            },
        },
    } = useStores();
    const data = edit?.data;

    const { form, defaultValues, isBusy, onFinish, onFinishFailed, onValuesChange, contextValue } =
        useFormServiceGroupHandler({
            // Currently, we do not provide service group templates, but who knows in future?
            template: defaultDescription
                ? { identifier: "none", version: 1, name: "", description: defaultDescription }
                : undefined,
            handleSave: async (values) => {
                try {
                    if (edit) {
                        edit.setName(values.name);
                        edit.setDescription(values.description);
                        await edit.patch();
                        return () => {
                            // Silence is golden.
                        };
                    } else {
                        const draft = new CookieGroupModel(cookieStore.groups, {
                            name: values.name,
                            description: values.description,
                            meta: {
                                order: cookieStore.groups.entries.size,
                                isEssential: false,
                                isDefault: false,
                            },
                        });
                        await draft.persist();
                        onClose?.();
                        return () => navigateAfterCreation && navigate(`/cookies/${draft.key.toString()}`);
                    }
                } catch (e) {
                    const { code, ...rest } = (e as any).responseJSON;
                    throw ["term_exists", "duplicate_term_slug"].indexOf(code) > -1
                        ? __("The service group already exists!")
                        : rest.message;
                }
            },
        });

    const initialValues = edit ? { name: data.name, description: data.description } : defaultValues;

    const [FormServiceGroupContextProvider, formServiceGroupContextValue] = useFormServiceGroupProvider({
        ...contextValue,
        recordId: data?.id,
        languages: data?.multilingual,
        languageOnClick: async (recordId, { code, id }) => {
            try {
                const forwardId = id === false ? (await createCopy("rcb-cookie-group", recordId, code)).id : id;

                // Open the newly created blocker
                const url = new URL(window.location.href);
                url.hash = `#/cookies/${forwardId}`;
                url.searchParams.set("lang", code);
                window.location.href = url.toString();
            } catch (e) {
                if (e.responseJSON?.message) {
                    message.error(e.responseJSON.message);
                } else {
                    throw e;
                }
            }
        },
        onCancel: onClose,
    });

    return (
        <FormServiceGroupContextProvider value={formServiceGroupContextValue}>
            <Spin spinning={isBusy}>
                <strong>{edit ? __("Edit service group") : __("Add new service group")}</strong>
                <hr />
                <Form
                    name="edit-group-form"
                    form={form}
                    style={{ width: 300 }}
                    layout="vertical"
                    initialValues={initialValues}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    onValuesChange={onValuesChange}
                    labelWrap
                >
                    <FormServiceGroup />
                </Form>
            </Spin>
        </FormServiceGroupContextProvider>
    );
});

export { CookieGroupEditForm };
