"use client";

import { TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import ServicesMultiselect from "@/app/services/components/shared/ServicesMultiselect/ServicesMultiselect";
import ServiceTypeSegmentedControl from "@/app/services/components/shared/ServiceTypeSegmentedControl/ServiceTypeSegmentedControl";
import { ServicesKitSchema } from "@/lib/client";
import BaseFormModal, {
    CreateEditFormProps,
} from "@/modals/base/BaseFormModal/BaseFormModal";
import { ServiceType } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/types/service";

type Props = CreateEditFormProps<ServicesKitSchema>;

const ServicesKitEditorModal = ({
    context,
    id,
    innerProps,
}: ContextModalProps<Props>) => {
    const initialValues: Partial<ServicesKitSchema> = innerProps.isEditing
        ? innerProps.entity
        : {
              name: "",
              serviceType: ServiceType.DEAL_SERVICE,
              services: [],
          };

    const form = useForm<Partial<ServicesKitSchema>>({
        initialValues,
        validate: {
            name: name => !name && "Введите название",
            services: services =>
                (!services || services.length === 0) && "Выберите услуги",
        },
    });

    return (
        <BaseFormModal
            {...innerProps}
            form={form}
            closeOnSubmit
            onClose={() => context.closeContextModal(id)}>
            <TextInput
                label={"Название"}
                placeholder={"Введите название набора услуг"}
                {...form.getInputProps("name")}
            />
            <ServiceTypeSegmentedControl
                value={form.values.serviceType?.toString()}
                onChange={tab => {
                    form.setFieldValue("serviceType", Number(tab));
                    form.setFieldValue("services", []);
                }}
                mt={"xs"}
            />
            <ServicesMultiselect
                label={"Услуги"}
                placeholder={"Выберите услуги"}
                filterBy={service =>
                    service.serviceType === form.values.serviceType
                }
                groupBy={service => service.category.name}
                {...form.getInputProps("services")}
            />
        </BaseFormModal>
    );
};

export default ServicesKitEditorModal;
