import {
  Autocomplete,
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  FormLabel,
  IconButton,
  InputAdornment,
  Radio,
  RadioGroup,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { DatePicker } from "@mui/x-date-pickers";
import { useFormik } from "formik";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { Yup } from "../../../../lib/yup/yup";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterGetKillerKillhousesService } from "../../../slaughter-house/services/slaughter-get-killers-killhouses";
import { slaughterGetPoultriesService } from "../../services/salughter-get-poultries";
import { slaughterEditFreeBuyService } from "../../services/slaughter-edit-free-buy";
import { slaughterGetProfile } from "../../services/slaughter-get-profile";
import { slaughterSubmitFreeBuyPostService } from "../../services/slaughter-submit-free-buy-post";
import { slaughterGetKillhousesService } from "../../services/slaughter-get-killhouses";
import { getApprovedPriceState } from "../../../province/services/get-approved-price-state";
import { paymentGetDeadLines } from "../../services/payment-get-deadlines";
import { avicultureGetHatchingData } from "../../../aviculture/services/aviculture-get-hatching-data";
import { provincePolicyValidatePoultryWithSmsStatusService } from "../../../province/services/province-policy-validate-poultry-wth-sms-service";
import FilterAltIcon from "@mui/icons-material/FilterAlt";
import { provincePolicyGetWeightRange } from "../../../province/services/province-policy-get-weight-range";
import { isValidIndexWeight } from "../../../../utils/isValidIndexWeight";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
import { provinceGetSellForFreezingStatus } from "../../../province/services/province-get-sell-for-freezing-status";

export const SlaughterSubmitFreeBuy = ({ edit, updateTable }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [maxAllowed, setMaxAllowed] = useState(false);
  const [selectedAge1, setSelectedAge1] = useState(1);
  const [selectedAge2, setSelectedAge2] = useState(1);
  const [showSearchFields, setShowSearchFields] = useState(false);
  const [editPoultry, setEditPoultry] = useState(false);
  const [sellForFreezing, setSellForFreezing] = useState(false);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const { slaughterGetPoultries, slaughterGetKillerKillhouses } = useSelector(
    (state) => state.slaughterSlice
  );

  const { weightRange } = useSelector((state) => state.provinceSlice);

  const [poultryData, setPoultryData] = useState("");
  const [selectedPolutry, setSelectedPolutry] = useState("");
  const [paymentDeadlineDays, setPaymentDeadlineDays] = useState(null);

  const [submitStatus, SetSubmitStatus] = useState(false);
  const fetchData = () => {
    dispatch(
      provincePolicyValidatePoultryWithSmsStatusService({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      SetSubmitStatus(r.payload.data.poultryStatus);
    });
  };

  useEffect(() => {
    dispatch(
      slaughterGetProfile({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
    dispatch(
      slaughterGetKillhousesService({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
    dispatch(
      slaughterGetPoultriesService({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
    dispatch(
      slaughterGetKillerKillhousesService({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
    dispatch(
      provincePolicyGetWeightRange({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
    dispatch(provinceGetSellForFreezingStatus()).then((r) => {
      setSellForFreezing(r.payload.data.permission);
    });
    fetchData();
  }, [selectedSubUser?.key]);

  const [value, setValue] = useState(edit ? edit?.freeDirectBuying : true);

  const handleChange = (event) => {
    setValue(event.target.value === "true" ? true : false);
  };

  const initialValues = {
    killhouse: edit ? edit.killHouse.key : selectedSubUser?.key,
    killerPlace: edit?.slaughterHouse?.key || null,
    poultry: edit ? edit.poultry.key : null,
    killDate: edit ? new Date(edit.reciveDate) : new Date(),
    numberForBuy: edit ? edit.killCapacity : null,
    indexWeight: edit ? edit.IndexWeight : "",
    avicultureSellType: "goverment",
    poultryPrice: edit ? edit.amount : 0,
    hatching_key: edit?.poultryHatching?.key || null,
    paymentDeadlineDays: edit?.paymentDeadlineDays?.key,
    freezing: false,
  };
  const onSubmit = (values) => {
    if (!paymentDeadlineDays && values.paymentDeadlineDays === 0) {
      return;
    }

    if (
      getRoleFromUrl() !== "SuperAdmin" &&
      getRoleFromUrl() !== "AdminX" &&
      !isValidIndexWeight(weightRange, selectedPolutry?.age, values.indexWeight)
    ) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "میانگین وزنی با احراز سنی مطابقت ندارد. لطفا با اتحادیه تماس بگیرید.",
        severity: "error",
      });
    } else {
      dispatch(
        slaughterSubmitFreeBuyPostService({
          kill_capacity: values.numberForBuy,
          ...(editPoultry
            ? {
                direct_buying_intermediary_mobile:
                  formik2.values.intermediaryMobile,
              }
            : {}),
          recive_time: "12 - 14",
          recive_date: values.killDate,
          low_weight: false,
          high_weight: false,
          Index_weight: values.indexWeight,
          chicken_breed: selectedPolutry?.chickenBreed,
          cash: true,
          credit: false,
          freezing: values.freezing,
          sms_payment: false,
          kill_house_key: values.killhouse,
          killer_kill_house_key: values.killerPlace ? values.killerPlace : null,
          role: getRoleFromUrl(),
          poultry_key: formik.values.poultry,
          free_direct_buying: value,

          amount:
            data?.approved &&
            !value &&
            !(
              data?.lowestPrice === 0 &&
              data?.highestPrice === 0 &&
              data?.lowestWeight === 0 &&
              data?.highestWeight === 0
            )
              ? Math.round(approvedPrice)
              : Number(values.poultryPrice),

          hatching_key: formik.values.hatching_key,
          payment_deadline_days: formik?.values?.paymentDeadlineDays,
          confirm_poultry_mobile: formik2.values.userInfoCheck,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",

            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          updateTable();
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          dispatch(
            DRAWER({
              right: false,
              bottom: false,
              left: false,
              content: null,
            })
          );
        }
      });
    }
  };

  const validationSchema = Yup.object().shape({
    killhouse: Yup.string("")
      .typeError("این فیلد الزامی است")
      .required("این فیلد الزامی است"),
    poultry: Yup.string("")
      .typeError("این فیلد الزامی است")
      .required("این فیلد الزامی است"),
    numberForBuy: Yup.number()
      .typeError("لطفا عدد وارد کنید")
      .max(edit ? Infinity : maxAllowed, "تعداد بیش از حد مجاز است")
      .required("لطفا عدد وارد کنید")
      .positive("لطفا عدد وارد کنید")
      .integer("لطفا عدد وارد کنید"),
    indexWeight: Yup.number()
      .typeError("لطفا عدد وارد کنید")
      .required("لطفا عدد وارد کنید")
      .positive("لطفا عدد وارد کنید"),
    poultryPrice: Yup.number()
      .typeError("لطفا فیلد را به درستی وارد کنید!")
      .min(value ? 400000 : 0, "حداقل قیمت پایه ۴۰۰,۰۰۰ ریال ")
      .required("این فیلد اجباری است"),

    hatching_key: Yup.string().required("این فیلد الزامی است"),
    paymentDeadlineDays: Yup.number().when([], {
      is: () => paymentDeadlineDays !== null,
      then: Yup.number()
        .required("این فیلد الزامی است")
        .min(1, "حداقل مقدار باید 1 باشد")
        .max(
          paymentDeadlineDays,
          `حداکثر مقدار باید ${paymentDeadlineDays} باشد`
        ),
      otherwise: Yup.number().notRequired(),
    }),
  });

  const formik = useFormik({
    initialValues,
    validationSchema,
    onSubmit,
  });

  const formik2 = useFormik({
    initialValues: {
      userInfoCheck: "",
      intermediaryMobile: "",
    },
    validationSchema: Yup.object({
      userInfoCheck: Yup.string()
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^0\d{10}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
      intermediaryMobile: Yup.string()
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^0\d{10}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
    }),
  });

  useEffect(() => {
    if (formik.values.poultry) {
      dispatch(
        avicultureGetHatchingData({
          key: formik.values.poultry,
        })
      ).then((r) => {
        setPoultryData(r.payload.data);
      });
    }
  }, [formik.values.poultry, selectedSubUser?.key]);

  useEffect(() => {
    let newVal = formik.values.indexWeight;
    const mystring = formik.values?.indexWeight
      ?.toString()
      ?.split(".")
      ?.join("");
    if (formik.values.indexWeight) {
      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("indexWeight", "");
    } else {
      formik.setFieldValue("indexWeight", Number.parseFloat(newVal));
    }
  }, [formik.values.indexWeight]);

  const handleSubmitSearchByAge = async (event) => {
    event.preventDefault();

    dispatch(
      slaughterGetPoultriesService({
        min_age: selectedAge1 ? selectedAge1 : 1,
        max_age: selectedAge2 ? selectedAge2 : 1,
      })
    );
  };
  const handleSubmitSearchNoAge = async (event) => {
    event.preventDefault();
    setSelectedAge1(1);
    setSelectedAge2(1);
    dispatch(slaughterGetPoultriesService());
  };

  useEffect(() => {
    if (value === true) {
      setMaxAllowed(
        selectedPolutry.freeGovernmentalInfo?.leftTotalFreeCommitmentQuantity
      );
    } else {
      setMaxAllowed(selectedPolutry.leftOver);
    }
    setTimeout(() => {
      formik.validateField("numberForBuy");
    }, 1);
  }, [value]);

  const [data, setData] = useState();
  const [approvedPrice, setApprovedPrice] = useState();

  useEffect(() => {
    dispatch(
      getApprovedPriceState({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      setData(r.payload.data);
      if (r.payload.data?.approved === false) {
        formik.setFieldValue("avicultureSellType", "freePrice");
      }
      // Check if approved is true but all price/weight fields are zero
      if (
        r.payload.data?.approved === true &&
        r.payload.data?.lowestPrice === 0 &&
        r.payload.data?.highestPrice === 0 &&
        r.payload.data?.lowestWeight === 0 &&
        r.payload.data?.highestWeight === 0
      ) {
        setValue(false); // Set to "دولتی"
      }
    });
  }, [selectedSubUser?.key]);

  useEffect(() => {
    dispatch(
      paymentGetDeadLines({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      const isEnabled = r?.payload?.data?.paymentDeadline;

      const days = r?.payload?.data?.paymentDeadlineDays;

      if (isEnabled === true && days > 0) {
        setPaymentDeadlineDays(days);
      }
    });
  }, [selectedSubUser?.key]);

  useEffect(() => {
    if (
      data?.approved &&
      !(
        data?.lowestPrice === 0 &&
        data?.highestPrice === 0 &&
        data?.lowestWeight === 0 &&
        data?.highestWeight === 0
      )
    ) {
      if (formik.values.indexWeight * 1000 <= data?.lowestWeight) {
        setApprovedPrice(data?.lowestPrice);
      } else if (formik.values.indexWeight * 1000 >= data?.highestWeight) {
        setApprovedPrice(data?.highestPrice);
      } else {
        const diffWeight = data?.highestWeight - data?.lowestWeight;
        const diffPrice = data?.highestPrice - data?.lowestPrice;
        const fraction = diffPrice / diffWeight;
        const diffFromMinWeight =
          formik.values.indexWeight * 1000 - data?.lowestWeight;
        setApprovedPrice(diffFromMinWeight * fraction + data?.lowestPrice);
        formik.setFieldValue(
          "poultryPrice",
          diffFromMinWeight * fraction + data?.lowestPrice
        );
      }
    }
  }, [formik.values.indexWeight]);

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container direction="column" gap={SPACING.TINY}>
        <>
          {/* {!edit ? (
            slaughterGetKillhouses?.length ? (
              <Autocomplete
                id="killhouse"
                disableClearable
                options={slaughterGetKillhouses?.map((item) => {
                  const buyerNamePrefix = item?.killer ? "کشتارکن" : "کشتارگاه";
                  return {
                    label: buyerNamePrefix + " " + item.name,
                    value: item.key,
                    killer: item.killer,
                    item: item,
                    disabled: item.allowDirectBuying,
                  };
                })}
                getOptionDisabled={(option) => !option.disabled}
                getOptionLabel={(option) => option.label}
                onChange={(_, value) => {
                  setIsKiller(value.killer);
                  formik.setFieldValue("killhouse", value.value);
                }}
                onBlur={formik.handleBlur}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label="انتخاب کشتارگاه/کشتارکن"
                    variant="outlined"
                    error={
                      formik.touched.killhouse &&
                      Boolean(formik.errors.killhouse)
                    }
                    helperText={
                      formik.touched.killhouse && formik.errors.killhouse
                    }
                  />
                )}
              />
            ) : (
              <CircularProgress />
            )
          ) : null} */}
          {selectedSubUser?.killer && (
            <Autocomplete
              id="killerPlace"
              disableClearable={true}
              options={slaughterGetKillerKillhouses?.map((item) => {
                return {
                  label: "کشتارگاه " + item.name,
                  value: item.key,
                };
              })}
              getOptionLabel={(option) => option.label}
              onChange={(_, value) =>
                formik.setFieldValue("killerPlace", value.value)
              }
              onBlur={formik.handleBlur}
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="انتخاب محل کشتار"
                  variant="outlined"
                  error={
                    formik.touched.killerPlace &&
                    Boolean(formik.errors.killerPlace)
                  }
                  helperText={
                    formik.touched.killerPlace && formik.errors.killerPlace
                  }
                />
              )}
            />
          )}
          {(formik.values.killhouse || formik.values.killerPlace) && (
            <>
              <Grid container alignItems="center" spacing={2}>
                {!edit && (
                  <Grid item xs={8} sm={9}>
                    <Autocomplete
                      id="poultry"
                      disableClearable
                      options={
                        slaughterGetPoultries?.map((item) => ({
                          label: `${item.unitName} (${item.user?.fullname})`,
                          value: item.key,
                          item,
                        })) || []
                      }
                      getOptionLabel={(option) => option.label}
                      onChange={(_, value) => {
                        formik.setFieldValue("poultry", value.item.key);
                        setMaxAllowed(value.item.lastHatchingRemainQuantity);
                      }}
                      onBlur={formik.handleBlur}
                      renderOption={(props, option) => {
                        const item = option.item;
                        return (
                          <li {...props} key={option.value}>
                            <Grid container direction="column">
                              <Typography
                                variant="body2"
                                sx={{ fontSize: "0.75rem" }}
                              >
                                {item?.unitName} ({item?.user?.fullname})
                              </Typography>
                              <Typography
                                variant="caption"
                                color="text.secondary"
                                sx={{ fontSize: "0.7rem" }}
                              >
                                {item?.user?.mobile || "-"} |{" "}
                                {item?.address?.city?.name || "-"}
                              </Typography>
                            </Grid>
                          </li>
                        );
                      }}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="انتخاب مرغداری"
                          variant="outlined"
                          fullWidth
                          error={
                            formik.touched.poultry &&
                            Boolean(formik.errors.poultry)
                          }
                          helperText={
                            formik.touched.poultry && formik.errors.poultry
                          }
                        />
                      )}
                    />
                  </Grid>
                )}
                {!edit && (
                  <Grid item xs={2} sm={1}>
                    <Tooltip title="جستجوی پیشرفته">
                      <IconButton
                        onClick={() => setShowSearchFields(!showSearchFields)}
                        color={showSearchFields ? "error" : "primary"}
                        size="large"
                      >
                        {showSearchFields ? <CloseIcon /> : <FilterAltIcon />}
                      </IconButton>
                    </Tooltip>
                  </Grid>
                )}
              </Grid>

              {showSearchFields && (
                <Grid container spacing={2} sm={12}>
                  <Grid item xs={6} sm={6}>
                    <TextField
                      size="small"
                      label="از سن"
                      type="number"
                      value={selectedAge1}
                      onChange={(e) => setSelectedAge1(e.target.value)}
                    />
                  </Grid>
                  <Grid item xs={6} sm={6}>
                    <TextField
                      size="small"
                      label="تا سن"
                      type="number"
                      value={selectedAge2}
                      onChange={(e) => setSelectedAge2(e.target.value)}
                    />
                  </Grid>

                  <Grid item xs={12} sm={12}>
                    <Grid
                      container
                      justifyContent="center"
                      alignItems="center"
                      spacing={1}
                    >
                      <Grid item sm={6}>
                        <Button
                          variant="contained"
                          disabled={
                            selectedAge1 > selectedAge2 ||
                            selectedAge1 < 1 ||
                            selectedAge2 < 1
                          }
                          onClick={handleSubmitSearchByAge}
                        >
                          اعمال فیلتر
                        </Button>
                      </Grid>
                      <Grid item sm={6}>
                        <Button
                          variant="outlined"
                          color="error"
                          onClick={handleSubmitSearchNoAge}
                        >
                          حذف فیلتر
                        </Button>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              )}

              {poultryData && (
                <Grid minWidth={210}>
                  {!edit && (
                    <Autocomplete
                      disablePortal
                      disabled={!formik.values.poultry}
                      id="combo-box-demo"
                      options={poultryData?.map((item) => {
                        return {
                          label: `${item?.poultry.unitName}`,
                          value: item.key,
                          item,
                        };
                      })}
                      onChange={(event, value) => {
                        setSelectedPolutry(value.item);
                        formik2.setFieldValue(
                          "userInfoCheck",
                          value.item?.poultry?.userprofile?.mobile
                        );
                        formik.setFieldValue("hatching_key", value.value);
                      }}
                      renderInput={(params) => (
                        <TextField {...params} label="محل پرورش" />
                      )}
                    />
                  )}

                  {formik.values.hatching_key && (
                    <Grid
                      container
                      direction="column"
                      gap={SPACING.SMALL}
                      mt={2}
                    >
                      {selectedPolutry && (
                        <Grid
                          container
                          direction="column"
                          justifyContent="space-between"
                        >
                          <Grid container gap={SPACING.TINY} mt={1}>
                            <Typography>نام و نام خانوادگی:</Typography>
                            <Typography>
                              {selectedPolutry?.poultry?.userprofile?.fullName}
                            </Typography>
                          </Grid>

                          <Grid
                            container
                            gap={1}
                            mt={1}
                            p={1}
                            sx={{
                              borderStyle: "solid",
                              borderRadius: "10px",
                              borderColor: "red",
                              borderWidth: "1px",
                            }}
                          >
                            <Tooltip title="ورود تلفن واقعی مرغدار جهت دریافت کد احراز">
                              <Grid
                                container
                                gap={SPACING.TINY}
                                alignItems="center"
                              >
                                <Typography>تلفن مرغدار:</Typography>
                                <Typography>
                                  {
                                    selectedPolutry?.poultry?.userprofile
                                      ?.mobile
                                  }
                                </Typography>
                              </Grid>
                            </Tooltip>

                            <Grid
                              alignItems="center"
                              xs={12}
                              container
                              justifyContent="start"
                            >
                              <Checkbox
                                sx={{ marginLeft: "-12px" }}
                                color="primary"
                                checked={editPoultry}
                                onChange={() => setEditPoultry(!editPoultry)}
                              />
                              <Typography variant="caption" color="primary">
                                تلفن واسطه جهت دریافت کد احراز
                              </Typography>
                            </Grid>

                            {editPoultry && (
                              <TextField
                                mt={2}
                                size="small"
                                fullWidth
                                id="intermediaryMobile"
                                label="تلفن واسطه"
                                variant="outlined"
                                value={formik2.values.intermediaryMobile}
                                onChange={formik2.handleChange}
                                onBlur={formik2.handleBlur}
                                error={!!formik2.errors.intermediaryMobile}
                                helperText={
                                  formik2.touched.intermediaryMobile &&
                                  Boolean(formik2.errors.intermediaryMobile)
                                    ? formik2.errors.intermediaryMobile
                                    : null
                                }
                              />
                            )}
                          </Grid>
                          <Grid container gap={SPACING.TINY} mt={1}>
                            <Typography>آدرس:</Typography>
                            <Typography>
                              {`شهر ${
                                selectedPolutry.poultry?.address?.city?.name
                              }  ${
                                selectedPolutry?.poultry?.address?.address
                                  ? "-" +
                                    selectedPolutry?.poultry?.address?.address
                                  : ""
                              }`}
                            </Typography>
                          </Grid>
                          <Grid container gap={SPACING.TINY} mt={1}>
                            <Typography>سن جوجه:</Typography>
                            <Typography>
                              {selectedPolutry?.chickenAge} روز
                            </Typography>
                          </Grid>
                          <Grid container gap={SPACING.TINY} mt={1}>
                            <Typography>مانده در سالن:</Typography>
                            <Typography>
                              {selectedPolutry?.leftOver?.toLocaleString()}
                              قطعه
                            </Typography>
                          </Grid>
                          <Grid container gap={SPACING.TINY} mt={1}>
                            <Typography color="error">
                              مانده فروش آزاد:
                            </Typography>
                            <Typography color="error">
                              {selectedPolutry?.freeGovernmentalInfo?.leftTotalFreeCommitmentQuantity?.toLocaleString()}{" "}
                              قطعه
                            </Typography>
                          </Grid>
                          <Grid container gap={SPACING.TINY} mt={1}>
                            <Typography>نژاد:</Typography>
                            <Typography>
                              {selectedPolutry?.chickenBreed}
                            </Typography>
                          </Grid>
                        </Grid>
                      )}
                      {submitStatus &&
                        selectedPolutry &&
                        getRoleFromUrl() !== "KillHouse" && (
                          <TextField
                            fullWidth
                            id="userInfoCheck"
                            label="ویرایش تلفن مرغدار"
                            variant="outlined"
                            value={formik2.values.userInfoCheck}
                            error={
                              formik2.touched.city
                                ? Boolean(formik2.errors.userInfoCheck)
                                : null
                            }
                            onChange={formik2.handleChange}
                            onBlur={formik2.handleBlur}
                            helperText={
                              formik2.touched.userInfoCheck &&
                              Boolean(formik2.errors.userInfoCheck)
                                ? formik2.errors.userInfoCheck
                                : null
                            }
                          />
                        )}
                      {submitStatus &&
                        selectedPolutry &&
                        getRoleFromUrl() !== "KillHouse" && (
                          <Typography variant="caption" color="error">
                            احراز پیامکی قیمت مرغدار در استان فعال است. در صورت
                            ویرایش، تلفن مرغدار در سراسر سامانه با تلفن جدید
                            جایگزین میگردد!
                          </Typography>
                        )}
                      {!edit && (
                        <Grid>
                          <DatePicker
                            fullWidth
                            label="تاریخ کشتار"
                            id="killDate"
                            renderInput={(params) => <TextField {...params} />}
                            value={
                              formik.values.killDate instanceof Date
                                ? formik.values.killDate
                                : formik.values.killDate
                                ? new Date(formik.values.killDate)
                                : null
                            }
                            error={
                              formik.touched.killDate
                                ? Boolean(formik.errors.killDate)
                                : null
                            }
                            onChange={(e) => {
                              formik.setFieldValue("killDate", e);
                            }}
                            onBlur={formik.handleBlur}
                            helperText={
                              formik.touched.killDate &&
                              Boolean(formik.errors.killDate)
                                ? formik.errors.killDate
                                : null
                            }
                          />
                        </Grid>
                      )}
                      <Grid>
                        <NumberInput
                          allowLeadingZeros
                          thousandSeparator=","
                          id="numberForBuy"
                          name="numberForBuy"
                          label="حجم"
                          variant="outlined"
                          value={formik.values.numberForBuy}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          error={
                            formik.touched.numberForBuy &&
                            Boolean(formik.errors.numberForBuy)
                          }
                          helperText={
                            formik.touched.numberForBuy &&
                            formik.errors.numberForBuy
                          }
                        />
                      </Grid>
                      <Grid>
                        <TextField
                          id="indexWeight"
                          name="indexWeight"
                          label="میانگین وزنی"
                          variant="outlined"
                          value={formik.values.indexWeight}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          InputProps={{
                            endAdornment: (
                              <InputAdornment position="end">
                                کیلوگرم
                              </InputAdornment>
                            ),
                          }}
                          error={
                            formik.touched.indexWeight &&
                            Boolean(formik.errors.indexWeight)
                          }
                          helperText={
                            formik.touched.indexWeight &&
                            formik.errors.indexWeight
                          }
                        />
                      </Grid>
                      {data?.approved &&
                        !edit &&
                        !(
                          data?.lowestPrice === 0 &&
                          data?.highestPrice === 0 &&
                          data?.lowestWeight === 0 &&
                          data?.highestWeight === 0
                        ) && (
                          <Grid>
                            <FormControl>
                              <FormLabel id="demo-controlled-radio-buttons-group">
                                قیمت خرید
                              </FormLabel>
                              <RadioGroup
                                aria-labelledby="demo-controlled-radio-buttons-group"
                                name="controlled-radio-buttons-group"
                                value={value}
                                onChange={handleChange}
                              >
                                <FormControlLabel
                                  value={true}
                                  control={<Radio />}
                                  label="آزاد"
                                />
                                <FormControlLabel
                                  value={false}
                                  control={<Radio />}
                                  label="دولتی"
                                />
                              </RadioGroup>
                            </FormControl>
                          </Grid>
                        )}
                      {data?.approved &&
                        value === false &&
                        !edit &&
                        !(
                          data?.lowestPrice === 0 &&
                          data?.highestPrice === 0 &&
                          data?.lowestWeight === 0 &&
                          data?.highestWeight === 0
                        ) && (
                          <Grid>
                            <Grid
                              gap={1}
                              container
                              p={1}
                              style={{
                                borderStyle: "solid",
                                borderWidth: "1px",
                                borderColor: "red",
                                borderRadius: "5px",
                              }}
                            >
                              <Tooltip
                                title={`قیمت مصوب بر اساس قیمت مصوب کف ${data?.lowestPrice.toLocaleString()} هزار ریال و سقف ${data?.highestPrice?.toLocaleString()} هزار ریال محاسبه شده است.`}
                              >
                                <Typography variant="body1" color="secondary">
                                  قیمت مصوب:
                                </Typography>
                              </Tooltip>
                              <Typography variant="body1" color="primary">
                                {approvedPrice
                                  ? Math.round(approvedPrice)?.toLocaleString()
                                  : 0}{" "}
                                ریال
                              </Typography>
                            </Grid>
                          </Grid>
                        )}
                      {(value ||
                        (value === false &&
                          data?.approved &&
                          data?.lowestPrice === 0 &&
                          data?.highestPrice === 0 &&
                          data?.lowestWeight === 0 &&
                          data?.highestWeight === 0)) &&
                        !edit && (
                          <Grid>
                            <TextField
                              id="poultryPrice"
                              label="قیمت فروش مرغدار"
                              variant="outlined"
                              InputProps={{
                                endAdornment: (
                                  <InputAdornment position="end">
                                    ریال
                                  </InputAdornment>
                                ),
                              }}
                              value={formik.values.poultryPrice}
                              error={
                                formik.touched.poultryPrice
                                  ? Boolean(formik.errors.poultryPrice)
                                  : null
                              }
                              onChange={formik.handleChange}
                              onBlur={formik.handleBlur}
                              helperText={
                                formik.touched.poultryPrice &&
                                Boolean(formik.errors.poultryPrice)
                                  ? formik.errors.poultryPrice
                                  : null
                              }
                            />
                            {/* {!data?.approved &&
                            formik.values.avicultureSellType !==
                              "goverment" && (
                              <Typography variant="caption" color="error">
                                نوع فروش: آزاد
                              </Typography>
                            )} */}
                          </Grid>
                        )}

                      {paymentDeadlineDays && !edit && (
                        <Grid>
                          <TextField
                            id="poultryPrice"
                            label="حداکثر زمان تسویه"
                            variant="outlined"
                            InputProps={{
                              endAdornment: (
                                <InputAdornment position="end">
                                  روز
                                </InputAdornment>
                              ),
                              inputProps: {
                                min: 1,
                                max: paymentDeadlineDays,
                              },
                            }}
                            value={formik.values.paymentDeadlineDays}
                            onChange={(e) => {
                              const val = Number(e.target.value);
                              if (val <= paymentDeadlineDays) {
                                formik.setFieldValue(
                                  "paymentDeadlineDays",
                                  val
                                );
                              }
                            }}
                            onBlur={formik.handleBlur}
                            error={formik.errors.paymentDeadlineDays}
                            helperText={
                              formik.touched.paymentDeadlineDays &&
                              formik.errors.paymentDeadlineDays
                                ? formik.errors.paymentDeadlineDays
                                : paymentDeadlineDays
                                ? `حداکثر زمان مجاز ${paymentDeadlineDays} روز است`
                                : ""
                            }
                          />
                        </Grid>
                      )}
                      {sellForFreezing && (
                        <Typography variant="body2">
                          <Checkbox
                            id="freezing"
                            onChange={formik.handleChange}
                          />
                          انجماد
                        </Typography>
                      )}

                      {!edit && (
                        <Button
                          type="submit"
                          variant="contained"
                          color="primary"
                          fullWidth
                          disabled={!selectedPolutry || !formik2.isValid}
                        >
                          {getRoleFromUrl() === "KillHouse"
                            ? "ثبت اولیه"
                            : "ثبت"}
                        </Button>
                      )}
                      {edit && (
                        <Button
                          disabled={
                            !formik.values.numberForBuy ||
                            !formik.values.killDate ||
                            !formik.values.indexWeight
                          }
                          variant="contained"
                          color="primary"
                          fullWidth
                          onClick={() => {
                            dispatch(
                              slaughterEditFreeBuyService({
                                role: getRoleFromUrl(),
                                kill_capacity: formik.values.numberForBuy,
                                recive_date: formik.values.killDate,
                                Index_weight: formik.values.indexWeight,
                                kill_request_key: edit.key,
                                remain_quantity: formik.values.numberForBuy,
                                free_direct_buying: value,
                              })
                            ).then((r) => {
                              if (r?.payload?.error) {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: r?.payload?.error,
                                  severity: "error",
                                });
                              } else {
                                updateTable();
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "عملیات با موفقیت انجام شد.",
                                  severity: "success",
                                });
                                dispatch(
                                  DRAWER({
                                    right: false,
                                    bottom: false,
                                    left: false,
                                    content: null,
                                  })
                                );
                              }
                            });
                          }}
                        >
                          ثبت ویرایش
                        </Button>
                      )}
                    </Grid>
                  )}
                </Grid>
              )}
            </>
          )}
        </>
      </Grid>
    </form>
  );
};
