"use client";

import { Stack, TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import BaseMarketplaceSelect from "@/app/clients/drawers/ClientMarketplacesDrawer/components/BaseMarketplaceSelect";
import MarketplaceAuthDataInput from "@/app/clients/drawers/ClientMarketplacesDrawer/components/MarketplaceAuthDataInput/MarketplaceAuthDataInput";
import {
    CreateMarketplaceSchema,
    MarketplaceSchema,
    UpdateMarketplaceSchema,
} from "@/lib/client";
import BaseFormModal, {
    CreateEditFormProps,
} from "@/modals/base/BaseFormModal/BaseFormModal";

type Props = CreateEditFormProps<
    MarketplaceSchema,
    CreateMarketplaceSchema,
    UpdateMarketplaceSchema
>;

const MarketplaceEditorModal = ({
    context,
    id,
    innerProps,
}: ContextModalProps<Props>) => {
    const initialValues: UpdateMarketplaceSchema | CreateMarketplaceSchema =
        innerProps.isEditing
            ? innerProps.entity
            : {
                  name: "",
                  authData: {
                      "Authorization": "",
                      "Client-Id": "",
                      "Api-Key": "",
                      "CampaignId": "",
                  },
              };

    const form = useForm({
        initialValues,
        validate: {
            name: name =>
                (!name || name.trim() === "") &&
                "Необходимо ввести название маркетплейса",
            baseMarketplace: baseMarketplace =>
                !baseMarketplace && "Необходимо указать базовый маркетплейс",
            authData: authData =>
                !authData && "Необходимо указать данные авторизации",
        },
    });

    return (
        <BaseFormModal
            {...innerProps}
            closeOnSubmit
            form={form}
            onClose={() => context.closeContextModal(id)}>
            <Stack gap={"xs"}>
                <TextInput
                    label={"Название"}
                    placeholder={"Введите название маркетплейса"}
                    {...form.getInputProps("name")}
                />
                <BaseMarketplaceSelect
                    label={"Базовый маркетплейс"}
                    placeholder={"Выберите базовый маркетплейс"}
                    {...form.getInputProps("baseMarketplace")}
                />

                {form.values.baseMarketplace && (
                    <MarketplaceAuthDataInput
                        baseMarketplace={form.values.baseMarketplace}
                        value={form.values.authData as Record<string, string>}
                        onChange={value =>
                            form.setFieldValue("authData", value)
                        }
                        error={form.getInputProps("authData").error}
                    />
                )}
            </Stack>
        </BaseFormModal>
    );
};

export default MarketplaceEditorModal;
