import React, { useContext, useEffect, useState } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import {
  RadioGroup,
  FormControlLabel,
  Radio,
  FormControl,
  Button,
  Typography,
  Autocomplete,
  TextField,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { useDispatch } from "react-redux";
import { provinceJahadSubmitAllocationGetUsers } from "../../services/province-jahad-submit-allocation-get-users";
import {
  provinceJahadEditAllocationService,
  provinceJahadSubmitAllocationService,
} from "../../services/province-jahad-submit-allocation";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ProvinceJahadSubmitAllocation = ({
  type,
  productKey,
  updateTable,
  getDashboardData,
  item,
  // getRemainWeight,
  maxAllow,
}) => {
  const validationSchema = Yup.object({
    allocationType: Yup.string().required("لطفا یک گزینه را انتخاب کنید"),
    weight: Yup.number()
      .required("این فیلد اجباریست!")
      .positive("عدد مثبت وارد کنید!"),
    place: Yup.string().required("این فیلد اجباریست!"),
    description: Yup.string(),
  });

  const [users, setUsers] = useState([]);

  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      allocationType:
        type === "charge" ? "LiveStockProvinceJahad" : "Cooperative",
      buyer_key: null,
      weight: item?.weight || "",
      place: item?.place || "",
      description: item?.description || "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      if (item) {
        let req = {
          allocation_key: item?.key,
          weight: values.weight,
          place: values.place,
          description: values.description,
        };

        req = Object.fromEntries(
          Object.entries(req).filter(([_, value]) => value !== null)
        );

        dispatch(provinceJahadEditAllocationService(req)).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());
            updateTable();
            getDashboardData();
          }
        });
      } else {
        let req = {
          allocator: getRoleFromUrl(),
          receiver:
            getRoleFromUrl() === "Cooperative"
              ? "Cooperative"
              : values.allocationType,
          product_key: productKey,
          buyer_key: values.buyer_key,
          weight: values.weight,
          place: values.place,
          description: values.description,
        };

        req = Object.fromEntries(
          Object.entries(req).filter(([_, value]) => value !== null)
        );

        if (maxAllow && values.weight > maxAllow) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مقدار وارد شده از سهیه دریافتی بیشتر است!",
            severity: "error",
          });
          return;
        }

        dispatch(provinceJahadSubmitAllocationService(req)).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());
            updateTable();
            getDashboardData();
          }
        });
      }
    },
  });

  useEffect(() => {
    if (type !== "charge" && !item) {
      formik.setFieldValue("buyer_key", null);
      dispatch(
        provinceJahadSubmitAllocationGetUsers({
          type: formik.values.allocationType,
        })
      ).then((r) => {
        setUsers(r.payload.data);
      });
    }
  }, [formik.values.allocationType]);

  useEffect(() => {
    formik.validateForm();
  }, []);

  const isFormValid = () => {
    if (type === "charge") {
      return formik.isValid;
    } else if (item) {
      return (
        formik.values.weight && formik.values.place && formik.values.description
      );
    } else {
      return formik.isValid && formik.values.buyer_key;
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      {type !== "charge" &&
        !item &&
        getRoleFromUrl() === "LiveStockProvinceJahad" && (
          <Grid container xs={12} justifyContent="center" alignItems="center">
            <FormControl component="fieldset">
              <RadioGroup
                row
                name="allocationType"
                value={formik.values.allocationType}
                onChange={formik.handleChange}
              >
                <FormControlLabel
                  value="Cooperative"
                  control={<Radio />}
                  label="تخصیص به تعاونی"
                />
                <FormControlLabel
                  value="Union"
                  control={<Radio />}
                  label="تخصیص به اتحادیه"
                />
              </RadioGroup>
              {formik.touched.allocationType &&
                formik.errors.allocationType && (
                  <Typography color="error">
                    {formik.errors.allocationType}
                  </Typography>
                )}
            </FormControl>
          </Grid>
        )}

      <Grid item xs={12}>
        <NumberInput
          allowLeadingZeros
          thousandSeparator=","
          fullWidth
          id="weight"
          label="وزن"
          variant="outlined"
          InputLabelProps={{
            shrink: true,
          }}
          value={formik.values.weight}
          error={formik.touched.weight ? Boolean(formik.errors.weight) : null}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.weight && Boolean(formik.errors.weight)
              ? formik.errors.weight
              : null
          }
        />
      </Grid>

      {type !== "charge" && !item && (
        <Grid xs={12} container>
          <Autocomplete
            fullWidth
            style={{ minWidth: 210 }}
            disablePortal
            id="hatching"
            options={
              users
                ? users.map((i) => {
                    return {
                      data: i,
                      label: `${i?.name}`,
                    };
                  })
                : []
            }
            onChange={(event, value) => {
              formik.setFieldValue("buyer_key", value?.data?.key);
            }}
            renderInput={(params) => (
              <TextField fullWidth {...params} label="انتخاب تخصیص گیرنده" />
            )}
          />
        </Grid>
      )}
      <TextField
        id="place"
        label={type === "charge" ? "مبدا" : "مکان دریافت "}
        variant="outlined"
        sx={{ width: "100%", height: "100%" }}
        value={formik.values.place}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={formik.touched.place ? Boolean(formik.errors.place) : null}
        helperText={
          formik.touched.place && Boolean(formik.errors.place)
            ? formik.errors.place
            : null
        }
      />
      <TextField
        id="description"
        label="توضیحات"
        variant="outlined"
        sx={{ width: "100%", height: "100%" }}
        value={formik.values.description}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={
          formik.touched.description ? Boolean(formik.errors.description) : null
        }
        helperText={
          formik.touched.description && Boolean(formik.errors.description)
            ? formik.errors.description
            : null
        }
      />
      <Button
        disabled={!isFormValid()}
        type="submit"
        variant="contained"
        color="primary"
        fullWidth
        onClick={formik.handleSubmit}
      >
        {item ? "ویرایش" : "ثبت"}
      </Button>
    </Grid>
  );
};
