import React, { FC, useState, useEffect } from "react";
import moment from "moment";
import cx from 'classnames';
import { Select } from "../../Select";
import './style.scss'
import { Label } from "../../Label";

export interface TimePickersInputsProps {
    /**Label to be displayed above to the input. if empty, input is displayed with out label. */
    label?: string,
    /**Time that is display by the input time component*/
    value?: moment.Moment | undefined,
    /**Action taken when the time changes */
    onChange?: (timeMoment: moment.Moment) => void
    /**Extra style to add by props. */
    style?: React.CSSProperties,
    /**Name of class to extend css properties of the input*/
    className?: string,
    /**Name of class to extend css properties of the label*/
    labelClassName?: string,
    /**If true, the component does not allow changes to time */
    isDisabled?: boolean,
}

export const TimePickerInputs: FC<TimePickersInputsProps> = ({
    label,
    value,
    onChange,
    style,
    className,
    labelClassName,
    isDisabled,
}) => {

    const [hourValue, setHourValue] = useState<number>(value ? parseInt(moment(value).format("hh")) : 12)
    const [minuteValue, setMinuteValue] = useState<number>(value ? parseInt(moment(value).format("mm")): 0)
    const [AmPm, setAmPm] = useState<string>(value ? moment(value).format("A") : "AM")

    const handle24h = (hour: number, period: string) => {
        let hour24 = 0;
        if(period === "AM"){
            if(hour == 12){
               hour24 = 0
            }else{
               hour24 = hour
            }
       } else {
           if(hour == 12){
               hour24 = 12
            }else{
               hour24 = +hour + 12      //without + -> it takes hour as string even though it is set as number
            }
       }
       return hour24
    }

    const handleOnChange = () => {
        onChange && onChange(moment(value).set({
            'hour': handle24h(hourValue, AmPm), 
            'minute': minuteValue,
        }))
    }

    const handleHourChange = (hourTemp: number) => {
        let hour = hourTemp;
        if( Number.isNaN(hour)){
            setHourValue(12)
            return
        }
        if (hour <= 0) {hour = 12}
        if (hour >= 12 && (AmPm === "AM")){hour = 12}
        if (hour > 12 && (AmPm === "PM")){hour = 11}
        if (hour == 0 && (AmPm === "PM")){hour = 12}
        setHourValue(hour)
    }

    const handleMinuteChange = (minuteTemp: number) => {
        let minute = Number.isNaN(minuteTemp) ? 0 : minuteTemp;
        if (minute < 0) {
            minute = 0;
        }
        if (minute > 59){
            minute = 59;
        }
        setMinuteValue(minute)
    }

    const handlePeriodChange = (period: string) => {
        if (period === "AM"){
            setAmPm("AM")
        } else {
            setAmPm("PM")
        }
    }

    useEffect(() => {
        if (value){
            setHourValue(parseInt(value.format("hh")))
            setMinuteValue(parseInt(value.format("mm")))
            setAmPm(value.format("A"))
        }
    }, [value]) 

    useEffect(() => {
        const delayHourTimeoutId = setTimeout(() => {
            handleOnChange()
        }, 500);
        return () => clearTimeout(delayHourTimeoutId);
    }, [hourValue, 500]);

    useEffect(() => {
        const delayMinuteTimeoutId = setTimeout(() => {
            handleOnChange()
        }, 500);
        return () => clearTimeout(delayMinuteTimeoutId);
    }, [minuteValue, 500]);

    useEffect(() => {
        handleOnChange()
    }, [AmPm]);

    return (
        <div>
            { label &&
                <Label className={labelClassName}>
                    {label}
                </Label>
            }
            <div className={cx("gtc-rc-timePicker-inputs-wrap", isDisabled && "gtc-rc-timePicker-inputs-disabled", className)} style={style} data-testid="gtc-rc-timePicker">
                <input
                    min={1}
                    max={12}
                    step={1}
                    className="timePicker-inputs-time" 
                    type="number" 
                    value={hourValue.toLocaleString('en-US', {minimumIntegerDigits: 1,useGrouping: false})} 
                    onChange={event => handleHourChange(parseInt(event.target.value))}
                    onMouseUp={e=>e.preventDefault()}
                    onFocus={(event) => event.target.select()}
                    disabled={isDisabled}
                />
                <label className="timePicker-inputs-label">
                    :
                </label>
                <input 
                    min={0}
                    max={59}
                    step={1}
                    className="timePicker-inputs-time"  
                    type="number" 
                    value={minuteValue.toLocaleString('en-US', {minimumIntegerDigits: 2,useGrouping: false})} 
                    onChange={event => handleMinuteChange(parseInt(event.target.value))}
                    onMouseUp={e=>e.preventDefault()}
                    onFocus={(event) => event.target.select()}
                    disabled={isDisabled}
                />
                <Select
                    className="timePicker-inputs-AmPmSelect"
                    name="AMPM"
                    value={AmPm == "PM" ? { id: "PM", label: "PM" } : { id: "AM", label: "AM" }}
                    onChange={(value) => {
                        handlePeriodChange(value.id)
                    }}
                    options={[{ id: "AM", label: "AM" }, { id: "PM", label: "PM" }]}
                    textField={'label'}
                    valueField={'id'}
                    onSelectAll={() => {}}
                    hasDropdownIcon={false}
                    isDisabled={isDisabled}
                />
            </div>
        </div>
    )
}
