import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  Divider,
  InputAdornment,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { PropTypes } from "prop-types";
import { Timer } from "../../../../components/timer/Timer";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import { AuctionOfferPrice } from "../../services/auction-offer-price";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { auctionGetAuctions } from "../../services/auction-get-auctions";
import { auctionSlaughterRequests } from "../../services/auction-slaughter-requests";

export const AuctionOfferPriceForm = ({
  data,
  floorPrice,
  ceilingPrice,
  highestBidedPrice,
  auctionRemainedSeconds,
}) => {
  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      offer: "",
    },
    validationSchema: Yup.object({
      offer: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
    }),
  });

  return (
    <Grid
      container
      gap={SPACING.TINY}
      direction="column"
      flex="1"
      height="100%"
      justifyContent="space-between"
    >
      <Grid container direction="column" gap={SPACING.TINY}>
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            مانده تا پایان مناقصه :
          </Typography>
          <Timer key={"auctiontimer"} seconds={auctionRemainedSeconds} />
        </Grid>
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            استان :
          </Typography>
          <Typography variant="body2">
            {data?.poultry?.address?.province?.name || ""}
          </Typography>
        </Grid>
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            شهر :
          </Typography>
          <Typography variant="body2">
            {data?.poultry?.address?.city?.name || ""}
          </Typography>
        </Grid>
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            مرغدار :
          </Typography>
          <Typography variant="body2">
            {data?.poultry?.userprofile?.fullName || ""}
          </Typography>
        </Grid>
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            محل پرورش :
          </Typography>
          <Typography variant="body2">
            {data?.poultry?.address?.address || ""}
          </Typography>
        </Grid>
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            نژاد :
          </Typography>
          <Typography variant="body2">{data?.chickenBreed || ""}</Typography>
        </Grid>
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            تعداد :
          </Typography>
          <Typography variant="body2" mr={SPACING.TINY}>
            {data?.quantity || 0}
          </Typography>
          قطعه
        </Grid>
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            سن :
          </Typography>
          <Typography variant="body2">
            {data?.process?.poultry?.age || 0} روز
          </Typography>
        </Grid>
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            وزن :
          </Typography>
          <Typography variant="body2">
            {data?.IndexWeight || 0} کیلوگرم
          </Typography>
        </Grid>
        <Divider />
        <Grid
          container
          gap={SPACING.SMALL}
          direction="column"
          flex="1"
          height="100%"
          justifyContent="space-between"
        >
          <Grid display="flex">
            <Typography
              variant="body1"
              mr={SPACING.TINY}
              color={(prop) => prop.palette.grey["A700"]}
            >
              قیمت پایه :
            </Typography>
            <Typography mr={SPACING.TINY} fontWeight="bold">
              {floorPrice || 0}
            </Typography>
            ریال
          </Grid>

          <Grid display="flex">
            <Typography
              variant="body1"
              mr={SPACING.TINY}
              color={(prop) => prop.palette.grey["A700"]}
            >
              بالاترین قیمت پیشنهادی :
            </Typography>
            <Typography mr={SPACING.TINY} fontWeight="bold">
              {highestBidedPrice || "پیشنهادی وجود ندارد!"}
            </Typography>
            {highestBidedPrice === "پیشنهادی وجود ندارد!" || !highestBidedPrice
              ? ""
              : "ریال"}
          </Grid>
        </Grid>

        <Grid mt={SPACING.SMALL}>
          <TextField
            id="offer"
            label="قیمت پیشنهادی"
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">ریال</InputAdornment>
              ),
            }}
            variant="outlined"
            sx={{ width: "100%" }}
            value={formik.values.offer}
            error={formik.touched.offer ? Boolean(formik.errors.offer) : null}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.offer && Boolean(formik.errors.offer)
                ? formik.errors.offer
                : null
            }
          />
        </Grid>
        <Grid mt={SPACING.SMALL}>
          <Button
            disabled={!formik.isValid}
            fullWidth
            variant="contained"
            onClick={() => {
              dispatch(LOADING_START());
              const offerValue = Number(formik.values.offer) || 0;
              const floorPriceNum = Number(floorPrice) || 0;
              const ceilingPriceNum = Number(ceilingPrice) || 0;
              const highestBidedPriceNum =
                highestBidedPrice === "پیشنهادی وجود ندارد!" ||
                !highestBidedPrice
                  ? 0
                  : Number(highestBidedPrice) || 0;

              if (
                (highestBidedPrice === "پیشنهادی وجود ندارد!" ||
                  !highestBidedPrice ||
                  (offerValue - highestBidedPriceNum >= 1000 &&
                    offerValue > floorPriceNum &&
                    offerValue <= ceilingPriceNum)) &&
                data?.key
              ) {
                dispatch(
                  AuctionOfferPrice({
                    key: data.key,
                    fee: offerValue,
                  })
                )
                  .then((r) => {
                    if (r?.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "مشکلی پیش آمده است!",
                        severity: "error",
                      });
                    } else {
                      dispatch(auctionGetAuctions());
                      dispatch(auctionSlaughterRequests());
                      dispatch(
                        DRAWER({ right: false, bottom: false, content: null })
                      );
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  })
                  .catch((error) => {
                    console.error("Error submitting offer:", error);
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "مشکلی پیش آمده است!",
                      severity: "error",
                    });
                  })
                  .finally(() => {
                    dispatch(LOADING_END());
                  });
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "قیمت پیشنهادی باید از بیشترین قیمت پیشنهاد شده بیشتر باشد و از حداکثر قیمت روز کمتر باشد.",
                  severity: "error",
                });
                dispatch(LOADING_END());
              }
            }}
          >
            ثبت اطلاعات
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
};

AuctionOfferPriceForm.propTypes = {
  data: PropTypes.any,
  floorPrice: PropTypes.string,
  ceilingPrice: PropTypes.string,
  highestBidedPrice: PropTypes.string,
  auctionRemainedSeconds: PropTypes.string,
};
