import {useEffect, useState} from "react";

import { TimeOfBirthType, PM_TIME, AM_TIME } from "./";

import {
    parseTimestempHours,
    paresHoursToTimestempWithDate,
    parseHoursToTimestemp
} from "../../helpers/functions/get_data_config";

export const useTimeOfBirth = ({ onTimeChanged, dateOfBirth }: TimeOfBirthType) => {
    const [hours, setHours] = useState('');
    const [minutes, setMinutes] = useState('');
    const [time, setTime] = useState('');
    const [error, setError] = useState({
        hours: true,
        minutes: true
    })

    const handleChangeHours = ({ target: { value } }: any) => {
        setHours(value);
    }

    const handleChangeMinutes = ({ target: { value } }: any) => {
        setMinutes(value);
    }

    const choosePmTime = () => {
        const newTime = time === PM_TIME ? '' : PM_TIME;

        setTime(newTime);
    }

    const chooseAmTime = () => {
        const newTime = time === AM_TIME ? '' : AM_TIME;

        setTime(newTime);
    }

    const handleMinuteError = (err: any) => {
        setError({
            ...error,
            minutes: err
        })
    }

    const handleHoursError = (err: any) => {
        setError({
            ...error,
            hours: err
        })
    }

    useEffect(() => {
        if(dateOfBirth) {
            const { hours, minutes, time } =  parseTimestempHours(dateOfBirth);
            console.log(time)
            const isHours = hours !== undefined;
            const isMinutes = minutes !== undefined;

            if(isHours) {
                setHours(hours);
            }

            if(isMinutes) {
                setMinutes(minutes);
            }

            setError({
                hours: !isHours,
                minutes: !isMinutes
            })

            if(time) {
                setTime(time);
            }
        }
    }, [])

    useEffect(() => {
        const isError = Object.values(error).some((err: boolean) => err);
        const isInvalid = isError || !hours || !minutes || !time
        if (isInvalid) {
            onTimeChanged(null);

            return;
        }

        const timestemp = dateOfBirth
            ? paresHoursToTimestempWithDate({ dateOfBirth, hours, minutes, time })
            : parseHoursToTimestemp({ hours, minutes, time });

        onTimeChanged(Number(timestemp));

    }, [hours, minutes, time]);

    return {
        handleChangeHours,
        handleChangeMinutes,
        choosePmTime,
        chooseAmTime,
        hours,
        minutes,
        time,
        handleMinuteError,
        handleHoursError
    }
}