import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  Button,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  Typography,
} from "@mui/material";
import { useDispatch } from "react-redux";
import {
  provincePolicyDeleteWeightRange,
  provincePolicyGetWeightRange,
} from "../../services/province-policy-get-weight-range";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { ProvincePolicyAddWeightRange } from "../province-policy-add-weight-range/ProvincePolicyAddWeightRange";
import EditIcon from "@mui/icons-material/Edit";
import { AppContext } from "../../../../contexts/AppContext";
import DeleteIcon from "@mui/icons-material/Delete";
import TuneIcon from "@mui/icons-material/Tune";

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

  const [openNotif] = useContext(AppContext);

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

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

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        i + 1,
        item?.fromAge,
        item?.toAge,
        item?.fromWeight,
        item?.toWeight,
        <WeightRangeActions
          key={`actions-${i}`}
          onEdit={() => {
            dispatch(
              OPEN_MODAL({
                title: "ویرایش بازه",
                content: (
                  <ProvincePolicyAddWeightRange
                    fetchData={fetchData}
                    item={item}
                  />
                ),
              })
            );
          }}
          onDelete={() => {
            dispatch(
              OPEN_MODAL({
                title: "آیا مطمئن هستید؟",
                content: (
                  <Grid container spacing={2}>
                    <Grid item>
                      <Button
                        variant="contained"
                        color="error"
                        onClick={() => {
                          dispatch(
                            provincePolicyDeleteWeightRange(item?.id)
                          ).then((r) => {
                            if (r.payload.error) {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: r.payload.error,
                                severity: "error",
                              });
                            } else {
                              fetchData();
                              dispatch(CLOSE_MODAL());
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "عملیات با موفقیت انجام شد.",
                                severity: "success",
                              });
                            }
                          });
                        }}
                      >
                        تایید
                      </Button>
                    </Grid>
                    <Grid item>
                      <Button
                        onClick={() => {
                          dispatch(CLOSE_MODAL());
                        }}
                      >
                        لغو
                      </Button>
                    </Grid>
                  </Grid>
                ),
              })
            );
          }}
        />,
      ];
    });

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

  const WeightRangeActions = ({ onEdit, onDelete }) => {
    const [anchorEl, setAnchorEl] = useState(null);
    const open = Boolean(anchorEl);

    const handleOpen = (event) => {
      setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
      setAnchorEl(null);
    };

    const handleEdit = () => {
      onEdit();
      handleClose();
    };

    const handleDelete = () => {
      onDelete();
      handleClose();
    };

    return (
      <Grid container justifyContent="center">
        <IconButton color="primary" onClick={handleOpen}>
          <TuneIcon />
        </IconButton>
        <Popover
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "right",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
        >
          <List sx={{ minWidth: 150, p: 1 }}>
            <ListItemButton onClick={handleEdit} sx={{ py: 1 }}>
              <ListItemIcon>
                <EditIcon color="primary" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    ویرایش
                  </Typography>
                }
              />
            </ListItemButton>
            <ListItemButton onClick={handleDelete} sx={{ py: 1 }}>
              <ListItemIcon>
                <DeleteIcon color="error" />
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography variant="body2" color="textPrimary">
                    حذف
                  </Typography>
                }
              />
            </ListItemButton>
          </List>
        </Popover>
      </Grid>
    );
  };

  return (
    <Grid container xs={12} justifyContent="start" alignItems="center">
      <Button
        variant="contained"
        color="primary"
        onClick={() => {
          dispatch(
            OPEN_MODAL({
              title: "ایجاد بازه جدید",
              content: <ProvincePolicyAddWeightRange fetchData={fetchData} />,
            })
          );
        }}
      >
        ایجاد بازه جدید
      </Button>

      <ResponsiveTable
        title="بازه وزنی"
        columns={[
          "ردیف",
          "از سن",
          "تا سن",
          "حداقل وزن",
          "حداکثر وزن",
          "عملیات",
        ]}
        data={tableData}
        paginated
      />
    </Grid>
  );
};
