import {
    Button,
    Group,
    Modal,
    NumberInput,
    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 { useGetProductors, useGetUsers } from "@/services/api";
import { useForm } from "@mantine/form";
import { useMemo } from "react";
import type { Form, FormInputs } from "@/services/resources/forms";

export type FormModalProps = ModalBaseProps & {
    currentForm?: Form;
    handleSubmit: (form: FormInputs, id?: number) => void;
};

export default function FormModal({ opened, onClose, currentForm, handleSubmit }: FormModalProps) {
    const { data: productors } = useGetProductors();
    const { data: users } = useGetUsers();

    const form = useForm<FormInputs>({
        initialValues: {
            name: currentForm?.name ?? "",
            season: currentForm?.season ?? "",
            start: currentForm?.start ?? null,
            end: currentForm?.end ?? null,
            productor_id: currentForm?.productor?.id.toString() ?? "",
            referer_id: currentForm?.referer?.id.toString() ?? "",
            minimum_shipment_value: currentForm?.minimum_shipment_value ?? null,
        },
        validate: {
            name: (value) =>
                !value ? `${t("a name", { capfirst: true })} ${t("is required")}` : null,
            season: (value) =>
                !value ? `${t("a season", { capfirst: true })} ${t("is required")}` : null,
            start: (value) =>
                !value ? `${t("a start date", { capfirst: true })} ${t("is required")}` : null,
            end: (value) =>
                !value ? `${t("a end date", { capfirst: true })} ${t("is required")}` : null,
            productor_id: (value) =>
                !value ? `${t("a productor", { capfirst: true })} ${t("is required")}` : null,
            referer_id: (value) =>
                !value ? `${t("a referer", { capfirst: true })} ${t("is required")}` : null,
        },
    });

    const usersSelect = useMemo(() => {
        return users?.map((user) => ({
            value: String(user.id),
            label: `${user.name}`,
        }));
    }, [users]);

    const productorsSelect = useMemo(() => {
        return productors?.map((prod) => ({
            value: String(prod.id),
            label: `${prod.name}`,
        }));
    }, [productors]);

    return (
        <Modal
            opened={opened}
            onClose={onClose}
            title={
                currentForm
                    ? t("edit form", { capfirst: true })
                    : t("create form", { capfirst: true })
            }
        >
            <TextInput
                label={t("form name", { capfirst: true })}
                placeholder={t("form name", { capfirst: true })}
                radius="sm"
                withAsterisk
                {...form.getInputProps("name")}
            />
            <TextInput
                label={t("contract season", { capfirst: true })}
                placeholder={t("contract season", { capfirst: true })}
                description={t("contract season recommandation", { capfirst: true })}
                radius="sm"
                withAsterisk
                {...form.getInputProps("season")}
            />
            <Group grow>
                <DatePickerInput
                    label={t("start date", { capfirst: true })}
                    placeholder={t("start date", { capfirst: true })}
                    withAsterisk
                    {...form.getInputProps("start")}
                />
                <DatePickerInput
                    label={t("end date", { capfirst: true })}
                    placeholder={t("end date", { capfirst: true })}
                    withAsterisk
                    {...form.getInputProps("end")}
                />
            </Group>
            <Select
                label={t("referer", { capfirst: true })}
                placeholder={t("referer", { capfirst: true })}
                nothingFoundMessage={t("nothing found", { capfirst: true })}
                withAsterisk
                clearable
                allowDeselect
                searchable
                data={usersSelect || []}
                {...form.getInputProps("referer_id")}
            />
            <Select
                label={t("productor", { capfirst: true })}
                placeholder={t("productor", { capfirst: true })}
                nothingFoundMessage={t("nothing found", { capfirst: true })}
                withAsterisk
                clearable
                allowDeselect
                searchable
                data={productorsSelect || []}
                {...form.getInputProps("productor_id")}
            />
            <NumberInput
                label={t("minimum shipment value", { capfirst: true })}
                placeholder={t("minimum shipment value", { capfirst: true })}
                description={t(
                    "some contracts require a minimum value per shipment, ignore this field if it's not the case",
                    { capfirst: true },
                )}
                radius="sm"
                {...form.getInputProps("minimum_shipment_value")}
            />
            <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={
                        currentForm
                            ? t("edit form", { capfirst: true })
                            : t("create form", { capfirst: true })
                    }
                    leftSection={currentForm ? <IconEdit /> : <IconPlus />}
                    onClick={() => {
                        form.validate();
                        if (form.isValid()) {
                            handleSubmit(form.getValues(), currentForm?.id);
                        }
                    }}
                >
                    {currentForm
                        ? t("edit form", { capfirst: true })
                        : t("create form", { capfirst: true })}
                </Button>
            </Group>
        </Modal>
    );
}
