import { Autocomplete, Button, TextField } from "@mui/material";
import { useFormik } from "formik";
import { useContext, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import * as yup from "yup";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { provinceCreateStewardService } from "../../services/province-create-steward";
import { provinceGetGuildsService } from "../../services/province-get-guilds";

const validationSchema = yup.object({
  //   guild: yup.string().required(""),
});

export const CreateStewards = ({ guild }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const { provinceGetGuildsOptions } = useSelector(
    (state) => state.provinceSlice
  );

  useEffect(() => {
    dispatch(provinceGetGuildsService());
  }, []);

  const formik = useFormik({
    initialValues: {
      guild: null,
    },
    validationSchema,
    onSubmit: (values) => {
      // Handle form submission here
      dispatch(
        provinceCreateStewardService({ guilds_key: values.guild.value })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.TINY}>
        <Autocomplete
          style={{ width: "100%" }}
          options={provinceGetGuildsOptions}
          value={formik.values.guild}
          onChange={(e, v) => {
            formik.setFieldValue("guild", v);
          }}
          error={formik.touched.guild && Boolean(formik.errors.guild)}
          helperText={formik.touched.guild && formik.errors.guild}
          getOptionLabel={(option) => option.label}
          renderInput={(params) => (
            <TextField {...params} label="انتخاب صنف" variant="outlined" />
          )}
        />
        <Button color="primary" fullWidth variant="contained" type="submit">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
