import React, { useContext } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { useDispatch } from "react-redux";
import { Button, TextField } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import {
  slaughterSubmitRepresentativeService,
  slaughterEditRepresentativeService,
} from "../../services/slaughter-submit-delegate";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

const getValidationSchema = () =>
  yup.object({
    first_name: yup.string().required("نام الزامی است"),
    last_name: yup.string().required("نام خانوادگی الزامی است"),
    mobile: yup
      .string()
      .required("شماره همراه الزامی است")
      .matches(/^09\d{9}$/, "شماره تلفن باید با 09 شروع شود و 11 رقم باشد"),
    city: yup.string().required("شهر الزامی است"),
  });

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

  const formik = useFormik({
    initialValues: {
      first_name: item?.first_name || item?.firstName || "",
      last_name: item?.last_name || item?.lastName || "",
      mobile: item?.mobile || "",
      city: item?.city || "",
    },
    enableReinitialize: true,
    validationSchema: getValidationSchema(),
    onSubmit: (values) => {
      const submitData = isEdit
        ? {
            key: item?.key,
            first_name: values.first_name,
            last_name: values.last_name,
            mobile: values.mobile,
            city: values.city,
          }
        : {
            first_name: values.first_name,
            last_name: values.last_name,
            mobile: values.mobile,
            city: values.city,
            role: getRoleFromUrl(),
          };

      const service = isEdit
        ? slaughterEditRepresentativeService
        : slaughterSubmitRepresentativeService;

      dispatch(service(submitData)).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",
          });
          if (updateTable) {
            updateTable();
          }
          dispatch(CLOSE_MODAL());
        }
      });
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.SMALL} p={2}>
        <Grid item xs={12}>
          <TextField
            label="نام"
            variant="outlined"
            fullWidth
            id="first_name"
            name="first_name"
            value={formik.values.first_name}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.first_name && Boolean(formik.errors.first_name)
            }
            helperText={formik.touched.first_name && formik.errors.first_name}
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            label="نام خانوادگی"
            variant="outlined"
            fullWidth
            id="last_name"
            name="last_name"
            value={formik.values.last_name}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.last_name && Boolean(formik.errors.last_name)}
            helperText={formik.touched.last_name && formik.errors.last_name}
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            label="شماره همراه"
            variant="outlined"
            fullWidth
            id="mobile"
            name="mobile"
            value={formik.values.mobile}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.mobile && Boolean(formik.errors.mobile)}
            helperText={formik.touched.mobile && formik.errors.mobile}
            inputProps={{ maxLength: 11 }}
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            label="شهر"
            variant="outlined"
            fullWidth
            id="city"
            name="city"
            value={formik.values.city}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.city && Boolean(formik.errors.city)}
            helperText={formik.touched.city && formik.errors.city}
          />
        </Grid>

        <Grid item xs={12} mt={2}>
          <Button
            type="submit"
            variant="contained"
            color="primary"
            fullWidth
            disabled={!formik.isValid}
          >
            {isEdit ? "ویرایش" : "ثبت"}
          </Button>
        </Grid>
      </Grid>
    </form>
  );
};
