import { yupResolver } from "@hookform/resolvers/yup";
import { Cancel, FilterAlt } from "@mui/icons-material";
import { Box, Button, IconButton, Typography } from "@mui/material";
import { useForm } from "react-hook-form";
import * as Yup from "yup";
import ScrollBox from "../ScrollBox";
import FilterController from "./FilterController";
import FilterControllerWithDependency from "./FilterControllerWithDependency";

const headerSx = {
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  px: 2,
  py: 1,
  backgroundColor: (theme) => theme.palette.primary.main,
  boxShadow:
    "rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px",
  maxWidth: "450px",
};

const headerTitleSx = { display: "flex", alignItems: "center" };
const headerIconSx = { color: "#fff", mr: 1 };
const iconButtonSx = { color: "#fff" };

const formContainerSx = { px: 2, py: 3 };
const footerSx = {
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  pb: 2,
};

const submitButtonSx = {
  px: 8,
  boxShadow:
    "rgba(0, 0, 0, 0.23) 0px 6px 6px, rgba(0, 0, 0, 0.19) 10px 0px 20px",
  backgroundColor: "primary2",
  ":hover": { backgroundColor: "primary2" },
};

const validationSchema = Yup.object({
  activity_date_time: Yup.array()
    .of(Yup.string().nullable())
    .test({
      test(value, ctx) {
        const [start, end] = value || ["", ""];
        if ((start && !end) || (!start && end)) {
          return ctx.createError({ message: "این بخش را تکمیل نمایید" });
        }
        return true;
      },
    }),
});

const FilterDrawer = ({ defaultValues, setFilterData, closeDrawer }) => {
  const {
    control,
    errors,
    reset,
    handleSubmit,
    formState: { isDirty },
  } = useForm({
    defaultValues,
    resolver: yupResolver(
      Yup.object(
        Object.keys(defaultValues).reduce((acc, key) => {
          const initialValue = defaultValues[key];
          if (initialValue.filterMode === "between") {
            acc[key] = Yup.object().shape({
              value: Yup.array()
                .of(Yup.string().nullable())
                .test({
                  test(value, ctx) {
                    const [start, end] = value || ["", ""];
                    if (
                      initialValue.datatype === "numeric" &&
                      parseInt(end, 10) <= parseInt(start, 10)
                    ) {
                      return ctx.createError({
                        message: `مقدار وارده باید بیشتر از (${start}) باشد`,
                      });
                    } else if ((start && !end) || (!start && end)) {
                      return ctx.createError({
                        message: "این بخش را تکمیل نمایید",
                      });
                    }
                    return true;
                  },
                }),
            });
          }
          return acc;
        }, {}),
      ),
    ),
    mode: "all",
  });

  const onSubmit = (data) => {
    setFilterData(data);
    closeDrawer();
  };

  return (
    <>
      <Box sx={headerSx}>
        <Box sx={headerTitleSx}>
          <FilterAlt sx={headerIconSx} />
          <Typography variant="h6" sx={{ color: "#fff" }}>
            فیلتر
          </Typography>
        </Box>
        <IconButton sx={iconButtonSx} onClick={closeDrawer}>
          <Cancel sx={{ fontSize: "1em" }} />
        </IconButton>
      </Box>
      <ScrollBox>
        <form onSubmit={handleSubmit(onSubmit)}>
          <Box sx={formContainerSx}>
            {Object.values(defaultValues).map(
              (item) =>
                item.enable &&
                (item.dependencyId ? (
                  <FilterControllerWithDependency
                    key={item.id}
                    item={item}
                    control={control}
                    errors={errors}
                    reset={reset}
                  />
                ) : (
                  <FilterController
                    key={item.id}
                    item={item}
                    control={control}
                    errors={errors}
                    reset={reset}
                  />
                )),
            )}

            <Box sx={footerSx}>
              <Button
                type="submit"
                variant="contained"
                size="large"
                disabled={!isDirty}
                sx={submitButtonSx}
              >
                اعمال فیلتر
              </Button>
            </Box>
          </Box>
        </form>
      </ScrollBox>
    </>
  );
};
export default FilterDrawer;
