import { Button, Col, Row } from "antd";
import "./Order_Overview.css";
import React, { useContext, useEffect, useState } from "react";
import CheckoutStepFormContext from "../CheckoutStepFormContext";
import Green_Outline_Btn from "../../../common-components/common_btn/green_outline_btn/Green_Outline_Btn";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTags, faTrashCan } from "@fortawesome/free-solid-svg-icons";
import { Form, InputGroup, Table } from "react-bootstrap";
import Order_Overview_summery_holder from "./order_Overview_summery_holder/Order_Overview_summery_holder";
import Success_Modal from "../../../common-components/common_modal/success_modal/Success_Modal";
import Coupons_Modal from "../../../common-components/common_modal/coupons_modal/Coupons_Modal";
import { useDispatch, useSelector } from "react-redux";
import { deleteAllCart, getAllCart } from "../../../../features/cart/cartSlice";
import { useRazorpay } from "react-razorpay";
import {
  CouponApplyed,
  createOrder,
  getSingleOrderAddress,
  OrderCalculation,
} from "../../../../features/order/orderSlice";

import { useForm } from "react-hook-form";
import Delete_Modal from "../../../common-components/common_modal/delete_modal/Delete_Modal";
import Spinner from "react-bootstrap/Spinner";
import { RoleId, variant_type } from "../../../../utils/common";
import { useRouter } from "next/navigation";
import Script from "next/script";

const Order_Overview = ({ paymentValue, selectedAddressId }) => {
  const [modalDeleteShow, setModalDeleteShow] = React.useState(false);
  const [modalShow, setModalShow] = React.useState(false);
  const [showCouponModal, setShowCouponModal] = useState(false);
  const [Errors, setErrors] = React.useState(null);
  const [data, setData] = useState({});

  const { prev } = useContext(CheckoutStepFormContext);
  const navigate = useRouter();

  const handleClick = () => {
    setModalShow(true); // Show modal

    setTimeout(() => {
      setModalShow(false); // Close modal after 3s (optional)
      navigate.push("/"); // Navigate after modal
    }, 3000); // Show for 3 seconds
  };

  const currentCurrency = useSelector((state) => state.master.currentCurrency);
  const rate = Number(currentCurrency?.rate) || 1;
  const symbol = currentCurrency?.symbol || "₹";

  const [CouponData, setCouponData] = React.useState("");

  const [loader, setLoader] = useState(false);

  const isSignin = useSelector((state) => state.auth.is_signin);
  const dispatch = useDispatch();
  const allcartData = useSelector((state) => state.cart.allCarts);
  useEffect(() => {
    dispatch(getAllCart(isSignin));
  }, [dispatch]);
  const current_location = useSelector(
    (state) => state.location.current_location,
  );

  const orderCalculation = async (
    selectedAddressId,
    currentCurrency,
    current_location,
  ) => {
    setLoader(true);

    const lat =
      current_location?.coordinates?.lat ??
      current_location?.geometry?.location?.lat;

    const lng =
      current_location?.coordinates?.lng ??
      current_location?.geometry?.location?.lng;

    // if (!lat || !lng) {
    //   console.error("Latitude or Longitude not available");
    //   return;
    // }

    const data = {
      address_id: selectedAddressId,
      exchange_rate: currentCurrency?.rate,
      // customer_lat: lat,
      // customer_long: lng,
    };

    if (CouponData) {
      data.coupon_id = CouponData?.id;
    }
    const res = await dispatch(OrderCalculation(data));

    if (res.meta?.requestStatus === "fulfilled") {
      setData(res.payload.data);
    } else if (res.meta?.requestStatus === "rejected") {
      if (res.payload?.errors) {
        setErrors(res.payload?.errors);
      }
    }
    await setLoader(false);
  };

  useEffect(() => {
    orderCalculation(selectedAddressId, currentCurrency, current_location);
  }, [selectedAddressId, CouponData, currentCurrency, current_location]);

  const address = useSelector((state) => state.order.orderAddress);
  useEffect(() => {
    dispatch(getSingleOrderAddress({ id: selectedAddressId }));
  }, [dispatch, selectedAddressId]);

  //order place
  const [razorid, setRazorId] = useState();

  // const [Razorpay] = useRazorpay();
  const Razorpay = useRazorpay();
  const handleRazorpay = async (price) => {
    const amountInPaise = Math.round(price * 100);
    const options = {
      // key: "rzp_test_I05KCFb1v5JJRc",
      key: process.env.NEXT_PUBLIC_RAZORPAY_KEY,
      amount: amountInPaise,
      currency: "INR",
      name: "Shiram Agro Traders",
      description: "Test Transaction",
      image:
        "http://localhost:3000/static/media/hippicart-logo.427718645d3015dbf003.png",
      handler: async (res) => {
        await setRazorId(res.razorpay_payment_id);
        finalFunction(res.razorpay_payment_id);
      },
      prefill: {
        name: "Piyush Garg",
        email: "youremail@example.com",
        contact: "9999999999",
      },
      notes: {
        address: "Razorpay Corporate Office",
      },
      theme: {
        color: "#052c65",
      },
    };
    // const rzpay = new Razorpay(options);
    const rzpay = new window.Razorpay(options);
    rzpay.open();
  };

  const finalFunction = async (razorpay) => {
    setLoader(true);
    const datafinal = {
      exchange_rate_id: currentCurrency?.id,
      exchange_rate: currentCurrency?.rate,
      address_id: selectedAddressId,
      payment_method_id: paymentValue,
      order_summary: data?.order_summary,
      order_Details_summary: data?.order_Details_summary,
    };
    if (razorpay) {
      datafinal.payment_id = razorpay;
    }

    const res = await dispatch(createOrder(datafinal));

    if (res.meta?.requestStatus === "fulfilled") {
      handleClick();
      await dispatch(getAllCart(isSignin));
    } else if (res.meta?.requestStatus === "rejected") {
      if (res.payload) {
        setErrors(res.payload);
      }
      // if (res.payload?.errors?.email) {
      //     setError("email", {
      //       type: "manual",
      //       message: res.payload?.errors?.email,
      //     });
      //   }
    }
    setLoader(false);
  };

  const {
    control,
    register,
    handleSubmit,
    getValues,
    setValue,
    setError,
    clearErrors,
    formState: { errors },
    reset,
    trigger,
  } = useForm();

  const onSubmit = async (d) => {
    d.amount = data?.order_summary?.total_selling_price;
    const res = await dispatch(CouponApplyed(d));
    clearErrors();
    if (res?.payload?.data) {
      setCouponData(res?.payload?.data);
      setValue("code", d?.code);
    }
    if (res?.payload?.errors) {
      setError("code", {
        type: "manual",
        message: res.payload?.errors,
      });
    }
    setShowCouponModal(false);
  };

  const deleteCart = async (id, product_id, varient_id) => {
    const res = await dispatch(
      deleteAllCart({ id, isSignin, product_id, varient_id }),
    );
    if (res.meta?.requestStatus === "fulfilled") {
      await dispatch(getAllCart(isSignin));
      await orderCalculation(selectedAddressId);
    } else if (res.meta?.requestStatus === "rejected") {
      console.log("Error:", res.payload || "Not In Cart");
    }
  };
  const isSignIn = useSelector((state) => state.auth.is_signin);
  const user = useSelector((state) => state.myaccount.addMyaccount);
  return (
    <>
      <div className={"Cart_Products_card Order_Overview"}>
        <div className="row">
          <div className="col-lg-8">
            <div className="table-responsive desktop_order_view">
              <Table>
                <tbody>
                  {allcartData?.data?.map((val) => (
                    <tr>
                      <td>
                        <div className="row">
                          <div className="col-md-4 col-12">
                            <div className="img_holder">
                              <img
                                className="Product_img"
                                src={
                                  process.env.NEXT_PUBLIC_IMG_URL +
                                  val.Product?.image
                                }
                                alt={"Product_img"}
                              />
                            </div>
                          </div>
                          <div className="col-md-8 col-12">
                            <div className="info_text_holder">
                              <div>
                                <h4>{val.Product?.name}</h4>
                                <p className="sale_price mobile_price">
                                  Sale Price : {symbol}
                                  {isSignIn &&
                                  Number(user.role_id) === RoleId.B2BCustomer
                                    ? Number(
                                        val.Product_Variant?.price ||
                                          val.Double_Variant?.price ||
                                          val.Triple_Variant?.price,
                                      ).toFixed(2)
                                    : Number(
                                        val.Product_Variant?.b2b_price ||
                                          val.Double_Variant?.price ||
                                          val.Triple_Variant?.price,
                                      ).toFixed(2)}{" "}
                                  <br />
                                  <span>
                                    MRP : {symbol}
                                    {isSignIn &&
                                    Number(user.role_id) === RoleId.B2BCustomer
                                      ? Number(
                                          val.Product_Variant?.mrp ||
                                            val.Double_Variant?.mrp ||
                                            val.Triple_Variant?.mrp,
                                        ).toFixed(2)
                                      : Number(
                                          val.Product_Variant?.b2b_mrp ||
                                            val.Double_Variant?.mrp ||
                                            val.Triple_Variant?.mrp,
                                        ).toFixed(2)}{" "}
                                  </span>
                                </p>
                                <h6>
                                  {/* {val?.Product?.variant_type_id ===
                                    variant_type.Single && (
                                      <>
                                        <strong>Variant :</strong>{" "}
                                        {val?.Product_Variant?.Metal?.name}
                                      </>
                                    )} */}

                                  {/* {val?.Product?.variant_type_id ===
                                    variant_type.Double && (
                                    <>
                                      <strong>Variant :</strong>{" "}
                                      {
                                        val?.Double_Variant?.Product_Variant
                                          ?.Metal?.name
                                      }
                                      , <strong>Size:</strong>{" "}
                                      {val?.Double_Variant?.Size?.name}{" "}
                                    </>
                                  )} */}

                                  {val?.Product?.variant_type_id ===
                                    variant_type.Triple && (
                                    <>
                                      <strong>Variant :</strong>{" "}
                                      {
                                        val?.Triple_Variant?.Double_Variant
                                          ?.Product_Variant?.Metal?.name
                                      }
                                      , <strong>Size:</strong>{" "}
                                      {
                                        val?.Triple_Variant?.Double_Variant
                                          ?.Size?.name
                                      }
                                      , <strong>Diamond:</strong>{" "}
                                      {val?.Triple_Variant?.Diamond?.name}
                                    </>
                                  )}
                                </h6>
                              </div>
                            </div>
                          </div>
                        </div>
                      </td>

                      <td>
                        <div className="Quantity_tr_holder">
                          <div className="price_holder">
                            <p className="mb-0">
                              {symbol}{" "}
                              {isSignIn &&
                              Number(user.role_id) === RoleId.B2BCustomer
                                ? Number(
                                    val.Product_Variant?.price ||
                                      val.Double_Variant?.price ||
                                      val.Triple_Variant?.price,
                                  ).toFixed(2) * Number(val.quantity)
                                : Number(
                                    val.Product_Variant?.b2b_price ||
                                      val.Double_Variant?.price ||
                                      val.Triple_Variant?.price,
                                  ).toFixed(2) * Number(val.quantity)}
                              <span>
                                {symbol}{" "}
                                {isSignIn &&
                                Number(user.role_id) === RoleId.B2BCustomer
                                  ? Number(
                                      val.Product_Variant?.mrp ||
                                        val.Double_Variant?.mrp ||
                                        val.Triple_Variant?.mrp,
                                    ).toFixed(2) * Number(val.quantity)
                                  : Number(
                                      val.Product_Variant?.b2b_mrp ||
                                        val.Double_Variant?.mrp ||
                                        val.Triple_Variant?.mrp,
                                    ).toFixed(2) * Number(val.quantity)}{" "}
                              </span>
                            </p>{" "}
                            <br />
                          </div>
                          {/* <FontAwesomeIcon
                            className="trash_icon ms-3"
                            icon={faTrashCan}
                            onClick={() =>
                              deleteCart(
                                val?.id,
                                val?.product_id,
                                val?.variant_id,
                              )
                            }
                          /> */}
                        </div>

                        <div className="Quantity_tr_holder">
                          <div className="price_holder">
                            <p className="mb-0">Qty: {val?.quantity} </p>
                          </div>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </Table>
            </div>
            <div className="mobile_order_view">
              {allcartData?.data?.map((val) => (
                <div className="mobile_order_card" key={val.id}>
                  <div className="mobile_order_top">
                    <img
                      src={process.env.NEXT_PUBLIC_IMG_URL + val.Product?.image}
                      alt={val.Product?.name}
                      className="mobile_order_img"
                    />

                    <div className="mobile_order_info">
                      <h5>{val.Product?.name}</h5>

                      <p>
                        Qty : <strong>{val.quantity}</strong>
                      </p>

                      <p className="mobile_price">
                        Sale : {symbol}
                        {(
                          Number(
                            val.Product_Variant?.price ||
                              val.Double_Variant?.price ||
                              val.Triple_Variant?.price,
                          ) * rate
                        ).toFixed(2)}
                      </p>
                      <p className="mobile_price">
                        MRP : {symbol}
                        {Number(
                          Number(
                            val.Product_Variant?.mrp ||
                              val.Double_Variant?.mrp ||
                              val.Triple_Variant?.mrp,
                          ) * rate,
                        ).toFixed(2)}{" "}
                      </p>

                      <p className="mobile_total">
                        Total : {symbol}
                        {(
                          Number(
                            val.Product_Variant?.price ||
                              val.Double_Variant?.price ||
                              val.Triple_Variant?.price,
                          ) *
                          rate *
                          Number(val.quantity)
                        ).toFixed(2)}
                      </p>
                    </div>

                    {/* <FontAwesomeIcon
                      className="mobile_delete_icon"
                      icon={faTrashCan}
                      onClick={() =>
                        deleteCart(val?.id, val?.product_id, val?.variant_id)
                      }
                    /> */}
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="col-lg-4">
            <Order_Overview_summery_holder
              data={data}
              address={address}
              paymentValue={paymentValue}
            />
            <div style={{ color: "red" }}>{Errors}</div>
            {errors.code && (
              <div style={{ color: "red" }}>{errors?.code?.message}</div>
            )}
            <div className="Rewards_text_holder">
              <h4>Offers and Rewards</h4>
              <Form onSubmit={handleSubmit(onSubmit)}>
                <InputGroup className="mb-3">
                  <InputGroup.Text
                    className="tags_icon_holder"
                    id="basic-addon2"
                  >
                    {" "}
                    <FontAwesomeIcon className="tags_icon" icon={faTags} />
                  </InputGroup.Text>

                  <Form.Control
                    className="mb-0"
                    placeholder="Enter Coupon Code"
                    {...register("code", {
                      required: "Coupon code is required",
                    })}
                    readOnly={!!CouponData}
                  />

                  {CouponData ? (
                    // If coupon code exists, View acts as submit
                    <InputGroup.Text
                      as="button"
                      type="submit"
                      className="view_grp"
                      id="basic-addon2"
                      style={{ cursor: "pointer" }}
                      onClick={() => {
                        setCouponData("");
                        setValue("code", "");
                      }}
                    >
                      Remove
                    </InputGroup.Text>
                  ) : (
                    // If no code, open modal
                    <InputGroup.Text
                      className="view_grp"
                      id="basic-addon2"
                      onClick={() => setShowCouponModal(true)}
                      style={{ cursor: "pointer" }}
                    >
                      View
                    </InputGroup.Text>
                  )}
                  {/* <InputGroup.Text
                  className="view_grp"
                  id="basic-addon2"
                  onClick={() => {
                    setShowCouponModal(true);
                  }}
                >
                  View
                </InputGroup.Text> */}
                </InputGroup>
              </Form>
            </div>
            {!data?.order_summary?.order_status && (
              <p
                style={{ color: "red", fontWeight: "500" }}
                className="delivery-rage"
              >
                Your location is not within our delivery range.
              </p>
            )}

            {loader ? (
              <>
                <Spinner animation="border" role="status">
                  <span className="visually-hidden">Loading...</span>
                </Spinner>
              </>
            ) : (
              <>
                <div className="btn_holder d-flex justify-content-center">
                  <Green_Outline_Btn btnText={"Back"} onClick={prev} />
                  {allcartData?.data?.length > 0 ? (
                    data?.order_summary?.order_status ? (
                      <Green_Outline_Btn
                        btnText={"Place Order"}
                        onClick={() =>
                          paymentValue !== 2
                            ? finalFunction()
                            : handleRazorpay(data?.order_summary?.total_amount)
                        }
                      />
                    ) : (
                      <>
                        <Green_Outline_Btn btnText={"Place Order"} />
                      </>
                    )
                  ) : (
                    // <>
                    //   {" "}
                    //   <Green_Outline_Btn
                    //     btnText={"Place Order"}
                    // onClick={() =>
                    //   paymentValue !== 2
                    //     ? finalFunction()
                    //     : handleRazorpay(data?.order_summary?.total_amount)
                    // }
                    //   />
                    // </>
                    <Green_Outline_Btn
                      btnText={"Continue Shopping"}
                      onClick={() => navigate.push("/shop")}
                    />
                    // <Link to="/shops" className="btn btn-outline-success">
                    //   Continue Shopping
                    // </Link>
                  )}
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      <Script
        id="razorpay-script"
        src="https://checkout.razorpay.com/v1/checkout.js"
      />

      <Success_Modal
        show={modalShow}
        onHide={() => setModalShow(false)}
        successText="Your Order Has Been Placed Successfully!"
      />

      <Coupons_Modal
        setValue={setValue}
        setCouponData={setCouponData}
        onSubmit={onSubmit}
        data={data}
        show={showCouponModal}
        onHide={() => {
          setShowCouponModal(false);
        }}
      />

      <Delete_Modal
        show={modalDeleteShow}
        onHide={() => setModalDeleteShow(false)}
        successText="Order Deleted Sucessfuly"
      />
    </>
  );
};
export default Order_Overview;
