import {
  Autocomplete,
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
} from "@mui/material";
import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { slaughterGetColdHouses } from "../../services/slaughter-get-cold-houses";
import { slaughterSubmitAllocateToFreezing } from "../../services/slaughter-submit-allocate-to-freezing";
import { AppContext } from "../../../../contexts/AppContext";
import {
  CLOSE_MODAL,
  LOADING_END,
} from "../../../../lib/redux/slices/appSlice";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { slaughterUpdateAllocationForFreezing } from "../../services/slaughter-update-allocation-for-freezing";
import { slaughterGetProductsService } from "../../services/slaughter-inventory-gets";

export const SlaughterAllocateToFreezing = ({
  fetchItems,
  isEdit,
  item,
  updateTable,
  handleUpdateFreezing,
}) => {
  const [coldHouse, setColdHouse] = useState("");
  const [coldHouses, setColdHouses] = useState([]);
  const [openNotif] = useContext(AppContext);
  const [productKey, setProductKey] = useState(null);
  const [productData, setProductData] = useState([]);

  const dispatch = useDispatch();

  useEffect(() => {
    if (!isEdit) {
      dispatch(slaughterGetProductsService()).then((r) => {
        setProductData(r.payload.data);
      });
      dispatch(slaughterGetColdHouses()).then((r) => {
        setColdHouses(r.payload.data);
      });
    }
  }, []);

  const handleChange = (event) => {
    setColdHouse(event.target.value);
  };

  const formik = useFormik({
    initialValues: {
      quantity: item?.quantity ? item?.quantity : "",
      weight: item?.weight ? item?.weight : "",
    },
    validationSchema: Yup.object({
      quantity: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      weight: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
    }),
  });

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

  return (
    <Grid container gap={2} xs={12} justifyContent="center">
      {!isEdit && (
        <Grid xs={12} container>
          <Autocomplete
            fullWidth
            style={{ minWidth: 210 }}
            disablePortal
            id="hatching"
            options={
              productData
                ? productData.map((i) => {
                    return {
                      data: i,
                      label: `${i.name}`,
                    };
                  })
                : []
            }
            onChange={(event, value) => {
              setProductKey(value.data);
            }}
            renderInput={(params) => (
              <TextField fullWidth {...params} label="انتخاب محصول" />
            )}
          />
        </Grid>
      )}
      {!isEdit && (
        <>
          <FormControl>
            <InputLabel id="demo-simple-select-disabled-label">
              انتخاب سردخانه
            </InputLabel>
            <Select
              labelId="demo-simple-select-disabled-label"
              id="demo-simple-select-disabled"
              value={coldHouse}
              label="سردخانه"
              onChange={handleChange}
            >
              {coldHouses?.map((item, i) => {
                return (
                  <MenuItem
                    key={i}
                    value={item?.key}
                  >{`سردخانه ${item.name}`}</MenuItem>
                );
              })}
            </Select>
          </FormControl>
        </>
      )}

      <TextField
        label="تعداد"
        name="quantity"
        value={formik.values.quantity}
        onChange={formik.handleChange}
        error={formik.touched.quantity && Boolean(formik.errors.quantity)}
        helperText={formik.touched.quantity && formik.errors.quantity}
        required
        fullWidth
      />
      <TextField
        label="وزن"
        name="weight"
        value={formik.values.weight}
        onChange={formik.handleChange}
        error={formik.touched.weight && Boolean(formik.errors.weight)}
        helperText={formik.touched.weight && formik.errors.weight}
        required
        fullWidth
      />
      <Button
        disabled={
          isEdit
            ? !formik.isValid
            : !coldHouse || !formik.isValid || !productKey
        }
        fullWidth
        variant="contained"
        onClick={() => {
          if (isEdit) {
            dispatch(
              slaughterUpdateAllocationForFreezing({
                allocation_key: item?.key,
                quantity: parseInt(formik.values.quantity),
                weight: parseInt(formik.values.weight),
              })
            ).then((r) => {
              if (r.payload.error) {
                dispatch(LOADING_END());
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                dispatch(CLOSE_MODAL());
                fetchItems();
                updateTable();
                handleUpdateFreezing();
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          } else {
            dispatch(
              slaughterSubmitAllocateToFreezing({
                cold_house_key: coldHouse,
                quantity: parseInt(formik.values.quantity),
                weight: parseInt(formik.values.weight),
                product_key: productKey?.key,
              })
            ).then((r) => {
              if (r.payload.error) {
                dispatch(LOADING_END());
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                dispatch(CLOSE_MODAL());
                fetchItems();
                updateTable();
                handleUpdateFreezing();
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
