import React, { useContext } from "react";
import {
  Grid,
  TextField,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useDispatch } from "react-redux";
import {
  provinceSendReportEditUser,
  provinceSendReportNewUser,
} from "../../services/province-send-report-new-user";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { getRoleList } from "../../../../utils/getRoleList";

export const ProvinceSendReportNewUser = ({ fetchApiData, isEdit, item }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const validationSchema = Yup.object({
    firstname: Yup.string().required("این فیلد اجباری است"),
    lastname: Yup.string().required("این فیلد اجباری است"),
    mobile: Yup.number()
      .required("این فیلد اجباری است!")
      .typeError("لطفا اعداد انگلیسی وارد کنید!")
      .test("len", "شماره تلفن باید 11 رقم باشد!", (val, context) => {
        return context.originalValue && context.originalValue.length === 11;
      }),
    post: Yup.string().required("این فیلد اجباری است"),
    city: Yup.string().required("این فیلد اجباری است"),
  });

  const formik = useFormik({
    initialValues: {
      firstname: item?.firstname ? item?.firstname : "",
      lastname: item?.lastname ? item?.lastname : "",
      mobile: item?.mobile ? item?.mobile : "",
      post: item?.position ? item?.position : "",
      city: item?.city ? item?.city : "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      if (isEdit) {
        dispatch(
          provinceSendReportEditUser({
            user_key: item?.key,
            firstname: values.firstname,
            lastname: values.lastname,
            mobile: values.mobile,
            position: values.post,
            city: values.city,
          })
        ).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",
            });
            dispatch(CLOSE_MODAL());
            fetchApiData(1);
          }
        });
      } else {
        dispatch(
          provinceSendReportNewUser({
            firstname: values.firstname,
            lastname: values.lastname,
            mobile: values.mobile,
            position: values.post,
            city: values.city,
          })
        ).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",
            });
            dispatch(CLOSE_MODAL());
            fetchApiData(1);
          }
        });
      }
    },
  });

  const handleChangePosition = (e) => {
    formik.setFieldValue("post", e.target.value);
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={1}>
      <TextField
        fullWidth
        id="firstname"
        name="firstname"
        label="نام"
        value={formik.values.firstname}
        onChange={formik.handleChange}
        error={formik.touched.firstname && Boolean(formik.errors.firstname)}
        helperText={formik.touched.firstname && formik.errors.firstname}
        onBlur={formik.handleBlur}
      />
      <TextField
        fullWidth
        id="lastname"
        name="lastname"
        label="نام خانوادگی"
        value={formik.values.lastname}
        onChange={formik.handleChange}
        error={formik.touched.lastname && Boolean(formik.errors.lastname)}
        helperText={formik.touched.lastname && formik.errors.lastname}
        onBlur={formik.handleBlur}
      />

      <TextField
        id="mobile"
        label="شماره تلفن"
        variant="outlined"
        sx={{ width: "100%" }}
        value={formik.values.mobile}
        error={formik.touched.mobile ? Boolean(formik.errors.mobile) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.mobile && Boolean(formik.errors.mobile)
            ? formik.errors.mobile
            : null
        }
      />
      <TextField
        id="city"
        label="شهر"
        variant="outlined"
        sx={{ width: "100%" }}
        value={formik.values.city}
        error={formik.touched.city ? Boolean(formik.errors.city) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.city && Boolean(formik.errors.city)
            ? formik.errors.city
            : null
        }
      />

      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">سمت</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          label="سمت"
          value={formik.values.post}
          onChange={handleChangePosition}
        >
          {getRoleList()?.map((item, i) => (
            <MenuItem key={i} value={item?.role}>
              {item?.translation}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

      <Button
        color="primary"
        variant="contained"
        fullWidth
        type="submit"
        onClick={formik.handleSubmit}
      >
        ثبت
      </Button>
    </Grid>
  );
};
