import { Button, rem, Textarea, TextInput } from "@mantine/core";
import { QuickCard } from "../../../../types/QuickCard.ts";
import { FC } from "react";
import { useForm } from "@mantine/form";
import styles from "./CreateCardForm.module.css";
import ClientAutocomplete from "../../../Selects/ClientAutocomplete/ClientAutocomplete.tsx";
import { DateTimePicker } from "@mantine/dates";
import ShippingWarehouseAutocomplete
    from "../../../Selects/ShippingWarehouseAutocomplete/ShippingWarehouseAutocomplete.tsx";
import BaseMarketplaceSelect from "../../../Selects/BaseMarketplaceSelect/BaseMarketplaceSelect.tsx";
import { usePrefillCardContext } from "../../../../pages/CardsPage/contexts/PrefillCardContext.tsx";
import isModuleInProject, { Modules } from "../../../../modules/utils/isModuleInProject.ts";
import { useProjectsContext } from "../../../../contexts/ProjectsContext.tsx";

type Props = {
    onSubmit: (quickDeal: QuickCard) => void;
    onCancel: () => void;
};

const CreateCardForm: FC<Props> = ({ onSubmit, onCancel }) => {
    const { selectedProject } = useProjectsContext();
    const isPrefillingEnabled = isModuleInProject(Modules.SERVICES_AND_PRODUCTS, selectedProject);
    const { prefillOnOpen, prefillCard } = usePrefillCardContext();

    const isServicesAndProductsIncluded = isModuleInProject(Modules.SERVICES_AND_PRODUCTS, selectedProject);
    const isClientsIncluded = isModuleInProject(Modules.CLIENTS, selectedProject);

    const form = useForm<QuickCard>({
        initialValues: {
            name: "",
            clientName: null,
            comment: "",
            acceptanceDate: new Date(),
            shippingWarehouse: null,
            baseMarketplace: null,
        },
        validate: {
            baseMarketplace: baseMarketplace =>
                isServicesAndProductsIncluded && !baseMarketplace && "МП не выбран",
            shippingWarehouse: shippingWarehouse =>
                isServicesAndProductsIncluded && !shippingWarehouse && "Склад отгрузки не выбран",
            clientName: clientName =>
                isClientsIncluded && !clientName && "Клиент не выбран",
        },
    });

    const prefillButtonLabel = prefillCard ? `Предзаполнено [ID: ${prefillCard.id}]` : "Предзаполнить";

    return (
        <form
            style={{ width: "100%" }}
            onSubmit={form.onSubmit(values => onSubmit(values))}>
            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    width: "100%",
                    gap: rem(10),
                    padding: rem(10),
                }}>
                <div className={styles["inputs"]}>
                    <TextInput
                        placeholder={"Название"}
                        {...form.getInputProps("name")}
                    />
                </div>
                {isClientsIncluded && (
                    <div className={styles["inputs"]}>
                        <ClientAutocomplete
                            nameRestProps={form.getInputProps("clientName")}
                        />
                    </div>
                )}
                {isServicesAndProductsIncluded && (
                    <>
                        <div className={styles["inputs"]}>
                            <BaseMarketplaceSelect
                                rightSection={<></>}
                                placeholder={"Базовый маркетплейс"}
                                {...form.getInputProps("baseMarketplace")}
                            />
                        </div>
                        <div className={styles["inputs"]}>
                            <ShippingWarehouseAutocomplete
                                {...form.getInputProps("shippingWarehouse")}
                                placeholder={"Склад отгрузки"}
                            />
                        </div>
                    </>
                )}
                <div className={styles["inputs"]}>
                    <Textarea
                        autosize
                        placeholder={"Комментарий"}
                        minRows={2}
                        maxRows={4}
                        {...form.getInputProps("comment")}
                    />
                </div>
                <div className={styles["inputs"]}>
                    <DateTimePicker
                        placeholder={"Дата приемки"}
                        {...form.getInputProps("acceptanceDate")}
                    />
                </div>
                {isPrefillingEnabled && (
                    <div className={styles["button-prefill"]}>
                        <Button
                            style={{ whiteSpace: "wrap" }}
                            variant={"outline"}
                            onClick={() => prefillOnOpen()}>
                            {prefillButtonLabel}
                        </Button>
                    </div>
                )}
                <div className={styles["buttons"]}>
                    <Button type={"submit"}>Добавить</Button>
                    <Button
                        variant={"outline"}
                        onClick={() => onCancel()}>
                        Отменить
                    </Button>
                </div>
            </div>
        </form>
    );
};

export default CreateCardForm;
