import {
    Button,
    Group,
    Modal,
    MultiSelect,
    Select,
    TextInput,
    type ModalBaseProps,
} from "@mantine/core";
import { t } from "@/config/i18n";
import { DatePickerInput } from "@mantine/dates";
import { IconCancel, IconEdit, IconPlus } from "@tabler/icons-react";
import { useForm } from "@mantine/form";
import { useMemo } from "react";
import { type Shipment, type ShipmentInputs } from "@/services/resources/shipments";
import { useGetForms, useGetProductors, useGetProducts } from "@/services/api";

export type ShipmentModalProps = ModalBaseProps & {
    currentShipment?: Shipment;
    handleSubmit: (shipment: ShipmentInputs, id?: number) => void;
};

export default function ShipmentModal({
    opened,
    onClose,
    currentShipment,
    handleSubmit,
}: ShipmentModalProps) {
    const form = useForm<ShipmentInputs>({
        initialValues: {
            name: currentShipment?.name ?? "",
            date: currentShipment?.date ?? null,
            form_id: currentShipment ? String(currentShipment?.form_id) : "",
            product_ids: currentShipment?.products.map((el) => String(el.id)) ?? [],
        },
        validate: {
            name: (value) =>
                !value ? `${t("a name", { capfirst: true })} ${t("is required")}` : null,
            date: (value) =>
                !value ? `${t("a shipment date", { capfirst: true })} ${t("is required")}` : null,
            form_id: (value) =>
                !value ? `${t("a form", { capfirst: true })} ${t("is required")}` : null,
        },
    });

    const { data: allForms } = useGetForms();
    const { data: allProducts } = useGetProducts(new URLSearchParams("types=1"));
    const { data: allProductors } = useGetProductors();

    const formsSelect = useMemo(() => {
        return allForms?.map((currentForm) => ({
            value: String(currentForm.id),
            label: `${currentForm.name} ${currentForm.season}`,
        }));
    }, [allForms]);

    const productsSelect = useMemo(() => {
        if (!allProducts) return;
        return allProductors?.map((productor) => {
            return {
                group: productor.name,
                items: allProducts
                    .filter((product) => product.productor.id === productor.id)
                    .map((product) => ({
                        value: String(product.id),
                        label: `${product.name}`,
                    })),
            };
        });
    }, [allProductors, allProducts]);

    return (
        <Modal
            opened={opened}
            onClose={onClose}
            title={currentShipment ? t("edit shipment") : t("create shipment")}
        >
            <TextInput
                label={t("shipment name", { capfirst: true })}
                placeholder={t("shipment name", { capfirst: true })}
                radius="sm"
                withAsterisk
                {...form.getInputProps("name")}
            />
            <DatePickerInput
                label={t("shipment date", { capfirst: true })}
                placeholder={t("shipment date", { capfirst: true })}
                withAsterisk
                {...form.getInputProps("date")}
            />
            <Select
                label={t("shipment form", { capfirst: true })}
                placeholder={t("shipment form", { capfirst: true })}
                radius="sm"
                data={formsSelect || []}
                clearable
                withAsterisk
                {...form.getInputProps("form_id")}
            />
            <MultiSelect
                label={t("shipment products", { capfirst: true })}
                placeholder={t("shipment products", { capfirst: true })}
                description={t(
                    "shipment products is necessary only for planned products (if all products are recurrent leave empty)",
                    { capfirst: true },
                )}
                data={productsSelect || []}
                clearable
                searchable
                {...form.getInputProps("product_ids")}
            />
            <Group mt="sm" justify="space-between">
                <Button
                    variant="filled"
                    color="red"
                    aria-label={t("cancel", { capfirst: true })}
                    leftSection={<IconCancel />}
                    onClick={() => {
                        form.clearErrors();
                        onClose();
                    }}
                >
                    {t("cancel", { capfirst: true })}
                </Button>
                <Button
                    variant="filled"
                    aria-label={
                        currentShipment
                            ? t("edit shipment", { capfirst: true })
                            : t("create shipment", { capfirst: true })
                    }
                    leftSection={currentShipment ? <IconEdit /> : <IconPlus />}
                    onClick={() => {
                        form.validate();
                        if (form.isValid()) {
                            handleSubmit(form.getValues(), currentShipment?.id);
                        }
                    }}
                >
                    {currentShipment
                        ? t("edit shipment", { capfirst: true })
                        : t("create shipment", { capfirst: true })}
                </Button>
            </Group>
        </Modal>
    );
}
