import React, { useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { IconButton } from "@mui/material";
import { useDispatch } from "react-redux";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import EditIcon from "@mui/icons-material/Edit";
import { provincePolicyGetWeightCategory } from "../../services/province-policy-get-weight-category";
import { ProvincePolicyEditWeightCategory } from "../province-policy-edit-weight-category/ProvincePolicyEditWeightCategory";

export const ProvincePolicyManageWeightCategory = () => {
  const dispatch = useDispatch();

  const [data, setData] = useState();
  const [tableData, setTableData] = useState();

  const fetchData = () => {
    dispatch(provincePolicyGetWeightCategory()).then((r) => {
      setData(r.payload.data);
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        i + 1,
        item?.name,
        item?.minValue,
        item?.maxValue,
        <Grid
          container
          alignItems="center"
          gap={12}
          justifyContent="center"
          key={i}
        >
          <IconButton
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ویرایش دسته بندی وزنی",
                  content: (
                    <ProvincePolicyEditWeightCategory
                      fetchData={fetchData}
                      item={item}
                    />
                  ),
                })
              );
            }}
          >
            <EditIcon />
          </IconButton>
        </Grid>,
      ];
    });

    setTableData(d);
  }, [data]);

  return (
    <Grid container xs={12} justifyContent="start" alignItems="center">
      <ResponsiveTable
        title="دسته بندی وزنی"
        columns={["ردیف", "نام", "حداقل وزن", "حداکثر وزن", "ویرایش"]}
        data={tableData}
        paginated
      />
    </Grid>
  );
};
