import * as React from 'react';
import {useState} from 'react';
import Button from '@mui/material/Button';
import {AdapterDateFnsJalali} from "@mui/x-date-pickers/AdapterDateFnsJalali";
import {LocalizationProvider} from '@mui/x-date-pickers/LocalizationProvider';
import {DatePicker} from '@mui/x-date-pickers/DatePicker';
import {useTranslations} from "next-intl";
import moment from "jalali-moment";
import {FormControl, FormHelperText} from "@mui/material";

function ButtonField(props) {
    const t = useTranslations();
    const {
        setOpen,
        label,
        id,
        disabled,
        InputProps: {ref} = {},
        inputProps: {'aria-label': ariaLabel} = {},
    } = props;

    return (
        <Button
            sx={{width: "100%", padding: 0.8}}
            variant="outlined"
            color={props.slotProps.formik.touched.birthday && Boolean(props.slotProps.formik.errors.birthday) ? "error" : "primary"}
            id={id}
            disabled={disabled}
            ref={ref}
            aria-label={ariaLabel}
            onClick={() => setOpen?.((prev) => !prev)}
        >
            {label ? `${t("birthday")}: ${label}` : `${t("birthday")}`}
        </Button>
    );
}

function ButtonDatePicker(props) {
    const t = useTranslations();
    const [open, setOpen] = useState(false);

    return (
        <DatePicker
            slots={{field: ButtonField, ...props.slots}}
            disableFuture
            disabled={props.disabled}
            slotProps={{
                formik: props.formik,
                field: {setOpen},
                textField: {
                    helperText: props.formik.errors.birthday ? `${t("birthday_error")}` : null
                }
            }}
            {...props}
            open={open}
            onClose={() => setOpen(false)}
            onOpen={() => setOpen(true)}
        />
    );
}

export default function PickerWithButtonField({formik, disabled}) {
    return (
        <FormControl
            variant={"outlined"}
            fullWidth
            size="small"
            error={true}
        >
            <LocalizationProvider dateAdapter={AdapterDateFnsJalali}>
                <ButtonDatePicker
                    label={formik.values.birthday === "" ? null : formik.values.birthday
                        .locale("fa")
                        .format("YYYY/MM/DD")}
                    value={formik.values.birthday === "" ? null : formik.values.birthday.toDate()}
                    formik={formik}
                    disabled={disabled}
                    onChange={(newValue) => {
                        formik.setFieldValue("birthday", moment(newValue))
                    }}

                />
            </LocalizationProvider>
            <FormHelperText>{formik.touched.birthday && formik.errors.birthday}</FormHelperText>
        </FormControl>
    );
}