import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getRoleList } from "../../../../utils/getRoleList";
import { useDispatch } from "react-redux";
import { provincePolicyGetTicketPermissions } from "../../services/province-policy-get-ticket-permissions";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import {
  FormControl,
  IconButton,
  InputLabel,
  MenuItem,
  Select,
} from "@mui/material";
import CheckIcon from "@mui/icons-material/Check";
import SaveIcon from "@mui/icons-material/Save";
import { AppContext } from "../../../../contexts/AppContext";
import { provincePolicySubmitTicketPermission } from "../../services/province-policy-submit-ticket-permission";

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

  const [openNotif] = useContext(AppContext);

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

  useEffect(() => {
    dispatch(provincePolicyGetTicketPermissions()).then((r) => {
      setData(r.payload.data);
    });
  }, []);

  const handleChangeRoles = (event, i) => {
    const {
      target: { value },
    } = event;

    const updatedData = [...data];
    updatedData[i] = {
      ...updatedData[i],
      roles: typeof value === "string" ? value.split(",") : value,
    };

    setData(updatedData);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        i + 1,
        getFaUserRole(item?.role) !== "نامشخص"
          ? getFaUserRole(item?.role)
          : item?.role,
        <Grid
          key={i}
          container
          justifyContent="center"
          style={{ margin: "3px" }}
        >
          <FormControl fullWidth>
            <InputLabel id="demo-simple-select-label">
              مجوز ارسال تیکت
            </InputLabel>
            <Select
              size="small"
              sx={{ width: { xs: "110px", sm: "220px" } }}
              labelId="demo-simple-select-label"
              label="مجوز ارسال تیکت"
              value={item?.roles}
              onChange={(event) => handleChangeRoles(event, i)}
              multiple
              renderValue={(selected) =>
                selected.map((option) => getFaUserRole(option)).join(", ")
              }
            >
              {getRoleList()?.map((roleItem, i) => (
                <MenuItem key={i} value={roleItem.role} alignItems="center">
                  {item?.roles.includes(roleItem.role) && (
                    <CheckIcon sx={{ marginRight: "8px", color: "#00796b" }} />
                  )}
                  {roleItem.translation}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>,
        <IconButton
          key={i}
          color="primary"
          onClick={() => {
            dispatch(
              provincePolicySubmitTicketPermission({
                roles: item?.roles,
                role: item?.role,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
                return;
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          <SaveIcon />
        </IconButton>,
      ];
    });

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

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" mb={2}>
      <ResponsiveTable
        paginated
        title="اجازه ثبت تیکت"
        columns={["ردیف", "نقش", "مجوز ارسال", "ثبت"]}
        data={tableData}
        customColors={[
          { name: "ردیف", color: "#74b9ff" },
          { name: "نقش", color: "#81ecec" },
          { name: "مجوز ارسال", color: "#636e72", text: "white" },
        ]}
      />
    </Grid>
  );
};
