import { useState, useRef } from "react";
import { Popper, ClickAwayListener, Paper } from "@mui/material";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DateCalendar } from "@mui/x-date-pickers/DateCalendar";
import dayjs from "dayjs";
import Textbox from "../Textbox/Textbox";

export interface TextDateProps {
    placeholder?: string;
    selectedDate?: dayjs.Dayjs;
    onChange?: (newValue: dayjs.Dayjs) => void;
}

export default function TextDate(props: TextDateProps) {
    const { placeholder, selectedDate } = props;
    const [value, setValue] = useState<dayjs.Dayjs>(selectedDate ? selectedDate : dayjs());
    const [open, setOpen] = useState(false);
    const anchorRef = useRef(null);

    const handleSelect = (newValue: dayjs.Dayjs) => {
        setValue(newValue);
        if (props.onChange) {
            props.onChange(newValue);
        }
        setOpen(false);
    };

    return (
        <LocalizationProvider dateAdapter={AdapterDayjs}>
            <div className="flex flex-col items-start gap-2 p-4">
                <Textbox
                    type="text"
                    width="100%"
                    placeholder={placeholder}
                    value={value ? value.format("YYYY-MM-DD") : ""}
                    onChange={() => {
                        console.log("ha cambiado");
                    }}
                    ref={anchorRef}
                    onClick={() => setOpen(true)}
                />

                <Popper
                    open={open}
                    anchorEl={anchorRef.current}
                    placement="bottom-start"
                    style={{ zIndex: 9999 }}
                >
                    <ClickAwayListener onClickAway={() => setOpen(false)}>
                        <Paper className="p-2 rounded-2xl shadow-xl">
                            <DateCalendar value={value} onChange={handleSelect} />
                        </Paper>
                    </ClickAwayListener>
                </Popper>
            </div>
        </LocalizationProvider>
    );
}
