import { Button, Group, Modal, Select, type ModalBaseProps } from "@mantine/core";
import { t } from "@/config/i18n";
import { useForm } from "@mantine/form";
import { IconCancel, IconDownload } from "@tabler/icons-react";
import { useGetForms } from "@/services/api";
import { useMemo } from "react";

export type ContractModalProps = ModalBaseProps & {
    handleSubmit: (id: number) => void;
};

export type ContractDownloadInputs = {
    form_id: number;
};

export function ContractModal({ opened, onClose, handleSubmit }: ContractModalProps) {
    const { data: allForms } = useGetForms();
    const form = useForm({
        initialValues: {
            form_id: null,
        },
        validate: {
            form_id: (value) =>
                !value ? `${t("a form", { capfirst: true })} ${t("is required")}` : null,
        },
    });

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

    return (
        <Modal
            opened={opened}
            onClose={onClose}
            title={t("download contracts", { capfirst: true })}
        >
            <Select
                label={t("form", { capfirst: true })}
                placeholder={t("select a form", { capfirst: true })}
                description={t(
                    "by selecting a form here you can download all contracts of your form",
                    { capfirst: true },
                )}
                nothingFoundMessage={t("nothing found", { capfirst: true })}
                withAsterisk
                clearable
                allowDeselect
                searchable
                data={formSelect || []}
                {...form.getInputProps("form_id")}
            />
            <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={t("download contracts")}
                    leftSection={<IconDownload />}
                    onClick={() => {
                        form.validate();
                        if (form.isValid()) {
                            handleSubmit(Number(form.values.form_id));
                        }
                    }}
                >
                    {t("download contracts", { capfirst: true })}
                </Button>
            </Group>
        </Modal>
    );
}
