import React, { useContext, useEffect, useState } from "react";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { Grid } from "../../../../components/grid/Grid";
import {
  Autocomplete,
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import {
  getTicketPermission,
  getTicketUsersFromRole,
} from "../../services/get-ticket-permission";
import { useDispatch } from "react-redux";
import { EditTicketService } from "../../services/create-ticket";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { sortRoles } from "../../../../utils/sortRoles";

export const SubmitRefferTicket = ({ fetchMessages, ticket }) => {
  const [role] = useUserProfile();
  const [openNotif] = useContext(AppContext);
  const [users, setUsers] = useState([]);
  const dispatch = useDispatch();

  const formik = useFormik({
    initialValues: {
      users: "",
      roles: [],
    },
    validationSchema: Yup.object({
      users: Yup.array().required("حداقل یک کاربر انتخاب کنید!"),
    }),
    onSubmit: (values) => {
      // console.log(values);
    },
  });

  const [permissionList, setPermissionList] = useState([]);

  useEffect(() => {
    dispatch(getTicketPermission({ role: sortRoles(role)[0] })).then((r) => {
      setPermissionList(r.payload.data);
    });
  }, []);

  useEffect(() => {
    if (formik.values.roles.length) {
      dispatch(getTicketUsersFromRole({ role: formik.values.roles })).then(
        (r) => {
          setUsers(r.payload.data);
        }
      );
    }
  }, [formik.values.roles]);

  useEffect(() => {
    formik.validateForm();
  }, [dispatch]);

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      gap={2}
      direction="column"
    >
      <Grid item xs={12}>
        {permissionList?.roles?.length ? (
          <Grid item xs={12}>
            <FormControl fullWidth>
              <InputLabel id="role-select-label">انتخاب نقش</InputLabel>
              <Select
                labelId="role-select-label"
                value={formik.values.roles}
                onChange={(event) => {
                  formik.setFieldValue("roles", event.target.value);
                }}
                fullWidth
              >
                {permissionList?.roles.map((roleItem, i) => (
                  <MenuItem key={i} value={roleItem}>
                    {getFaUserRole(roleItem)}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
        ) : (
          <Typography variant="body1" color="error">
            نقش انتخابی اجازه ارسال تیکت ندارد!
          </Typography>
        )}
      </Grid>

      <Grid xs={12}>
        {users?.length ? (
          <Grid item xs={12}>
            <Autocomplete
              multiple
              id="tags-standard"
              options={users}
              getOptionLabel={(option) =>
                `${option.fullname || "-"} (${option.mobile})`
              }
              onChange={(event, value) => {
                formik.setFieldValue("users", value);
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  variant="outlined"
                  label="انتخاب کاربر"
                />
              )}
            />
          </Grid>
        ) : (
          <Typography color="error" variant="body2">
            موردی یافت نشد!
          </Typography>
        )}
      </Grid>
      <Button
        disabled={!formik.isValid}
        fullWidth
        variant="contained"
        onClick={() => {
          dispatch(
            EditTicketService({
              ticket: ticket,
              referred_to: formik.values.users.map((item) => {
                return item?.key;
              }),
            })
          ).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              fetchMessages();
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
              dispatch(CLOSE_MODAL());
            }
          });
        }}
      >
        ارجاع
      </Button>
    </Grid>
  );
};
