import React from "react"
import { BodyInputDate, BodyInputDateField } from "./style";

export interface DateEditorProps {
    value: Date,
    format?: string,
    onChange: (value: Date) => void,
    onEditting: (editting: boolean) => void,
}

export const DateEditor: React.FC<DateEditorProps> = ({ value, format, onChange, onEditting }) => {
    const open = React.useRef(false);

    const handleChange = (event: any) => {
        const val = event
            ? new Date(event.getUTCFullYear(), event.getUTCMonth(), event.getUTCDate())
            : null;

        if (val) {
            setTimeout(() => onEditting(false), 250);
        }
        onChange(val as any)
    }

    return (
        <BodyInputDate
            inputFormat={format ? format : 'yyyy-MM-dd'}
            value={value ? value : null}
            renderInput={
                (params) => (
                    <BodyInputDateField
                        focused
                        {...params}
                        variant="standard"
                        onBlur={() => setTimeout(() => !open.current && onEditting(false), 250)}
                        InputProps={{ ...params.InputProps, autoFocus: true }}
                    />
                )
            }
            open={open.current}
            onOpen={() => { open.current = true }}
            onClose={() => { open.current = false }}
            onChange={handleChange} />
    )
}