import { Popover, Typography } from "@mui/material";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { provinceGetGuildsNumbersNamesService } from "../../services/province-get-guilds-numbers-names";

export const ProvinceGuildsQuantity = ({ item }) => {
  const dispatch = useDispatch();
  const [anchorEl, setAnchorEl] = useState(null);
  const [dataTable, setDataTable] = useState([]);
  const [data, setData] = useState([]);

  useEffect(() => {
    const d = data?.map((item) => {
      return [
        item?.guildsName,
        item?.user?.fullname,
        item?.user?.mobile,
        item?.allocationLimit?.toLocaleString(),
        item?.address?.city?.name,
      ];
    });
    setDataTable(d);
  }, [data]);

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

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

  const open = Boolean(anchorEl);
  const id = open ? item.key : undefined;

  useEffect(() => {
    dispatch(provinceGetGuildsNumbersNamesService({ key: item.key })).then(
      (r) => setData(r.payload.data)
    );
  }, []);

  return (
    <Grid container alignItems="center" justifyContent="center">
      <Typography
        onClick={handleClick}
        variant="caption"
        color="success"
        style={{ cursor: "pointer" }}
      >
        {item.guildsQuantity}
      </Typography>
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <Grid width="500px">
          <SimpleTable
            columns={["نام صنف", "نام", "تلفن", "وزن (کیلوگرم)", "شهر"]}
            data={dataTable}
          />
        </Grid>
      </Popover>
    </Grid>
  );
};
