import BaseFormModal, {CreateProps} from "../../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import {PaymentRecordCreateSchema} from "../../../../client";
import {ContextModalProps} from "@mantine/modals";
import {useForm} from "@mantine/form";
import {Flex, NumberInput, rem} from "@mantine/core";
import {DatePickerInput, MonthPickerInput} from "@mantine/dates";
import {useEffect, useState} from "react";
import UserSelect from "../../../../components/Selects/UserSelect/UserSelect.tsx";
import {PaySchemeType} from "../../../../shared/enums/PaySchemeType.ts";
import {motion} from "framer-motion";
import {dateWithoutTimezone} from "../../../../shared/lib/date.ts";

type Props = CreateProps<PaymentRecordCreateSchema>;
const CreatePaymentRecordModal = ({
                                      context,
                                      id,
                                      innerProps
                                  }: ContextModalProps<Props>) => {
    const form = useForm<Partial<PaymentRecordCreateSchema>>({
        validate: {
            user: (user) => !user && "Необходимо выбрать сотрудника",
            startDate: (startDate) => !startDate && "Необходимо указать временной промежуток",
            workUnits: (workUnits) => !workUnits && "Укажите количество"
        }
    })
    const [dateRange, setDateRange] = useState<[Date | null, Date | null]>([null, null]);
    useEffect(() => {

        const setDates = (start: string | undefined, end: string | undefined) => {
            form.setFieldValue("startDate", start);
            form.setFieldValue("endDate", end);
        };

        if (dateRange.every(dr => dr == null)) {
            setDates(undefined, undefined);
            return
        } else {
            const notNullValues = dateRange.filter((dr): dr is Date => dr !== null).map(dateWithoutTimezone);
            const startDate = notNullValues[0];
            const endDate = notNullValues[1] || startDate;
            setDates(startDate, endDate);
        }
    }, [dateRange]);

    const getDateRangeInput = () => {
        if (!form.values.user) return <></>
        const payRate = form.values.user.payRate;
        if (!payRate) return <></>;
        if (payRate.payrollScheme.key == PaySchemeType.MONTHLY)
            return (
                <MonthPickerInput
                    error={form.getInputProps("startDate").error}

                    label={"Временной промежуток"}
                    placeholder={"Выберите временной промежуток"}
                    type={"range"}
                    value={dateRange}
                    onChange={setDateRange}
                    allowSingleDateInRange
                />
            )
        return (<DatePickerInput
            error={form.getInputProps("startDate").error}
            label={"Временной промежуток"}
            placeholder={"Выберите временной промежуток"}
            type={"range"}
            allowSingleDateInRange
            value={dateRange}
            onChange={setDateRange}
        />);
    }
    const getAmountLabel = () => {
        const user = form.values.user;
        if (!user) return "";
        const payRate = user?.payRate;
        if (!payRate) return "";
        if (payRate.payrollScheme.key == PaySchemeType.HOURLY) return "Количество часов";
        if (payRate.payrollScheme.key == PaySchemeType.MONTHLY) return "Количество месяцев";
        if (payRate.payrollScheme.key == PaySchemeType.DAILY) return "Количество дней";
        return "";
    }
    const getAmountPlaceholder = () => {
        return "Укажите " + getAmountLabel().toLowerCase();
    }
    return (<BaseFormModal
        form={form}
        closeOnSubmit
        onClose={() => context.closeContextModal(id)}
        {...innerProps}
    >
        <BaseFormModal.Body>
            <>
                <Flex direction={"column"} gap={rem(10)}>
                    <UserSelect
                        label={"Сотрудник"}
                        placeholder={"Выберите сотрудника"}
                        searchable
                        filterBy={(user) => !!user.payRate}
                        {...form.getInputProps("user")}
                    />

                    {form.values.user &&
                        <>
                            <motion.div

                                initial={{opacity: 0}}
                                animate={{opacity: 1}}
                                transition={{duration: 0.3}}
                            >
                                <Flex
                                    direction={"column"}
                                    gap={rem(10)}>

                                    {getDateRangeInput()}
                                    <NumberInput
                                        label={getAmountLabel()}
                                        placeholder={getAmountPlaceholder()}
                                        hideControls
                                        {...form.getInputProps("workUnits")}
                                    />
                                </Flex>
                            </motion.div>
                        </>
                    }
                </Flex>
            </>
        </BaseFormModal.Body>
    </BaseFormModal>)
}
export default CreatePaymentRecordModal;