import { t } from "@/config/i18n";
import type { ContractInputs } from "@/services/resources/contracts";
import { Group, NumberInput, Stack, Text, TextInput, Title } from "@mantine/core";
import type { UseFormReturnType } from "@mantine/form";
import { useEffect } from "react";

export type ContractChequeProps = {
    inputForm: UseFormReturnType<ContractInputs>;
    price: number;
    chequeOrder: string;
};

export type Cheque = {
    name: string;
    value: string;
};

export function ContractCheque({ inputForm, price, chequeOrder }: ContractChequeProps) {
    useEffect(() => {
        if (!inputForm.values.payment_method.includes("cheque")) {
            return;
        }
        const quantity = Number(inputForm.values.cheque_quantity);
        if (!quantity || quantity <= 0) return;
        const cheques = inputForm.values.cheques || [];
        if (cheques.length !== quantity) {
            const newCheques = Array.from({ length: quantity }, (_, i) => ({
                name: cheques[i]?.name ?? "",
                value: cheques[i]?.value ?? 0,
            }));
            inputForm.setFieldValue("cheques", newCheques);
        }

        const totalCents = Math.round(price * 100);
        const base = Math.floor(totalCents / quantity);
        const rest = totalCents - base * quantity;
        for (let i = 0; i < quantity; i++) {
            const val = (i === quantity - 1 ? base + rest : base) / 100;
            inputForm.setFieldValue(`cheques.${i}.value`, val.toFixed(2));
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [inputForm.values.cheque_quantity, price, inputForm.values.cheques]);

    return (
        <Stack>
            <Title order={4}>{`${t("order name")} : ${chequeOrder}`}</Title>
            <NumberInput
                label={t("cheque quantity", { capfirst: true })}
                placeholder={t("enter cheque quantity", { capfirst: true })}
                description={t(
                    "number of cheques between 1 and 3 cheques also enter your cheques identifiers, value is calculated automatically",
                    { capfirst: true },
                )}
                min={1}
                max={3}
                {...inputForm.getInputProps(`cheque_quantity`)}
            />
            <Group grow>
                {inputForm.values.cheques.map((cheque, index) => (
                    <Stack key={`${index}`}>
                        <TextInput
                            label={t("cheque id", { capfirst: true })}
                            placeholder={t("cheque id", { capfirst: true })}
                            {...inputForm.getInputProps(`cheques.${index}.name`)}
                            error={
                            cheque.name == "" ? 
                            <Text size="sm" c="red">{inputForm?.errors.cheques}</Text> :
                            null
                        }
                        />   
                        <NumberInput
                            readOnly
                            label={t("cheque value", { capfirst: true })}
                            suffix={"€"}
                            placeholder={t("enter cheque value", { capfirst: true })}
                            {...inputForm.getInputProps(`cheques.${index}.value`)}
                        />
                    </Stack>
                ))}
            </Group>
        </Stack>
    );
}
