"use client";

import FilterBodyControllerWithDependency from "@/core/components/DataTable/filter/FilterBodyControllerWithDependency";
import FilterHeader from "@/core/components/DataTable/filter/FilterHeader";
import useDataTable from "@/lib/hooks/useDataTable";
import { yupResolver } from "@hookform/resolvers/yup";
import { Box, Button } from "@mui/material";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import * as Yup from "yup";
import ScrollBox from "../../ScrollBox";
import FilterBodyController from "./FilterBodyController";

function FilterBody({ columns, drawerState, setDrawerState }) {
  const { filterData, setFilterData } = useDataTable();
  const [validationSchema, setValidationSchema] = useState(Yup.object({}));

  console.log(filterData);

  useEffect(() => {
    const schema = Yup.object(
      Object.keys(filterData).reduce((acc, key) => {
        const initialValue = filterData[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;
      }, {}),
    );

    setValidationSchema(schema);
  }, [filterData]);

  const {
    handleSubmit,
    control,
    reset,
    formState: { errors, isDirty, isValid },
  } = useForm({
    defaultValues: filterData,
    resolver: yupResolver(validationSchema),
    mode: "all",
  });

  const onSubmit = (data) => {
    setDrawerState(false);
    setFilterData(data);
  };

  return (
    <>
      <FilterHeader setDrawerState={setDrawerState} />
      {Object.keys(filterData).length > 0 && (
        <ScrollBox>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Box sx={{ px: 2, py: 3 }}>
              {columns.map((column) =>
                column.enableColumnFilter ? (
                  column.dependencyId ? (
                    <FilterBodyControllerWithDependency
                      key={column.id}
                      column={column}
                      control={control}
                      errors={errors}
                      reset={reset}
                    />
                  ) : (
                    <FilterBodyController
                      key={column.id}
                      column={column}
                      control={control}
                      errors={errors}
                      reset={reset}
                    />
                  )
                ) : null,
              )}
            </Box>
            <Box
              sx={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                pb: 2,
              }}
            >
              <Button
                type="submit"
                variant="contained"
                size="large"
                disabled={!isDirty || !isValid}
                sx={{
                  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",
                  },
                }}
              >
                اعمال فیلتر
              </Button>
            </Box>
          </form>
        </ScrollBox>
      )}
    </>
  );
}

export default FilterBody;
