import { Autocomplete, Button, InputAdornment, TextField } 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 { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { Yup } from "../../../../lib/yup/yup";
import { slaughterGetUpdatedInventoryStock } from "../../services/salughter-get-updated-inventory-stock";
import { slaughterManageInventoryAllocationsService } from "../../services/salughter-manage-inventory-allocations";
import { slaughterAllocateStewardService } from "../../services/slaughter-allocate-steward";
import { slaughterEditAllocateStewardService } from "../../services/slaughter-edit-allocate-steward";
import { slaughterGetGuildsService } from "../../services/slaughter-get-guilds";
import { slaughterGetKillhouseGuildsService } from "../../services/slaughter-get-killhouse-guilds";
import { slaughterGetKillhouseStewardsService } from "../../services/slaughter-get-killhouse-stewards";
import { slaughterGetStewardsService } from "../../services/slaughter-get-stewards";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";

export const SlaughterAddSteward = ({
  stewardKey,
  guildKey,
  sellType,
  isGuild,
  weight,
  quantity,
  item,
  totalAverageWeightOfCarcasses,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [, , selectedDate1] = useContext(AppContext);
  const [price, setPrice] = useState();

  const {
    slaughterGetStewards,
    inventorySelectedKillHouse,
    slaughterGetGuilds,
  } = useSelector((state) => state.slaughterSlice);

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

  const getOptionLabel = (option) => option.label;

  const validationSchema = Yup.object({
    wholePrice: Yup.number().when("quantity", {
      is: quantity,
      then: Yup.number().required("لطفا این فیلد را پر کنید"),
      otherwise: Yup.number(),
    }),
    slaughteSteward: Yup.string().required("لطفاً یک مورد را انتخاب کنید"),
    numberOfPieces: Yup.number()
      .required("حجم لاشه را وارد کنید")
      .min(1, "حداقل یک قطعه"),
    weight: Yup.number()
      .required("وزن لاشه را وارد کنید")
      .min(0.01, "حداقل 0.01 کیلوگرم"),
  });

  let defaultKey;

  if (isGuild) {
    defaultKey = guildKey;
  } else {
    defaultKey = stewardKey;
  }

  const formik = useFormik({
    initialValues: {
      slaughteSteward: defaultKey,
      numberOfPieces: quantity ? quantity : "",
      weight: weight ? weight : "",
    },
    validationSchema,
    onSubmit: (values) => {
      let req;
      if (!isGuild) {
        req = {
          steward_key: values.slaughteSteward,
          kill_house_key: inventorySelectedKillHouse,
          number_of_carcasses: Number(values.numberOfPieces),
          weight_of_carcasses: Number(values.weight),
          sell_type: sellType,
          date: selectedDate1,
          amount: Number(price),
          total_amount: Number(values.wholePrice),
        };
      } else {
        req = {
          guild_key: values.slaughteSteward,
          kill_house_key: inventorySelectedKillHouse,
          number_of_carcasses: Number(values.numberOfPieces),
          weight_of_carcasses: Number(values.weight),
          sell_type: sellType,
          date: selectedDate1,
          amount: Number(price),
          total_amount: Number(values.wholePrice),
        };
      }
      if (quantity) {
        dispatch(
          slaughterEditAllocateStewardService({
            steward_allocation_key: item.key,
            number_of_carcasses: Number(values.numberOfPieces),
            weight_of_carcasses: Number(values.weight),
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(
              slaughterGetKillhouseStewardsService({
                kill_house_key: inventorySelectedKillHouse,
                date: selectedDate1,
              })
            );
            dispatch(
              slaughterGetUpdatedInventoryStock({
                kill_house_key: inventorySelectedKillHouse,
                date: selectedDate1,
              })
            );
            dispatch(
              slaughterManageInventoryAllocationsService({
                kill_house_key: inventorySelectedKillHouse,
                date: selectedDate1,
              })
            );
            dispatch(
              slaughterGetKillhouseGuildsService({
                kill_house_key: inventorySelectedKillHouse,
                date: selectedDate1,
              })
            );
            dispatch(CLOSE_MODAL());
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          }
        });
      } else {
        dispatch(slaughterAllocateStewardService(req)).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(
              slaughterGetKillhouseStewardsService({
                kill_house_key: inventorySelectedKillHouse,
                date: selectedDate1,
              })
            );
            dispatch(
              slaughterGetUpdatedInventoryStock({
                kill_house_key: inventorySelectedKillHouse,
                date: selectedDate1,
              })
            );
            dispatch(
              slaughterManageInventoryAllocationsService({
                kill_house_key: inventorySelectedKillHouse,
                date: selectedDate1,
              })
            );
            dispatch(
              slaughterGetKillhouseGuildsService({
                kill_house_key: inventorySelectedKillHouse,
                date: selectedDate1,
              })
            );
            dispatch(CLOSE_MODAL());
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          }
        });
      }
    },
  });

  useEffect(() => {
    const finalQuantity = formik.values.weight / totalAverageWeightOfCarcasses;
    formik.setFieldValue("numberOfPieces", Number(finalQuantity).toFixed(0));
  }, [formik.values.weight]);

  useEffect(() => {
    const calcPrice = formik.values.wholePrice / Number(formik.values.weight);
    setPrice(Number(calcPrice.toFixed(0)));
  }, [formik.values.wholePrice]);

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container width="100%" gap={SPACING.SMALL}>
        {!stewardKey && !guildKey && !isGuild && !quantity && (
          <Autocomplete
            disablePortal
            options={slaughterGetStewards}
            getOptionLabel={getOptionLabel}
            sx={{ width: "100%" }}
            onChange={(event, value) =>
              formik.setFieldValue("slaughteSteward", value.value)
            }
            onBlur={formik.handleBlur("slaughteSteward")}
            //   value={formik.values.slaughteSteward}
            renderInput={(params) => <TextField {...params} label="مباشر" />}
          />
        )}

        {isGuild && !quantity && !stewardKey && !guildKey && (
          <Autocomplete
            disablePortal
            options={slaughterGetGuilds ? slaughterGetGuilds : []}
            getOptionLabel={getOptionLabel}
            sx={{ width: "100%" }}
            onChange={(event, value) =>
              formik.setFieldValue("slaughteSteward", value.value)
            }
            onBlur={formik.handleBlur("slaughteSteward")}
            //   value={formik.values.slaughteSteward}
            renderInput={(params) => <TextField {...params} label="اصناف" />}
          />
        )}

        <TextField
          id="weight"
          name="weight"
          type="number"
          label="وزن لاشه"
          variant="outlined"
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">کیلوگرم</InputAdornment>
            ),
          }}
          {...formik.getFieldProps("weight")}
          error={formik.touched.weight && formik.errors.weight}
          helperText={formik.touched.weight && formik.errors.weight}
        />

        {!quantity && (
          <>
            <NumberInput
              allowLeadingZeros
              thousandSeparator=","
              fullWidth
              id="wholePrice"
              label="هزینه کل"
              variant="outlined"
              InputProps={{
                endAdornment: (
                  <InputAdornment position="start">ریال</InputAdornment>
                ),
              }}
              value={formik.values.wholePrice}
              error={
                formik.touched.wholePrice
                  ? Boolean(formik.errors.wholePrice)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.wholePrice && Boolean(formik.errors.wholePrice)
                  ? formik.errors.wholePrice
                  : null
              }
            />

            <NumberInput
              allowLeadingZeros
              thousandSeparator=","
              fullWidth
              id="price"
              label="قیمت هر کیلو مرغ"
              variant="outlined"
              InputLabelProps={{
                shrink: true,
              }}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="start">ریال</InputAdornment>
                ),
                readOnly: true,
              }}
              value={price}
            />
          </>
        )}

        <TextField
          id="numberOfPieces"
          name="numberOfPieces"
          type="number"
          label="حجم لاشه"
          variant="outlined"
          value={formik.values.numberOfPieces}
          InputProps={{
            endAdornment: <InputAdornment position="end">قطعه</InputAdornment>,
          }}
          {...formik.getFieldProps("numberOfPieces")}
          error={formik.touched.numberOfPieces && formik.errors.numberOfPieces}
          helperText={
            formik.touched.numberOfPieces && formik.errors.numberOfPieces
          }
        />
        <Button variant="contained" fullWidth type="submit">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
