import { ChangeEvent, useEffect, useState } from "react";

import {
    getDefaultDataConfig, getDaysInMonth,
    getCorrectFebruaryDay, FEBRUARY_MONTH_FORMAT,
    parseTimestemp
} from "../../helpers/functions/get_data_config";
import moment from "moment";

interface ValueProps {
    value: number | string,
    displayValue: number | string
}

export const useDateOfBirth = (date: number, onDateChanged: (x: number | null) => {}, monthsTranslated?: string[]) => {
    const { months, years, defaultDays } = getDefaultDataConfig(monthsTranslated);
    const [days, setDays] = useState(defaultDays);
    const [day, setDay] = useState<ValueProps>()
    const [month, setMonth] = useState<ValueProps>();
    const [year, setYear] = useState<ValueProps>();

    const handleChooseDay = (e: ChangeEvent<HTMLSelectElement>) => {
        const value = days.find(({ value }: ValueProps) => value.toString() === e.target.value);

        setDay(value);
    }

    const handleChooseMonth = ({ target: { value: val } }: ChangeEvent<HTMLSelectElement>) => {
        const value = months.find(({ value }: ValueProps) => value.toString() === val);

        setMonth(value);

        const newDays = getDaysInMonth(val, year?.value);

        if(newDays.length !== days.length) {
            setDays(newDays);

            if(val === FEBRUARY_MONTH_FORMAT && day) {
                const febDay = getCorrectFebruaryDay(day.value, year?.value);

                setDay(febDay)
            }
        }
    }

    const handleChooseYear = ({ target: { value: val } }: ChangeEvent<HTMLSelectElement>) => {
        const value = years.find(({ value }: ValueProps) => value.toString() === val);

        if(month?.value.toString() === FEBRUARY_MONTH_FORMAT) {
            const newDays = getDaysInMonth(FEBRUARY_MONTH_FORMAT, val);

            if(newDays.length !== days.length) {
                setDays(newDays);
                if(day && newDays.length < day.value){
                    setDay(newDays[newDays.length-1])
                }
            }
        }

        setYear(value);
    };

    useEffect(() => {
        if(date) {
            const { day, month, year } = parseTimestemp(date);

            setDay({ value: day, displayValue: day });
            setMonth({ value: month, displayValue: month });
            setYear({ value: year, displayValue: year });
        }
    }, []);

    useEffect(() => {
        if(!day || !month || !year) {
            onDateChanged(null);

            return;
        }

        const unixDate = moment.utc(`${month?.value}/${day?.value}/${year?.value}`);

        if(onDateChanged) {
            onDateChanged(Number(unixDate));
        }
    }, [year, day, month]);

    return {
        year,
        month,
        day,
        years,
        months,
        days,
        handleChooseDay,
        handleChooseMonth,
        handleChooseYear
    }
}
