import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import {
  provinceDispensersAddSteward,
  provinceDispensersGetAllStewards,
} from "../../services/province-dispensers-services";
import {
  Autocomplete,
  Button,
  FormControl,
  FormControlLabel,
  FormLabel,
  Radio,
  RadioGroup,
  TextField,
} from "@mui/material";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ProvinceAllocateStewardGuild = ({
  killHousekey,
  updateTable,
  type,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [stewardsOptions, setStewardsOptions] = useState([]);

  const [value, setValue] = useState("forced");
  const [userType, setUserType] = useState("steward");

  const handleChangeRadioButton = (event) => {
    setValue(event.target.value);
  };
  const handleChangeRadioButtonUserType = (event) => {
    setUserType(event.target.value);
  };

  useEffect(() => {
    dispatch(
      provinceDispensersGetAllStewards({
        role_type: "KillHouse",
        key: killHousekey,
        type: userType,
      })
    ).then((r) => {
      setStewardsOptions(r.payload.data);
    });
  }, [dispatch, userType]);

  const validationSchema = Yup.object({
    steward_key: Yup.string(),
    allocation_limit: Yup.number()
      .required("این فیلد اجباری است!")
      .typeError("لطفا عدد وارد کنید!"),
  });

  const formik = useFormik({
    initialValues: {
      steward_key: "",
      allocation_limit: "",
    },
    validationSchema,
  });

  useEffect(() => {
    formik.validateForm();
  }, []);
  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid>
        <FormControl>
          <RadioGroup
            aria-labelledby="demo-controlled-radio-buttons-group"
            name="controlled-radio-buttons-group"
            value={userType}
            onChange={handleChangeRadioButtonUserType}
            row
            sx={{ alignItems: "center" }}
          >
            <FormControlLabel
              value="steward"
              control={<Radio />}
              label="مباشرین"
            />
            <FormControlLabel value="guild" control={<Radio />} label="اصناف" />
          </RadioGroup>
        </FormControl>
      </Grid>

      <Grid item xs={12}>
        <Autocomplete
          style={{ width: "100%" }}
          options={
            stewardsOptions
              ? stewardsOptions.map((i) => ({
                  id: i.key,
                  label: `${i.guildsName} (${i.user?.mobile}) / نوع فعالیت: ${i.typeActivity} / حوزه فعالیت: ${i.areaActivity}`,
                  item: i,
                }))
              : []
          }
          value={formik.values.guild}
          onChange={(e, item) => {
            formik.setFieldValue("steward_key", item?.id);
            formik.validateForm();
          }}
          error={formik.touched.guild && Boolean(formik.errors.guild)}
          helperText={formik.touched.guild && formik.errors.guild}
          getOptionLabel={(option) => option.label}
          renderInput={(params) => (
            <TextField
              {...params}
              label={`انتخاب ${userType === "steward" ? "مباشر" : "صنف"}`}
              variant="outlined"
            />
          )}
        />
      </Grid>

      <Grid item xs={12}>
        <TextField
          fullWidth
          id="allocation_limit"
          label="وزن تعهد روزانه"
          variant="outlined"
          sx={{ width: "100%" }}
          value={formik.values.allocation_limit}
          error={
            formik.touched.allocation_limit
              ? Boolean(formik.errors.allocation_limit)
              : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.allocation_limit &&
            Boolean(formik.errors.allocation_limit)
              ? formik.errors.allocation_limit
              : null
          }
        />
      </Grid>

      <Grid>
        <FormControl>
          <RadioGroup
            aria-labelledby="demo-controlled-radio-buttons-group"
            name="controlled-radio-buttons-group"
            value={value}
            onChange={handleChangeRadioButton}
            row
            sx={{ alignItems: "center" }}
          >
            <FormLabel id="demo-radio-buttons-group-label">
              نوع تعهد: {"‌‌‌‌‌ ‌"}
            </FormLabel>

            <FormControlLabel
              value="forced"
              control={<Radio />}
              label="اجباری"
            />
            <FormControlLabel
              value="optional"
              control={<Radio />}
              label="اختیاری"
            />
          </RadioGroup>
        </FormControl>
      </Grid>

      <Grid container xs={12}>
        <Button
          fullWidth
          variant="contained"
          disabled={!formik.isValid}
          onClick={() => {
            dispatch(
              provinceDispensersAddSteward({
                guilds_key: formik.values.steward_key,
                choose: true,
                type: type,
                owner_key: killHousekey,
                allocation_limit: formik.values.allocation_limit,
                allocation_type: value,
                choose_type: userType,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                updateTable();
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
                dispatch(CLOSE_MODAL());
              }
            });
          }}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
