import React, { FC, useState, useEffect } from "react";
import moment from "moment";
import cx from 'classnames';

import './style.scss'
import { Icons } from "../../../Icons";
import { PillsGroup } from "../../../Pill";
import { Select } from "../../../Select";

export interface TimePickersInputsProps {
    date: moment.Moment | undefined,
    withIcon?: boolean,
    onChange: (timeMoment: moment.Moment) => void
}

const AmPmOptions = [
    {id: "AM", label: "AM"},
    {id: "PM", label: "PM"}
]

const TimePickerInputsModal: FC<TimePickersInputsProps> = ({
    date,
    withIcon = false, 
    onChange
}) => {


    const [hourValue, setHourValue] = useState<number>(parseInt(moment(date).format("HH")))
    const [minuteValue, setMinuteValue] = useState<number>(parseInt(moment(date).format("mm")))
    const [AmPm, setAmPm] = useState<string>(moment(date).format("A"))
    const [selectedPills, setSelectedPills] = useState([AmPmOptions[0]])

    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 handleHourChange = (hourTemp: number) => {
        let hour = hourTemp;

        if( Number.isNaN(hour)){
            setHourValue(0)
            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 hour24 = handle24h(hour, AmPm)
        const newMoment = moment().set({
            'hour': hour24, 
            'minute': minuteValue,
        })
        onChange && onChange(newMoment)
    }

    const handleMinuteChange = (minuteTemp: number) => {
        let minute = Number.isNaN(minuteTemp) ? 0 : minuteTemp;
        if (minute < 0) {
            minute = 0;
        }
        if (minute > 59){
            minute = 59;
        }
        setMinuteValue(minute)
        const hour24 = handle24h(hourValue, AmPm)
        const newMoment = moment().set({
            'hour': hour24, 
            'minute': minute,
        })
        onChange && onChange(newMoment)
    }

    const handlePeriodChange = (period: string) => {
        if (period === "AM"){
            setAmPm("AM")
        } else {
            setAmPm("PM")
        }
        const hour24 = handle24h(hourValue, period)
        const newMoment = moment().set({
            'hour': hour24, 
            'minute': minuteValue,
        })
        onChange && onChange(newMoment)
    }

    useEffect(() => {
        if (date){
            setHourValue(parseInt(date.format("hh")))
            setMinuteValue(parseInt(date.format("mm")))
            setAmPm(date.format("A"))
            setSelectedPills([{id: date.format("A"), label: date.format("A")}])

        }
    }, [date]) 

    return (
        <div className={cx("gtc-rc-timePicker-range-modal-inputs-wrap")} data-testid="gtc-rc-timePicker">
            {withIcon &&
                <Icons  style={{paddingRight: "5px"}}  name={"access_time"} size="large" />
            }
            <input 
                min={0}
                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))}
            />
            <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))}
            />
            { !withIcon && 
                <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}
                />
            }

            {withIcon && 
                <div style={{paddingLeft: "3px"}}>
                    <PillsGroup 
                        options={AmPmOptions}
                        values={selectedPills} 
                        onChange={(selected) => {
                            handlePeriodChange(selected[0].id)
                            setSelectedPills(selected)
                        }} 
                    />
                </div>
            }
        </div>
    )
}



export default TimePickerInputsModal