import React, { FC, useRef, useState, useEffect } from "react";
import Datepicker, { registerLocale } from "react-datepicker"
import { useCurrentLang } from "../../../hooks/useLocale";
import moment from "moment";
import { Icons } from "../../Icons";
import { DataPickerProps } from "./DatePicker.types";
import { TimePicker } from "../TimePicker"
import { Button } from "../../Button";
import cx from 'classnames';


import AreaMenu, { Area, Menu } from '../../AreaMenu';

import '../style.scss'
import "react-datepicker/dist/react-datepicker.css"

//react-datepicker change useIntl() (locale) for date-fns and need to register
import en from 'date-fns/locale/en-US';
import es from 'date-fns/locale/es';


registerLocale('en', en);
registerLocale('es', es);

export const DatePicker: FC<DataPickerProps> = ({
    id,
    value = "",
    placeholder = "",
    format = 'MMMM DD, YYYY',
    timeZone = 0,                   //<---- need to use, how?
    showButtons = true,
    maxDate = "",
    minDate = "",
    showTimePicker = false,
    style = {},
    className = "",
    calendarPosition = "bottom",
    isDisabled = false,
    onChange,
    isClearable = false
}) => {
    const locale = useCurrentLang()
    const [dateValue, setDateValue] = useState(value && moment(value) || null)
    const [prevDateValue, setPrevDateValue] = useState(value && moment(value) || null)
    const areaMenuRef = useRef<any>()

    let inputSize = { minWidth: "150px" }
    const widthButtons = isClearable ? '75px' : '111px'

    if (showTimePicker) {
        format = format + " hh:mm A"
        inputSize = { minWidth: "212px" }
    }

    useEffect(() => {
        if (value) {
            setDateValue(moment(value));
        }
    }, [value]);

    const handleTimeChange = (datetime: any, momentTime: any) => {
        if (dateValue) {
            let tempDate = dateValue?.clone();

            tempDate?.set({
                'hour': momentTime.hours(),
                'minute': momentTime.minutes()
            });

            // if (maxDate) {
            //     const newMaxDate = moment(maxDate);
            //     if (tempDate > newMaxDate) {
            //         tempDate = newMaxDate?.clone();
            //     } 
            // }

            // if (minDate) {
            //     const newMinDate = moment(minDate);
            //     if (tempDate < newMinDate) {
            //         tempDate = newMinDate?.clone();
            //     } 
            // }

            setDateValue(tempDate);
        }
    }

    const saveInfoOnClose = () => {
        if (dateValue) {
            setPrevDateValue(dateValue);
            onChange && onChange(dateValue?.toDate(), dateValue);
        }
    }

    function capitalize(str: string | undefined) {
        if (str)
            return (str.charAt(0).toUpperCase() + str.slice(1)).replace('.', '');
    }

    return (
        <AreaMenu
            id={id || "datepicker"}
            menuPlacement={calendarPosition}
            ref={areaMenuRef}
        >
            <Area>
                <div className={cx("gtc-rc-datepicker_area", className)} style={{ ...inputSize, ...style }}>
                    <input
                        style={{ ...inputSize, ...style }}
                        className={cx("gtc-rc-datepicker_input", isDisabled && "gtc-rc-datepicker_input_disabled")}
                        value={dateValue ? capitalize(dateValue.locale(locale).format(format)) : ""} //charAt & slice to capitalize
                        placeholder={placeholder}
                        readOnly
                        spellCheck={false}
                        data-testid="datepickerInput"
                        disabled={isDisabled}
                    />
                    <Icons className="gtc-rc-datepicker_icon" name={"calendar_month"} size="small" />
                </div>
            </Area>
            <Menu>
                <div className="gtc-rc-datepicker_menu" style={{ "minWidth": "250px" }} data-testid="datepickerTooltip">
                    <Datepicker
                        selected={dateValue?.toDate()}
                        onChange={(selectedDate) => {
                            setDateValue(moment(selectedDate))
                            if (!showButtons && !showTimePicker) {
                                onChange && onChange(selectedDate, moment(selectedDate))
                                areaMenuRef.current?.close()
                            }
                        }}
                        inline
                        disabledKeyboardNavigation
                        maxDate={maxDate ? new Date(maxDate) : undefined}
                        minDate={minDate ? new Date(minDate) : undefined}
                        locale={locale}
                    />
                    <>
                        {showTimePicker &&
                            <div className="gtc-rc-datepicker_buttons_container">
                                <TimePicker
                                    variant="inputs"
                                    value={dateValue}
                                    maxDate={maxDate || undefined}
                                    minDate={minDate || undefined}
                                    onChange={handleTimeChange}
                                />
                            </div>
                        }
                        {
                            showButtons &&
                            <div className="gtc-rc-datepicker_buttons_container">
                                <Button
                                    style={{ width: widthButtons, height: "30px" }}
                                    size="small"
                                    variant="secondary"
                                    onClick={() => {
                                        if (prevDateValue) {
                                            setDateValue(moment(prevDateValue))        // cancel resets value to previous
                                        }
                                        areaMenuRef.current?.close()
                                    }}
                                >
                                    cancel
                                </Button>
                                {
                                    isClearable &&
                                    <Button
                                        style={{ width: widthButtons, height: "30px" }}
                                        size="small"
                                        variant="secondary"
                                        onClick={() => {
                                            setDateValue(null)
                                            onChange && onChange(null, moment(null));
                                            areaMenuRef.current?.close()
                                        }}
                                    >
                                        clear
                                    </Button>
                                }
                                <Button
                                    style={{ width: widthButtons, height: "30px" }}
                                    size="small"
                                    variant="primary"
                                    onClick={() => {
                                        saveInfoOnClose()
                                        areaMenuRef.current?.close()
                                    }}
                                >
                                    apply
                                </Button>
                            </div>
                        }
                    </>
                </div>
            </Menu>
        </AreaMenu>
    )
}

//export default DatePicker