import {
  Autocomplete,
  Button,
  Checkbox,
  Divider,
  FormControl,
  FormControlLabel,
  // FormGroup,
  // FormControlLabel,
  FormHelperText,
  FormLabel,
  IconButton,
  InputAdornment,
  InputLabel,
  ListItem,
  ListItemIcon,
  ListItemText,
  MenuItem,
  Radio,
  // Radio,
  RadioGroup,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { useEffect } from "react";
import { DatePicker } from "@mui/x-date-pickers";
import { useDispatch, useSelector } from "react-redux";
import { avicultureNewRequest } from "../../services/aviculture-new-request";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import moment from "moment";
import { useState } from "react";
import { avicultureGetHatchingData } from "../../services/aviculture-get-hatching-data";
import { avicultureGetPoultry } from "../../services/aviculture-get-poultry";
import { avicultureGetChickenPrice } from "../../services/aviculture-get-chicken-price";
import DeleteIcon from "@mui/icons-material/Delete";
import { avicultureGetRequests } from "../../services/aviculture-requests";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import AddIcon from "@mui/icons-material/Add";
// import { NumericFormat } from "react-number-format";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { DialogAlert } from "../../../../components/dialog-alert/DialogAlert";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
// import { NumberFormatCustom } from "../../../../components/number-format-custom/NumberFormatCustom";
import DoneIcon from "@mui/icons-material/Done";
// import { SelectCheck } from "../../../../components/select-check/SelectCheck";
import { avicultureGetSlaughters } from "../../services/aviculture-get-slaughters";
import { avicultureGetUnions } from "../../services/aviculture-get-unions";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { SelectCheck } from "../../../../components/select-check/SelectCheck";

export const AvicultureNewRequest = () => {
  const [openNotif] = useContext(AppContext);
  const [hatchingKey, sethatchingKey] = useState("");
  const [hatchingData, setHatchingData] = useState("");
  const [hatchingSelected, setHatchingSelected] = useState("");
  const [poultryData, setPoultryData] = useState("");
  const [poultryKey, setPolutryKey] = useState("");
  const [quantity, setQuantity] = useState("");
  const [losses, setlosses] = useState("");
  const [leftOvers, setLeftOvers] = useState("");
  const [isUnion] = useState(false);
  const [isStockMarket, setIsStockMarket] = useState(false);
  const [pricingKey, setPriceKey] = useState();
  const [chickenBreed, setChickenBreed] = useState("");
  const [chickenCanRequest, setChickenCanRequest] = useState("");
  const [slaughterHousesListForSelect, setSlaughterHousesListForSelect] =
    useState([]);

  const [, userProfile] = useUserProfile();

  const validationSchemaFreeSale = Yup.object().shape({
    name: Yup.string().required("نام اجباری است"),
    lastname: Yup.string().required("نام خانوادگی اجباری است"),
    mobile: Yup.string().required("موبایل اجباری است"),
    province: Yup.string().required("استان اجباری است"),
    city: Yup.string().required("شهرستان اجباری است"),
    buyerType: Yup.string().required("نوع خریدار اجباری است"),
  });

  const inputArr = [
    {
      type: "text",
      id: 1,
      value: "",
    },
  ];

  const inputArrPrices = [
    {
      type: "text",
      id: 1,
      value: "",
    },
  ];

  const [arr, setArr] = useState(inputArr);
  const [arrPrices, setArrPrices] = useState(inputArrPrices);

  const dispatch = useDispatch();

  const { avicultureChickenPrice } = useSelector(
    (state) => state.avicultureSlice
  );

  const { avicultureSlaughters } = useSelector(
    (state) => state.avicultureSlice
  );

  useEffect(() => {
    setSlaughterHousesListForSelect(
      avicultureSlaughters?.map((item) => {
        return {
          label: `${item.name} (${item.killHouseOperator?.user?.fullname})`,
          value: `${item.name} (${item.killHouseOperator?.user?.fullname})`,
        };
      })
    );
  }, [avicultureSlaughters]);

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(avicultureGetChickenPrice());
    dispatch(avicultureGetSlaughters());
    dispatch(LOADING_END());
  }, []);

  const [unions, setUnions] = useState();
  const [unionSelected, setUnionSelected] = useState();

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(avicultureGetUnions()).then((r) => {
      setUnionSelected(r.payload.data[0]?.key);
      setUnions(r.payload.data);
    });
    dispatch(LOADING_END());
  }, []);

  const addInput = () => {
    if (arr.length < 3) {
      setArr((prevState) => {
        return [
          ...prevState,
          {
            type: "text",
            value: "",
          },
        ];
      });

      setArrPrices((prevState) => {
        return [
          ...prevState,
          {
            type: "text",
            value: "",
          },
        ];
      });
    }
  };

  const removeInput = () => {
    const number = arr.length - 1;

    if (number !== 0) {
      const filteredArrayPrice = arr.filter((object, i) => i !== number);
      const filteredArrayTime = arrPrices.filter((object, i) => i !== number);

      setArr(filteredArrayPrice);
      setArrPrices(filteredArrayTime);
    }

    // setArr((s) => {
    //   return s.splice(arr.findIndex((item) => item.id === number, 1));
    // });

    // setArrPrices((s) => {
    //   return s.splice(arr.findIndex((item) => item.id === number, 1));
    // });
  };

  const handleChange = (e) => {
    e.preventDefault();

    const index = e.target.id;
    setArr((s) => {
      const newArr = s.slice();
      newArr[index].value = e.target.value;

      return newArr;
    });
  };

  const handleChangeTime = (e) => {
    e.preventDefault();

    const index = e.target.id;

    setArrPrices((s) => {
      const newArrPrice = s.slice();
      newArrPrice[index].value = e.target.dataset.value;

      return newArrPrice;
    });
  };

  useEffect(() => {
    if (avicultureChickenPrice) {
      setPriceKey(avicultureChickenPrice?.key);
    }
  }, [avicultureChickenPrice]);
  const formik = useFormik({
    initialValues: {
      noChicken: "",
      sellType: {
        cash: true,
        haveTime: false,
      },
      price1: "",
      price2: "",
      price3: "",
      slaughterDate: moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
      period1: "4",
      period2: "4",
      period3: "4",
      weight: "",
      losses: "0",
      isUnion,
      isStockMarket,
      isAccepted: false,
      selectedSlaughters: [],
    },
    validationSchema: Yup.object({
      noChicken: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!")
        .min(0, "تعداد وارد شده از حداقل ممکن کمتر است")
        .max(chickenCanRequest, "تعداد وارد شده از کل موجودی بیشتر است"),
      isAccepted: Yup.boolean()
        .test("req", "باید تعهد نامه را بپذیرید!", (val, context) => {
          return context.originalValue && context.originalValue === true;
        })
        .required("این فیلد اجباری است!"),
      price1: Yup.number()
        .typeError("لطفا عدد وارد کنید!")
        .min(
          avicultureChickenPrice?.floorPrice,
          "قیمت وارد شده از کف قیمت امروز کمتر است"
        )
        .max(
          avicultureChickenPrice?.ceilingPrice,
          "قیمت وارد شده از سقف قیمت امروز بیشتر است"
        ),
      price2: Yup.number()
        .typeError("لطفا عدد وارد کنید!")
        .min(
          avicultureChickenPrice?.floorPrice,
          "قیمت وارد شده از کف قیمت امروز کمتر است"
        )
        .max(
          avicultureChickenPrice?.ceilingPrice,
          "قیمت وارد شده از سقف قیمت امروز بیشتر است"
        ),
      price3: Yup.number()
        .typeError("لطفا عدد وارد کنید!")
        .min(
          avicultureChickenPrice?.floorPrice,
          "قیمت وارد شده از کف قیمت امروز کمتر است"
        )
        .max(
          avicultureChickenPrice?.ceilingPrice,
          "قیمت وارد شده از سقف قیمت امروز بیشتر است"
        ),
      weight: Yup.number()
        .test("weight", "وزن را تا دو رقم اعشار وارد کنید", (val, context) => {
          return (
            context.originalValue &&
            context.originalValue.toString().length <= 4
          );
        })
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
      losses: Yup.number()
        .required("این فیلد اجباری است!")
        .max(quantity, "تلفات وارد شده از باقیمانده بیشتر است!")
        .typeError("لطفا تعداد تلفات را وارد کنید!"),
      sellType: Yup.object()
        .test("sellType", "نحوه فروش را انتخاب کنید!", (val, context) => {
          return (
            context.originalValue &&
            Object.values(context.originalValue).some((item) => item === true)
          );
        })
        .required("این فیلد اجباری است!"),
    }),
  });

  const penaltyPrice = formik.values.noChicken * 1000;
  const dialogContent = (
    <>
      <Typography variant="body1">
        اینجانب {userProfile.fullname} موافقت خود را نسبت به موارد ذکر شده اعلام
        می نمایم.
      </Typography>
      <ListItem>
        <ListItemIcon>
          <DoneIcon />
        </ListItemIcon>
        <ListItemText
          primary={`        بر اساس این توافق نامه در صورت لغو فروش ${formik.values.noChicken} قطعه
        مرغ ${penaltyPrice} ریال جریمه خواهم شد.`}
        />
      </ListItem>
      <Typography></Typography>
    </>
  );

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(avicultureGetPoultry()).then((r) => {
      setPoultryData(r.payload.data);
      dispatch(LOADING_END());
    });
  }, []);

  useEffect(() => {
    let newVal = formik.values.weight;
    const mystring = formik.values.weight.toString().split(".").join("");
    if (formik.values.weight) {
      if (mystring.length <= 3) {
        if (mystring.length === 2) {
          newVal = mystring[0] + "." + mystring[1];
        }
        if (mystring.length === 3) {
          newVal = mystring[0] + "." + mystring[1] + mystring[2];
        }
      }
    }
    if (isNaN(Number.parseFloat(newVal))) {
      formik.setFieldValue("weight", "");
    } else {
      formik.setFieldValue("weight", Number.parseFloat(newVal));
    }
  }, [formik.values.weight]);

  useEffect(() => {
    if (isStockMarket) {
      dispatch(avicultureGetChickenPrice()).then((r) => {
        if (Array.isArray(r.payload.data)) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "قیمت روز مرغ در سامانه ثبت نشده است.",
            severity: "error",
          });

          dispatch(DRAWER({ right: false, bottom: false, content: null }));
        } else {
          dispatch(LOADING_END());
        }
      });
    }
  }, [isStockMarket]);

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

  useEffect(() => {
    if (poultryKey) {
      dispatch(LOADING_START());
      dispatch(avicultureGetHatchingData({ key: poultryKey })).then((r) => {
        if (r.payload.data) {
          setHatchingData(r.payload.data);

          dispatch(LOADING_END());
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات جوجه ریزی یافت نشد!",
            severity: "error",
          });
        }
        dispatch(LOADING_END());
      });
    }
  }, [poultryKey]);

  useEffect(() => {
    setChickenCanRequest(
      formik.values.noChicken <= Number(leftOvers) &&
        Number(formik.values.losses) <= Number(leftOvers)
        ? Number(leftOvers) - Number(formik.values.losses)
        : 0
    );
  }, [formik.values.losses, leftOvers, formik.values.noChicken]);

  useEffect(() => {
    setQuantity(hatchingSelected.quantity);
    setlosses(hatchingSelected.losses);
    setLeftOvers(hatchingSelected.leftOver);
  }, [hatchingSelected]);

  // const handleSellTypeChange = (event) => {
  //   formik.setFieldValue("sellType", {
  //     ...formik.values.sellType,
  //     [event.target.name]: event.target.checked,
  //   });
  // };

  const formikFreeSale = useFormik({
    initialValues: {
      name: "",
      lastname: "",
      mobile: "",
      province: "",
      city: "",
      buyerType: "",
    },
    validationSchemaFreeSale,
    onSubmit: (values) => {
      // console.log(values);
    },
  });

  return (
    <Grid container gap={SPACING.SMALL} direction="column" display={"flex"}>
      <Grid container gap={SPACING.SMALL} direction={"column"}>
        <Grid minWidth={210}>
          <Autocomplete
            disablePortal
            id="combo-box-demo"
            options={
              poultryData
                ? poultryData.map((i) => ({
                    id: i.key,
                    label: i.unitName,
                  }))
                : []
            }
            onChange={(event, value) => {
              setPolutryKey(value.id);
            }}
            renderInput={(params) => (
              <TextField {...params} label="محل پرورش" />
            )}
          />
        </Grid>

        <Grid minWidth={210}>
          <Autocomplete
            disablePortal
            id="hatching"
            options={
              hatchingData
                ? hatchingData.map((i) => {
                    return {
                      id: i.key,
                      race: i.chickenBreed,
                      selected: i,
                      label: `دوره ${i.period} سالن ${i.hall} نژاد ${i.chickenBreed} باقیمانده ${i.leftOver} قطعه`,
                    };
                  })
                : []
            }
            onChange={(event, value) => {
              sethatchingKey(value.id);
              setHatchingSelected(value.selected);
              let race = value.race;
              if (race.includes("-")) {
                race = "ترکیبی";
              }
              setChickenBreed(race);
            }}
            renderInput={(params) => (
              <TextField {...params} label="دوره جوجه ریزی" />
            )}
          />
        </Grid>
        <Grid>
          <TextField
            disabled
            fullWidth
            id="outlined-read-only-input"
            label="تعداد جوجه ریزی"
            value={quantity ? quantity : "نامشخص"}
            InputProps={{
              readOnly: true,
            }}
          />
        </Grid>
        <Grid>
          <TextField
            disabled
            fullWidth
            id="outlined-read-only-input"
            label="جمع ثبت شده دامپزشک و مرغدار"
            value={losses ? losses : "نامشخص"}
            InputProps={{
              readOnly: true,
            }}
          />
        </Grid>
        <Grid>
          <TextField
            disabled
            fullWidth
            id="outlined-read-only-input"
            label="باقیمانده"
            value={leftOvers ? leftOvers : "نامشخص"}
            InputProps={{
              readOnly: true,
            }}
          />
        </Grid>
      </Grid>

      {hatchingSelected && (
        <Grid container gap={SPACING.SMALL} direction={"column"}>
          <Typography>اطلاعات کشتار</Typography>
          {getRoleFromUrl() !== "Poultry" && (
            <Grid>
              <Grid>
                <NumberInput
                  allowLeadingZeros
                  thousandSeparator=","
                  fullWidth
                  id="losses"
                  label="تلفات"
                  variant="outlined"
                  value={formik.values.losses}
                  error={
                    formik.touched.losses ? Boolean(formik.errors.losses) : null
                  }
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.losses && Boolean(formik.errors.losses)
                      ? formik.errors.losses
                      : null
                  }
                />
              </Grid>
            </Grid>
          )}
          <Grid>
            {/* <NumericFormat
              customInput={TextField}
              allowLeadingZeros
              thousandSeparator=","
              fullWidth
              id="noChicken"
              label="تعداد مرغ برای کشتار"
              // InputProps={{
              //   inputComponent: NumberFormatCustom,
              // }}
              variant="outlined"
              value={formik.values.noChicken}
              error={
                formik.touched.noChicken
                  ? Boolean(formik.errors.noChicken)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.noChicken && Boolean(formik.errors.noChicken)
                  ? formik.errors.noChicken
                  : null
              }
            /> */}
            <NumberInput
              allowLeadingZeros
              thousandSeparator=","
              fullWidth
              id="noChicken"
              label="تعداد مرغ برای کشتار"
              // InputProps={{
              //   inputComponent: NumberFormatCustom,
              // }}
              variant="outlined"
              value={formik.values.noChicken}
              error={
                formik.touched.noChicken
                  ? Boolean(formik.errors.noChicken)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.noChicken && Boolean(formik.errors.noChicken)
                  ? formik.errors.noChicken
                  : null
              }
            />
          </Grid>

          <Grid
            container
            gap={SPACING.TINY}
            justifyContent="space-evenly"
            alignItems={"start"}
          >
            <Grid container gap={SPACING.TINY}>
              <Typography
                color={(prop) => prop.palette.grey["A700"]}
                variant={"caption"}
              >
                باقیمانده:
              </Typography>
              <Typography variant={"button"}>
                {formik.values.noChicken
                  ? formik.values.noChicken <= Number(leftOvers) &&
                    Number(formik.values.losses) <= Number(leftOvers) &&
                    Number(leftOvers) -
                      Number(formik.values.losses) -
                      Number(formik.values.noChicken) >=
                      0
                    ? Math.abs(
                        Number(leftOvers) -
                          Number(formik.values.losses) -
                          Number(formik.values.noChicken)
                      )
                    : 0
                  : Number(leftOvers)}
              </Typography>

              <Typography variant={"button"}>قطعه</Typography>
            </Grid>
            <Grid container>
              <Grid container gap={SPACING.TINY} alignItems={"center"}>
                <Typography
                  color={(prop) => prop.palette.grey["A700"]}
                  variant={"caption"}
                >
                  سن مرغ:
                </Typography>
                <Typography variant={"button"}>
                  {hatchingSelected.age}
                </Typography>
                <Typography variant={"button"}>روزه</Typography>
              </Grid>
            </Grid>
          </Grid>

          <Grid>
            <DatePicker
              label="تاریخ کشتار"
              id="slaughterDate"
              renderInput={(params) => <TextField {...params} />}
              value={formik.values.slaughterDate}
              error={
                formik.touched.slaughterDate
                  ? Boolean(formik.errors.slaughterDate)
                  : null
              }
              onChange={(e) => {
                formik.setFieldValue(
                  "slaughterDate",
                  moment(e).format("YYYY-MM-DD hh:mm:ss")
                );
              }}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.slaughterDate &&
                Boolean(formik.errors.slaughterDate)
                  ? formik.errors.slaughterDate
                  : null
              }
            />
          </Grid>
          <Grid>
            <TextField
              id="weight"
              label="وزن تقریبی مرغ"
              variant="outlined"
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">کیلوگرم</InputAdornment>
                ),
              }}
              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>

          {/* <Grid>
            <Typography>نحوه فروش</Typography>
          </Grid> */}
          <Grid display="none">
            <FormControl>
              <RadioGroup
                aria-labelledby="demo-radio-buttons-group-label"
                defaultValue="فروش اتحادیه"
                name="radio-buttons-group"
                onChange={(event) => {
                  setIsStockMarket(event.currentTarget.value);
                }}
              >
                {/* <FormControlLabel
                  value="فروش اتحادیه"
                  control={<Radio />}
                  label="فروش اتحادیه"
                /> */}
                {/* <FormControlLabel
                  value="فروش مزایده ای"
                  control={
                    <Radio id="isStockMarket" onChange={formik.handleChange} />
                  }
                  label="فروش مزایده ای"
                /> */}
                {isStockMarket === "فروش مزایده ای" && (
                  <Grid container gap={SPACING.SMALL}>
                    <Grid container gap={SPACING.SMALL} alignItems={"center"}>
                      <Typography
                        color={(prop) => prop.palette.grey["A700"]}
                        variant={"caption"}
                      >
                        کف قیمت امروز:
                      </Typography>
                      <Typography color="secondary" variant={"button"}>
                        {avicultureChickenPrice?.floorPrice
                          ? avicultureChickenPrice?.floorPrice.toLocaleString()
                          : "نامشخص"}{" "}
                        {"  "}
                        ریال
                      </Typography>
                    </Grid>
                    <Grid container gap={SPACING.SMALL} alignItems={"center"}>
                      <Typography
                        color={(prop) => prop.palette.grey["A700"]}
                        variant={"caption"}
                      >
                        سقف قیمت امروز:
                      </Typography>
                      <Typography color="secondary" variant={"button"}>
                        {avicultureChickenPrice?.ceilingPrice
                          ? avicultureChickenPrice?.ceilingPrice.toLocaleString()
                          : "نامشخص"}{" "}
                        {"  "}
                        ریال
                      </Typography>
                    </Grid>

                    <Divider style={{ width: "100%" }} />

                    {arr.map((item, i) => {
                      return (
                        <Grid
                          gap={SPACING.SMALL}
                          container
                          key={item?.id}
                          sx={{ minWidth: 210 }}
                        >
                          <Typography mb={SPACING.SMALL} display="flex">
                            پیشنهاد {i + 1}
                          </Typography>

                          <NumberInput
                            allowLeadingZeros
                            thousandSeparator=","
                            error={false}
                            fullWidth
                            label="قیمت پیشنهادی"
                            variant="outlined"
                            onChange={handleChange}
                            id={i}
                          />

                          <FormControl fullWidth>
                            <InputLabel id="demo-simple-select-label">
                              بازه زمانی (ساعت)
                            </InputLabel>
                            <Select
                              id={i}
                              labelId="demo-simple-select-label"
                              label="بازه زمانی (ساعت)"
                            >
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"1"}
                              >
                                1
                              </MenuItem>
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"2"}
                              >
                                2
                              </MenuItem>
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"3"}
                              >
                                3
                              </MenuItem>
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"4"}
                              >
                                4
                              </MenuItem>
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"5"}
                              >
                                5
                              </MenuItem>
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"6"}
                              >
                                6
                              </MenuItem>
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"7"}
                              >
                                7
                              </MenuItem>
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"8"}
                              >
                                8
                              </MenuItem>
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"9"}
                              >
                                9
                              </MenuItem>
                              <MenuItem
                                onClick={handleChangeTime}
                                id={i}
                                value={"10"}
                              >
                                10
                              </MenuItem>
                            </Select>
                            <FormHelperText>
                              {formik.touched.period1 &&
                              Boolean(formik.errors.period1)
                                ? formik.errors.period1
                                : null}
                            </FormHelperText>
                          </FormControl>
                          {/* <input
                        key={i}
                        onChange={handleChange}
                        value={item.value}
                        id={i}
                        type={item.type}
                      /> */}
                        </Grid>
                      );
                    })}

                    <Grid container>
                      {arr.length > 1 && (
                        <IconButton
                          onClick={removeInput}
                          aria-label="delete"
                          color="secondary"
                        >
                          <DeleteIcon />
                        </IconButton>
                      )}
                      {arr.length < 3 && (
                        <IconButton
                          xs={12}
                          onClick={addInput}
                          aria-label="add"
                          color="primary"
                        >
                          <AddIcon />
                          <Typography>افزودن پیشنهاد جدید</Typography>
                        </IconButton>
                      )}
                    </Grid>

                    <Grid container sx={{ width: "100%" }}>
                      <Typography variant="body2">
                        در صورت عدم فروش در بورس، از طریق اتحادیه فروش برود
                        <Checkbox id="isUnion" onChange={formik.handleChange} />
                      </Typography>
                    </Grid>
                  </Grid>
                )}
              </RadioGroup>
            </FormControl>
          </Grid>

          {poultryData?.length &&
            poultryData[0]?.provinceAllowChooseKillHouse && (
              <Grid container direction="column" gap={SPACING.SMALL}>
                <SelectCheck
                  label={"انتخاب کشتارگاه پیشنهادی"}
                  onChange={(e) =>
                    formik.setFieldValue("selectedSlaughters", e)
                  }
                  options={slaughterHousesListForSelect}
                />
                <Grid container gap={SPACING.SMALL}>
                  {formik.values.selectedSlaughters && (
                    <Typography variant="body1">کشتارگاهای انتخابی</Typography>
                  )}
                  <Grid container direction="column">
                    {formik.values.selectedSlaughters.map((item, i) => {
                      return (
                        <Typography variant="body2" key={i}>
                          {i + 1}- {item}
                        </Typography>
                      );
                    })}
                  </Grid>
                </Grid>
              </Grid>
            )}

          {/* <Grid>
            <Grid mb={SPACING.TINY}>
              <Typography varaint="body1">نحوه فروش</Typography>
            </Grid>
            <FormGroup>
              <FormControlLabel
                control={
                  <Checkbox
                    onChange={handleSellTypeChange}
                    name="cash"
                    value="نقدی"
                  />
                }
                label="نقدی"
              />
              <FormControlLabel
                control={
                  <Checkbox
                    onChange={handleSellTypeChange}
                    name="haveTime"
                    value="زمان دار"
                  />
                }
                label="زمان دار (تا یک ماه)"
              />
            </FormGroup>
            <FormHelperText>
              {formik.touched.sellType && Boolean(formik.errors.sellType)
                ? formik.errors.sellType
                : null}
            </FormHelperText>
          </Grid> */}

          {/* {unions?.length > 1 && (
            <> */}
          <Divider />
          <Grid>
            <FormControl>
              <FormLabel id="demo-radio-buttons-group-label">
                اطلاعات تعاونی
              </FormLabel>
              <RadioGroup
                aria-labelledby="demo-radio-buttons-group-label"
                defaultValue={unions?.length ? unions[0]?.key : ""}
                name="radio-buttons-group"
                onChange={(event) => {
                  setUnionSelected(event.currentTarget.value);
                }}
              >
                {unions?.map((item) => {
                  return (
                    <FormControlLabel
                      key={item.key}
                      disabled={true}
                      value={item.key}
                      label={item.unitName}
                      control={<Radio />}
                    />
                  );
                })}
              </RadioGroup>
            </FormControl>
          </Grid>
          {/* </>
          )} */}
          <Grid>
            <DialogAlert
              title="تعهد نامه"
              content={dialogContent}
              actions={
                <Grid container gap={SPACING.TINY}>
                  <Button
                    variant="outlined"
                    color="error"
                    onClick={() => {
                      formik.setFieldValue("isAccepted", false);
                    }}
                  >
                    رد
                  </Button>
                  <Button
                    variant="contained"
                    color="success"
                    onClick={() => {
                      formik.setFieldValue("isAccepted", true);
                    }}
                  >
                    موافقم
                  </Button>
                </Grid>
              }
              btnTitle={"با تعهد نامه موافق هستم!"}
              isAccepted={formik.values.isAccepted}
            />
          </Grid>
          <Grid mb={SPACING.SMALL}>
            <Button
              fullWidth
              disabled={!formik.isValid}
              onClick={() => {
                dispatch(LOADING_START());
                if (isStockMarket === "فروش مزایده ای") {
                  dispatch(
                    avicultureNewRequest({
                      operator_key: unions?.length > 1 ? unionSelected : "",
                      poultry_hatching_key: hatchingKey,
                      quantity: formik.values.noChicken,
                      send_date: formik.values.slaughterDate,
                      chicken_breed: chickenBreed,
                      Index_weight: formik.values.weight,
                      union: formik.values.isUnion,
                      losses:
                        formik.values.losses !== "" ? formik.values.losses : 0,
                      auction: true,
                      auction_list: arr.map((item, i) => {
                        return {
                          pricing_key: pricingKey,
                          fee: item.value
                            ? item.value
                            : avicultureChickenPrice?.floorPrice,
                          hour: arrPrices[i].value ? arrPrices[i].value : "4",
                        };
                      }),
                    })
                  ).then((r) => {
                    dispatch(LOADING_END());
                    if (r.error) {
                      if (r.error.message.includes("403")) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "قیمت پیشنهادی نباید از حداکثر قیمت روز بیشتر باشد.",
                          severity: "error",
                        });
                      } else {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "مشکلی پیش آمده است!",
                          severity: "error",
                        });
                      }
                    } else {
                      dispatch(avicultureGetRequests());
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                      dispatch(
                        DRAWER({ right: false, bottom: false, content: null })
                      );
                    }
                  });
                } else {
                  dispatch(
                    avicultureNewRequest({
                      operator_key: unions?.length > 1 ? unionSelected : "",
                      poultry_hatching_key: hatchingKey,
                      quantity: formik.values.noChicken,
                      send_date: formik.values.slaughterDate,
                      chicken_breed: chickenBreed,
                      Index_weight: formik.values.weight,
                      losses:
                        formik.values.losses !== "" ? formik.values.losses : 0,
                      auction_list: [],
                      cash: formik.values.sellType.cash,
                      credit: formik.values.sellType.haveTime,
                      kill_house_list: formik.values.selectedSlaughters,
                      buyer: null,
                    })
                  )
                    .then((r) => {
                      dispatch(LOADING_END());
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: r.payload.error.response.data.result,
                          severity: "error",
                        });
                        return;
                      }
                      if (r.error) {
                        if (r.error.message.includes("403")) {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "تعداد مرغ برای کشتار از باقیمانده بیشتر است!",
                            severity: "error",
                          });
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "مشکلی پیش آمده است!",
                            severity: "error",
                          });
                        }
                      } else {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                        dispatch(avicultureGetRequests());
                        dispatch(
                          DRAWER({ right: false, bottom: false, content: null })
                        );
                      }
                    })
                    .catch((e) => console.log(e, "ooooo"));
                }
              }}
              size="large"
              variant="contained"
            >
              ثبت درخواست
            </Button>
          </Grid>
        </Grid>
      )}
    </Grid>
  );
};
