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

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", {
                      value: `${props.slotProps.formik.values.person_type === "legal" ? "مدیر عامل" : ""}`,
                  })}: ${label}`
                : `${t("birthday", {
                      value: `${props.slotProps.formik.values.person_type === "legal" ? "مدیر عامل" : ""}`,
                  })}`}
        </Button>
    );
}

function ButtonDatePicker(props) {
    const t = useTranslations();
    const [open, setOpen] = useState(false);
    const dateRange = useMemo(() => {
        const today = moment();
        const min = moment(`${process.env.NEXT_PUBLIC_MIN_BIRTHDAY}-01-01`, "jYYYY-jMM-jDD").toDate();
        const max = moment(
            `${process.env.NEXT_PUBLIC_MAX_BIRTHDAY}-${today.format("jMM-jDD")}`,
            "jYYYY-jMM-jDD"
        ).toDate();
        return { min, max };
    }, []);

    return (
        <DatePicker
            slots={{ field: ButtonField, ...props.slots }}
            disabled={props.disabled}
            slotProps={{
                formik: props.formik,
                field: { setOpen },
                textField: {
                    helperText: props.formik.errors.birthday
                        ? `${t("birthday_error", {
                              value: `${props.formik.values.person_type === "legal" ? "مدیر عامل" : "خود"}`,
                          })}`
                        : null,
                },
            }}
            {...props}
            open={open}
            minDate={dateRange.min}
            maxDate={dateRange.max}
            onClose={() => setOpen(false)}
            onOpen={() => setOpen(true)}
        />
    );
}

export default function PickerWithButtonField({ formik, disabled }) {
    return (
        <FormControl variant={"outlined"} fullWidth size="small" error={true}>
            <LocalizationProvider
                dateAdapter={AdapterDateFnsJalali}
                localeText={{
                    ...faIR.components.MuiLocalizationProvider.defaultProps.localeText,
                    okButtonLabel: "تایید",
                }}
            >
                <ButtonDatePicker
                    label={formik.values.birthday !== "" && formik.values.birthday.locale("fa").format("YYYY/MM/DD")}
                    value={formik.values.birthday !== "" ? formik.values.birthday.toDate() : null}
                    formik={formik}
                    disabled={disabled}
                    onChange={(newValue) => {
                        formik.setFieldValue("birthday", moment(newValue));
                    }}
                />
            </LocalizationProvider>
            <FormHelperText>{formik.touched.birthday && formik.errors.birthday}</FormHelperText>
        </FormControl>
    );
}
