import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
} from "@mui/material";
import {
  provinceSendReportGetReports,
  provinceSendReportSubmitReport,
} from "../../services/province-send-report-get-times";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ProvinceSendReportNewReport = ({ fetchApiData }) => {
  const [report, setReport] = useState([]);
  const [allReports, setAllReports] = useState();

  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();

  const handleChangeReport = (event) => {
    const {
      target: { value },
    } = event;
    setReport(typeof value === "string" ? value.split(",") : value);
  };

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

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">گزارش</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          label="گزارش"
          value={report}
          onChange={handleChangeReport}
          multiple
        >
          {allReports?.map((item, i) => (
            <MenuItem key={i} value={item?.key}>
              {item?.title}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
      <Button
        variant="contained"
        fullWidth
        disabled={!report?.length}
        onClick={() => {
          dispatch(
            provinceSendReportSubmitReport({
              reports_list: report,
            })
          ).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
              fetchApiData(1);
              dispatch(CLOSE_MODAL());
            }
          });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
