import {
  Autocomplete,
  Button,
  FormControl,
  InputAdornment,
  InputLabel,
  MenuItem,
  Select,
  TextField,
} from "@mui/material";
import { useFormik } from "formik";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AppContext } from "../../../contexts/AppContext";
import { Yup } from "../../../lib/yup/yup";
import { CLOSE_MODAL } from "../../../lib/redux/slices/appSlice";
import { SPACING } from "../../../data/spacing";
import { Grid } from "../../../components/grid/Grid";
import { guildGetStewardsService } from "../services/guild-get-guilds";
import { guildGetAllocationData } from "../services/guildGetAllocationData";
import { guildGetStewards } from "../services/guild-get-stewards";
import { slaughterAllocateStewardService } from "../../slaughter-house/services/slaughter-allocate-steward";
import { guildGetInventoryStockService } from "../services/guild-get-inventory-stock";
import { GuildEditAllocateStewardService } from "../services/guildEditAllocateStewardService";
import { NumberInput } from "../../../components/number-format-custom/NumberFormatCustom";

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

  const { guildGetStewardsState } = useSelector((state) => state.generalSlice);

  useEffect(() => {
    if (sellType !== "exclusive") {
      dispatch(guildGetStewardsService());
    }
  }, []);

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

  const validationSchema = Yup.object({
    slaughteSteward: Yup.string(),
    // price: Yup.number().when("quantity", {
    //   is: quantity,
    //   then: Yup.number().required("لطفا این فیلد را پر کنید"),
    //   otherwise: Yup.number(),
    // }),
    wholePrice: Yup.number().when("quantity", {
      is: quantity,
      then: Yup.number().required("لطفا این فیلد را پر کنید"),
      otherwise: Yup.number(),
    }),
    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: "",
      wholePrice: "",
      weight: weight ? weight : "",
    },
    validationSchema,
    onSubmit: (values) => {
      let req;

      if (quantity) {
        dispatch(
          GuildEditAllocateStewardService({
            steward_allocation_key: item.key,
            number_of_carcasses: Number(values.numberOfPieces),
            weight_of_carcasses: Number(values.weight),
          })
        ).then(() => {
          dispatch(
            guildGetAllocationData({
              date: selectedDate1,
            })
          );
          dispatch(guildGetStewards({ date: selectedDate1 }));
          dispatch(
            guildGetAllocationData({
              date: selectedDate1,
            })
          );
          dispatch(
            guildGetInventoryStockService({
              date: selectedDate1,
            })
          );

          dispatch(CLOSE_MODAL());
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        });
      } else {
        if (isGuild) {
          req = {
            guild_key: values.slaughteSteward,
            number_of_carcasses: Number(values.numberOfPieces),
            weight_of_carcasses: Number(values.weight),
            sell_type: sellType,
            date: selectedDate1,
            broadcast_type: "steward_broadcast",
            amount: Number(price),
            total_amount: Number(values.wholePrice),
          };
        } else {
          req = {
            guild_key: values.slaughteSteward,
            number_of_carcasses: Number(values.numberOfPieces),
            weight_of_carcasses: Number(values.weight),
            sell_type: sellType,
            date: selectedDate1,
            broadcast_type: "steward_broadcast",
            amount: Number(price),
            total_amount: Number(values.wholePrice),
          };
        }
        dispatch(slaughterAllocateStewardService(req)).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(guildGetStewards({ date: selectedDate1 }));
            dispatch(
              guildGetAllocationData({
                date: selectedDate1,
              })
            );
            dispatch(
              guildGetInventoryStockService({
                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={guildGetStewardsState}
            getOptionLabel={getOptionLabel}
            sx={{ width: "100%" }}
            size="small"
            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={guildGetStewardsState}
            getOptionLabel={getOptionLabel}
            sx={{ width: "100%" }}
            size="small"
            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"
          size="small"
          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
              size="small"
              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
              }
            />
            <FormControl fullWidth>
              <InputLabel id="demo-select-label">خودرو حمل لاشه</InputLabel>
              <Select
                labelId="demo-select-label"
                id="demo-select"
                value=""
                disabled
                label="Select Option"
                size="small"
              >
                {/* You can add MenuItem components for each option */}
                <MenuItem value="" disabled>
                  Select an option
                </MenuItem>
                <MenuItem value={10}>Option 1</MenuItem>
                <MenuItem value={20}>Option 2</MenuItem>
                <MenuItem value={30}>Option 3</MenuItem>
              </Select>
            </FormControl>
            <NumberInput
              allowLeadingZeros
              thousandSeparator=","
              size="small"
              fullWidth
              id="price"
              label="قیمت هر کیلو مرغ"
              variant="outlined"
              InputProps={{
                endAdornment: (
                  <InputAdornment position="start">ریال</InputAdornment>
                ),
                readOnly: true,
              }}
              value={price}
            />
          </>
        )}

        <TextField
          id="numberOfPieces"
          name="numberOfPieces"
          type="number"
          label="حجم لاشه"
          size="small"
          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>
  );
};
