import {
  Autocomplete,
  Button,
  Checkbox,
  FormControlLabel,
  InputAdornment,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { Yup } from "../../../../lib/yup/yup";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceChangeActiveGuildService } from "../../services/province-change-active-guild";
import { provinceGetBuyersService } from "../../services/province-get-buyers";
import { provinceGetStewardsService } from "../../services/province-get-stewards";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

const validationSchema = Yup.object().shape({
  // agreed: Yup.boolean().oneOf([true], 'You must agree to the terms and conditions'),
});

export const GuildLimitaion = ({ guild, updateTable }) => {
  const { provinceGetStewardsOptions, provinceGetBuyersOptions } = useSelector(
    (state) => state.provinceSlice
  );
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [warehouses, setWarehouses] = useState(
    guild.centersAllocation ? guild.centersAllocation : []
  );
  const [buyers, setBuyers] = useState(
    guild.killHouseCentersAllocation ? guild.killHouseCentersAllocation : []
  );

  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const formik = useFormik({
    initialValues: {
      allocation_limit: guild.allocationLimit,
      centers_allocation: "",
      limitation_allocation: guild.limitationAllocation,
      currentBuyer: "",
    },
    validationSchema,
    onSubmit: (values) => {
      dispatch(
        provinceChangeActiveGuildService({
          kill_house_centers_allocation: buyers,
          allocation_limit: values.allocation_limit,
          limitation_allocation: values.limitation_allocation,
          centers_allocation: warehouses,
          guilds_key: guild.key,
        })
      ).then((r) => {
        updateTable();
        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",
          });
        }
      });
    },
  });

  useEffect(() => {
    dispatch(
      provinceGetStewardsService({
        role_key: checkPathStartsWith("province")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
    dispatch(
      provinceGetBuyersService({
        role_key: checkPathStartsWith("province")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
  }, [selectedSubUser?.key]);

  return (
    <form onSubmit={formik.handleSubmit} style={{ width: "100%" }}>
      <Grid container direction="column" width="100%" gap={SPACING.SMALL}>
        <FormControlLabel
          control={
            <Checkbox
              name="limitation_allocation"
              checked={formik.values.limitation_allocation}
              onChange={formik.handleChange}
            />
          }
          label="محدودیت تخصیص"
        />
        {formik.errors.limitation_allocation && (
          <div>{formik.errors.limitation_allocation}</div>
        )}
        {formik.values.limitation_allocation && (
          <>
            <TextField
              label="حداکثر تخصیص"
              variant="outlined"
              fullWidth
              id="allocation_limit"
              name="allocation_limit"
              InputProps={{
                endAdornment: (
                  <InputAdornment position="start">کیلوگرم</InputAdornment>
                ),
              }}
              value={formik.values.allocation_limit}
              onChange={formik.handleChange}
              error={
                formik.touched.allocation_limit &&
                Boolean(formik.errors.allocation_limit)
              }
              helperText={
                formik.touched.allocation_limit &&
                formik.errors.allocation_limit
              }
            />
            {!guild?.steward && getRoleFromUrl() !== "Guilds" && (
              <>
                <Autocomplete
                  style={{ width: "100%" }}
                  options={provinceGetStewardsOptions}
                  value={formik.values.guild}
                  onChange={(e, item) => {
                    setWarehouses([...warehouses, item]);
                  }}
                  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"
                    />
                  )}
                />
                <Typography>محدودیت مباشرین انتخاب شده</Typography>
                {!warehouses.length && (
                  <Typography variant="caption">محدودیتی وجود ندارد</Typography>
                )}
                {warehouses?.map((item) => {
                  return (
                    <>
                      {item !== null && (
                        <Grid
                          container
                          gap={SPACING.SMALL}
                          key={item.value}
                          alignItems="center"
                        >
                          <Button
                            variant="text"
                            onClick={() => {
                              setWarehouses(
                                warehouses.filter(
                                  (it) => it.value !== item.value
                                )
                              );
                            }}
                          >
                            حذف
                          </Button>
                          <Typography key={item.label}>{item.label}</Typography>
                        </Grid>
                      )}
                    </>
                  );
                })}
              </>
            )}
          </>
        )}

        {formik.values.limitation_allocation &&
          getRoleFromUrl() !== "KillHouse" &&
          getRoleFromUrl() !== "Guilds" && (
            <>
              <Autocomplete
                style={{ width: "100%" }}
                options={provinceGetBuyersOptions}
                value={formik.values.guild}
                onChange={(e, item) => {
                  setBuyers([...buyers, item]);
                }}
                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"
                  />
                )}
              />
              <Typography>محدودیت انبار های انتخاب شده</Typography>
              {!buyers.length && (
                <Typography variant="caption">محدودیتی وجود ندارد</Typography>
              )}
              {buyers?.map((item) => {
                return (
                  <>
                    {item !== null && (
                      <Grid
                        container
                        gap={SPACING.SMALL}
                        key={item.value}
                        alignItems="center"
                      >
                        <Button
                          variant="text"
                          onClick={() => {
                            setBuyers(
                              buyers.filter((it) => it.value !== item.value)
                            );
                          }}
                        >
                          حذف
                        </Button>
                        <Typography key={item.label}>{item.label}</Typography>
                      </Grid>
                    )}
                  </>
                );
              })}
            </>
          )}
        <Button color="primary" fullWidth variant="contained" type="submit">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
