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

export const ProvinceDispenserEditToGuild = ({
  item,
  key,
  sellerType,
  buyerType,
  allocationType,
  sellType,
  fetchApiData,
  editData,
  priceInfo,
  coldHouseKey,
  coldHouseItemKey,
  remainWeight,
  fetchDashboardData,
}) => {
  const dispatch = useDispatch();
  const [productData, setProductData] = useState([]);
  const [guildsData, setGuildsData] = useState([]);
  const [productKey, setProductKey] = useState(null);
  const [openNotif] = useContext(AppContext);

  const [value, setValue] = useState("own");

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

  const [sellGovernmental, setSellGovernmental] = useState(
    priceInfo?.active ? "true" : "false"
  );

  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(() => {
    if (!editData) {
      dispatch(slaughterGetProductsService()).then((r) => {
        setProductData(r.payload.data);
      });
      if (!item) {
        dispatch(
          slaughterGetGuildsForAllocateService({
            free: value === "free" ? true : false,
          })
        ).then((r) => {
          setGuildsData(r.payload.data);
        });
      }
    }
  }, [dispatch, value]);

  const validationSchema = Yup.object({
    weight: Yup.number()
      .required("این فیلد اجباری است!")
      .min(1, "یک مقدار مثبت وارد کنید!"),
    price: Yup.number()
      .required("این فیلد اجباری است!")
      .min(1, "یک مقدار مثبت وارد کنید!"),
    wholePrice: Yup.number()
      .required("این فیلد اجباری است!")
      .min(1, "یک مقدار مثبت وارد کنید!"),
  });

  const formik = useFormik({
    initialValues: {
      weight: editData?.realWeightOfCarcasses || "",
      wholePrice: editData?.totalAmount || "",
      price: editData?.amount || "",
    },
    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());
    fetchDashboardData();
    fetchApiData(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="صنوف آزاد"
            />
          </RadioGroup>
        </FormControl>
      )}

      {!item && !editData && (
        <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>
      )}
      <NumberInput
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        id="weight"
        label="وزن لاشه"
        variant="outlined"
        value={formik.values.weight}
        error={formik.touched.weight && Boolean(formik.errors.weight)}
        helperText={formik.touched.weight && formik.errors.weight}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
      />

      {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
        }
      />

      <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,
            };
          } else if (!editData) {
            req = {
              seller_type: sellerType,
              buyer_type: buyerData?.buyerType,
              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: coldHouseKey
                ? "ColdHouse"
                : buyerData?.allocationType,
              number_of_carcasses: 0,
              weight_of_carcasses: formik.values.weight,
              sell_type: sellType,
              amount: formik.values.price,
              total_amount: formik.values.wholePrice,
              approved_price_status: sellGovernmental === "true" ? true : false,
              date: selectedDate1,
            };
            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,
            };
          }

          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>
  );
};
