import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Autocomplete,
  Button,
  FormControl,
  FormControlLabel,
  InputAdornment,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { slaughterGetProductsService } from "../../services/slaughter-inventory-gets";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import {
  slaughterAllocateStewardService,
  slaughterEditAllocateStewardService,
} from "../../services/slaughter-allocate-steward";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import {
  slaughterGetColdHousesForAllocateService,
  slaughterGetGuildsForAllocateService,
} from "../../services/slaughter-get-guilds-for-allocate";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { provincePolicyGetUploadImageService } from "../../../province/services/province-policy-upload-image";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterAllocateToColdHouse = ({
  item,
  key,
  sellerType,
  fetchData,
  buyerType,
  allocationType,
  sellType,
  updateTable,
  fetchApiData,
  editData,
  priceInfo,
  coldHouseKey,
  coldHouseItemKey,
  remainWeight,
  killHouseAllocation,
}) => {
  const dispatch = useDispatch();
  const [productData, setProductData] = useState([]);
  const [guildsData, setGuildsData] = useState([]);
  const [coldHouseData, setColdHouseData] = useState([]);
  const [productKey, setProductKey] = useState(null);
  const [openNotif] = useContext(AppContext);
  const [sellGovernmental, setSellGovernmental] = useState(
    priceInfo?.active ? "true" : "false"
  );
  const [profileImages, setProfileImages] = useState(
    editData?.image ? [{ data_url: editData.image }] : []
  );
  const [value, setValue] = useState("own");
  const [imageUploadLimit, setImageUploadLimit] = useState(1);
  const [imageChanged, setImageChanged] = useState(false);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const handleChange = (event) => {
    setValue(event.target.value);
    setBuyerData({
      key: "",
      item: "",
      buyerType: "",
      allocationType: "",
    });
  };

  const handleChangeSellGovernmental = (event) => {
    setSellGovernmental(event.target.value);
    if (event.target.value === "false") {
      formik.setFieldValue("price", "");
    }
  };

  const [buyerData, setBuyerData] = useState({
    key,
    item,
    buyerType,
    allocationType,
  });

  useEffect(() => {
    if (getRoleFromUrl() === "Steward") {
      setValue("free");
    }
  }, []);

  useEffect(() => {
    dispatch(provincePolicyGetUploadImageService()).then((r) => {
      if (r.payload?.data) {
        setImageUploadLimit(r.payload.data.killHouseAllocation);
      }
    });

    if (!editData) {
      dispatch(
        slaughterGetProductsService({
          role_key: checkPathStartsWith("slaughter")
            ? selectedSubUser?.key || ""
            : "",
        })
      ).then((r) => {
        setProductData(r.payload.data);
      });
      if (!item) {
        if (value === "cold") {
          dispatch(
            slaughterGetColdHousesForAllocateService({
              role_key: checkPathStartsWith("slaughter")
                ? selectedSubUser?.key || ""
                : "",
            })
          ).then((r) => {
            setColdHouseData(r.payload.data);
          });
        }
        dispatch(
          slaughterGetGuildsForAllocateService({
            free: value === "free" ? true : false,
            role_key: checkPathStartsWith("slaughter")
              ? selectedSubUser?.key || ""
              : "",
          })
        ).then((r) => {
          setGuildsData(r.payload.data);
        });
      }
    }
  }, [dispatch, value, selectedSubUser?.key]);

  const validationSchema = Yup.object({
    weight: Yup.number()
      .required("این فیلد اجباری است!")
      .min(1, "یک مقدار مثبت وارد کنید!")
      .max(
        editData
          ? remainWeight + editData?.realWeightOfCarcasses
          : remainWeight,
        "وزن وارد شده بیش از موجودی انبار است!"
      ),
    price: Yup.number()
      .required("این فیلد اجباری است!")
      .min(1, "یک مقدار مثبت وارد کنید!"),
    wholePrice: Yup.number()
      .required("این فیلد اجباری است!")
      .min(1, "یک مقدار مثبت وارد کنید!"),
    ...(killHouseAllocation && {
      image: Yup.string().when([], {
        is: () => (!editData || imageChanged) && imageUploadLimit > 0,
        then: Yup.string().required("عکس الزامی است"),
        otherwise: Yup.string().notRequired(),
      }),
    }),
  });

  const factorPaymentHandler = (imageList) => {
    if (imageList[0]) {
      formik.setFieldValue("image", fixBase64(imageList[0]?.data_url));
      setImageChanged(true);
    } else {
      formik.setFieldValue("image", "");
      setImageChanged(true);
    }
    setProfileImages(imageList);
  };

  const formik = useFormik({
    initialValues: {
      weight: editData?.realWeightOfCarcasses || "",
      wholePrice: editData?.totalAmount || "",
      price: editData?.amount || "",
      image: editData?.image || "",
    },
    validationSchema,
  });

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

  useEffect(() => {
    if (sellGovernmental === "false") {
      if (formik.values.weight && formik.values.price) {
        formik.setFieldValue(
          "wholePrice",
          formik.values.price * formik.values.weight
        );
      }
    } else {
      if (priceInfo?.active && formik.values.weight) {
        formik.setFieldValue(
          "wholePrice",
          priceInfo?.killHousePrice * formik.values.weight
        );
      }
    }
  }, [formik.values.price, formik.values.weight, sellGovernmental]);

  useEffect(() => {
    if (priceInfo?.active && sellGovernmental === "true") {
      formik.setFieldValue("price", priceInfo?.killHousePrice);
    }
  }, [sellGovernmental]);

  const successSubmit = () => {
    dispatch(CLOSE_MODAL());
    openNotif({
      vertical: "top",
      horizontal: "center",
      msg: "عملیات با موفقیت انجام شد.",
      severity: "success",
    });
    dispatch(
      fetchSlaughterBroadcastAndProducts({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );

    fetchApiData && fetchApiData(1);
    updateTable && updateTable();
    fetchData && fetchData(1);
  };

  const [selectedDate1, setSelectedDate1] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );

  return (
    <Grid
      container
      xs={12}
      direction="column"
      justifyContent="center"
      alignItems="center"
      gap={1}
    >
      {!editData && (
        <DatePicker
          label="تاریخ"
          id="date"
          renderInput={(params) => <TextField fullWidth {...params} />}
          value={selectedDate1}
          onChange={(e) => {
            setSelectedDate1(moment(e).format("YYYY-MM-DD"));
          }}
        />
      )}

      {!editData && !coldHouseKey && (
        <Grid xs={12} container>
          <Autocomplete
            fullWidth
            style={{ minWidth: 210 }}
            disablePortal
            id="hatching"
            options={
              productData
                ? productData.map((i) => {
                    return {
                      data: i,
                      label: `${i.name}`,
                    };
                  })
                : []
            }
            onChange={(event, value) => {
              setProductKey(value.data);
            }}
            renderInput={(params) => (
              <TextField fullWidth {...params} label="انتخاب محصول" />
            )}
          />
        </Grid>
      )}

      {!editData && (
        <FormControl>
          <RadioGroup
            row
            aria-labelledby="demo-controlled-radio-buttons-group"
            name="controlled-radio-buttons-group"
            value={value}
            onChange={handleChange}
          >
            <FormControlLabel
              value="own"
              control={<Radio />}
              label="صنوف اختصاصی"
            />
            <FormControlLabel
              value="free"
              control={<Radio />}
              label="صنوف آزاد"
            />
            <FormControlLabel
              value="cold"
              control={<Radio />}
              label="انتقال به سردخانه"
            />
          </RadioGroup>
        </FormControl>
      )}

      {!item && !editData && value !== "cold" && (
        <Grid xs={12} container>
          <Autocomplete
            fullWidth
            style={{ minWidth: 210 }}
            disablePortal
            id="hatching"
            options={
              guildsData
                ? guildsData.map((i) => {
                    return {
                      data: i,
                      label: `${i?.steward ? "مباشر" : "صنف"} ${
                        i?.guildsName
                      } ${i?.user?.fullname} (${i?.user?.mobile})`,
                    };
                  })
                : []
            }
            onChange={(event, value) => {
              setBuyerData({
                item: value?.data,
                key: value?.data?.key,
                allocationType: value?.data?.steward
                  ? "killhouse_steward"
                  : "killhouse_guild",
                buyerType: value?.data?.steward ? "Steward" : "Guild",
              });
            }}
            renderInput={(params) => (
              <TextField fullWidth {...params} label="انتخاب مباشر / صنف" />
            )}
          />
        </Grid>
      )}

      {!item && !editData && value === "cold" && (
        <Grid xs={12} container>
          <Autocomplete
            fullWidth
            style={{ minWidth: 210 }}
            disablePortal
            id="hatching"
            options={
              coldHouseData
                ? coldHouseData.map((i) => {
                    return {
                      data: i,
                      label: `سردخانه ${i?.name} (${
                        i?.steward?.user?.mobile ||
                        i?.killHouse?.killHouseOperator?.user?.mobile
                      })`,
                    };
                  })
                : []
            }
            onChange={(event, value) => {
              setBuyerData({
                item: value?.data,
                key: value?.data?.key,
                allocationType: "ColdHouse",
                buyerType: "ColdHouse",
              });
            }}
            renderInput={(params) => (
              <TextField fullWidth {...params} label="انتخاب سردخانه" />
            )}
          />
        </Grid>
      )}
      <NumberInput
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        id="weight"
        label="وزن لاشه"
        variant="outlined"
        value={formik.values.weight}
        error={
          (formik.touched.weight && Boolean(formik.errors.weight)) ||
          remainWeight <= 0
        }
        helperText={
          remainWeight <= 0
            ? "موجودی انبار کافی نیست"
            : formik.touched.weight && formik.errors.weight
        }
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        disabled={remainWeight < 1}
        sx={{
          "& .MuiFormHelperText-root": {
            color:
              remainWeight && formik.values.weight > remainWeight
                ? "error.main"
                : undefined,
          },
        }}
      />

      {priceInfo?.active && (
        <FormControl>
          <RadioGroup
            row
            aria-labelledby="demo-controlled-radio-buttons-group"
            name="controlled-radio-buttons-group"
            value={sellGovernmental}
            onChange={handleChangeSellGovernmental}
          >
            <FormControlLabel
              value="true"
              control={<Radio />}
              label="قیمت مصوب"
            />
            <FormControlLabel
              value="false"
              control={<Radio />}
              label="قیمت آزاد"
            />
          </RadioGroup>
        </FormControl>
      )}

      <NumberInput
        disabled={priceInfo?.active && sellGovernmental === "true"}
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        id="price"
        label="قیمت هر کیلوگرم"
        variant="outlined"
        InputProps={{
          endAdornment: <InputAdornment position="start">ریال</InputAdornment>,
        }}
        value={formik.values.price}
        error={formik.touched.price ? Boolean(formik.errors.price) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.price && Boolean(formik.errors.price)
            ? formik.errors.price
            : null
        }
      />

      <NumberInput
        disabled
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        id="wholePrice"
        label="هزینه کل"
        variant="outlined"
        InputProps={{
          endAdornment: <InputAdornment position="start">ریال</InputAdornment>,
        }}
        value={formik.values.wholePrice}
        error={
          formik.touched.wholePrice ? Boolean(formik.errors.wholePrice) : null
        }
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.wholePrice && Boolean(formik.errors.wholePrice)
            ? formik.errors.wholePrice
            : null
        }
      />
      {(killHouseAllocation || (editData && editData.image)) && (
        <>
          <ImageUpload
            onChange={factorPaymentHandler}
            images={profileImages}
            maxNumber={1}
            title={"بارگزاری سند"}
          />
          {formik.touched.image && Boolean(formik.errors.image) && (
            <Typography color="error">ثبت تصویر الزامی است</Typography>
          )}
        </>
      )}
      <Button
        variant="contained"
        fullWidth
        disabled={
          editData
            ? !formik.isValid
            : !formik.isValid ||
              (coldHouseKey ? false : !productKey) ||
              !buyerData?.item?.key
        }
        onClick={() => {
          let req = {};
          if (coldHouseItemKey) {
            req = {
              allocation_key: coldHouseItemKey,
              number_of_carcasses: 0,
              weight_of_carcasses: formik.values.weight,
              amount: formik.values.price,
              total_amount: formik.values.wholePrice,
              ...(imageChanged && { image: formik.values.image }),
            };
          } else if (!editData) {
            req = {
              seller_type: sellerType,
              buyer_type: buyerData?.buyerType,
              other_cold_house_key:
                buyerData?.buyerType === "ColdHouse"
                  ? buyerData?.item?.key
                  : null,
              guild_key:
                buyerData?.buyerType === "Guild" ? buyerData?.item?.key : null,
              steward_key:
                buyerData?.buyerType === "Steward"
                  ? buyerData?.item?.key
                  : null,
              kill_house_key:
                buyerData?.buyerType === "KillHouse"
                  ? buyerData?.item?.key
                  : null,
              cold_house_key: coldHouseKey || null,
              product_key: coldHouseKey ? null : productKey.key,
              type: "manual",
              allocation_type: buyerData?.allocationType,
              number_of_carcasses: 0,
              weight_of_carcasses: formik.values.weight,
              sell_type: value === "cold" ? "free" : sellType,
              amount: formik.values.price,
              total_amount: formik.values.wholePrice,
              approved_price_status: sellGovernmental === "true" ? true : false,
              date: selectedDate1,
              ...(profileImages.length > 0 && { image: formik.values.image }),
            };
            req = Object.fromEntries(
              Object.entries(req).filter(([_, value]) => value !== null)
            );
          } else {
            req = {
              allocation_key: editData?.key,
              number_of_carcasses: 0,
              weight_of_carcasses: formik.values.weight,
              amount: formik.values.price,
              total_amount: formik.values.wholePrice,
              ...(imageChanged && { image: formik.values.image }),
            };
          }

          if (!editData) {
            dispatch(slaughterAllocateStewardService(req)).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                successSubmit();
              }
            });
          } else {
            dispatch(slaughterEditAllocateStewardService(req)).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                successSubmit();
              }
            });
          }
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
