import * as React from "react";
import { useMemo, 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 { faIR } from "@mui/x-date-pickers/locales";
import { useTranslations } from "next-intl";
import moment from "jalali-moment";
import { FormControl, FormHelperText } from "@mui/material";
import { useConfig } from "@witel/webapp-builder";

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 { config } = useConfig();
  const t = useTranslations();
  const [open, setOpen] = useState(false);
  const dateRange = useMemo(() => {
    const today = moment();
    const min = moment(
      `${config.add_request_loan_birthday_range.min}-01-01`,
      "jYYYY-jMM-jDD"
    ).toDate();
    const max = moment(
      `${config.add_request_loan_birthday_range.max}-${today.format(
        "jMM-jDD"
      )}`,
      "jYYYY-jMM-jDD"
    ).toDate();
    return { min, max };
  }, [config.add_request_loan_birthday_range]);

  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")}`
            : 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>
  );
}