import React, { useState } from "react";
import "./Order_summery_holder.css";
import Green_btn from "../../../common-components/common_btn/green_btn/Green_btn";
import { Button, Table } from "react-bootstrap";

import { useSelector } from "react-redux";
import Login_Modal from "../../../common-components/common_modal/login_modal/Login_Modal";
import Reset_Password_Modal from "../../../common-components/common_modal/reset_password_modal/Reset_Password_Modal";
import Set_New_Password_Modal from "../../../common-components/common_modal/set_new_password_modal/Set_New_Password_Modal";
import Success_Modal from "../../../common-components/common_modal/success_modal/Success_Modal";
import { useRouter } from "next/navigation";
import { RoleId } from "../../../../utils/common";

function Order_summery_holder({ data, instock }) {
  const navigate = useRouter();

  const [showResetModal, setShowResetModal] = useState(false);
  const [showSetPassModal, setShowSetPassModal] = useState(false);
  const [showSuccessModal, setShowSucsessModal] = useState(false);
  const [showAccountCreted, setShowAccountCreted] = useState(false);
  const [error, setError] = useState("");
  const isSignIn = useSelector((state) => state.auth.is_signin);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const handleClick = () => {
    if (instock) {
      setError("Item is out of stock. Please try later.");
      return; // Don't proceed
    }

    if (data.data?.length > 0) {
      if (isSignIn) {
        navigate.push("/proceed-to-Checkout");
      } else {
        setShowLoginModal(true);
        //  navigate("/proceed-to-Checkout");
      }
    } else {
      setError("Your cart is currently empty. Please add items to proceed.");
    }
  };

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

  const user = useSelector((state) => state.myaccount.addMyaccount);
  let total_amount = 0;
  let total_tax = 0;

  if (Array.isArray(data?.data)) {
    total_amount = data.data.reduce((acc, item) => {
      const tax_percentage = parseFloat(item?.Product?.tax_percentage || 0);
      let price = 0;
      if (isSignIn && user?.role_id === RoleId.B2BCustomer) {
        price = parseFloat(
          item?.Product_Variant?.b2b_price ||
            item?.Double_Variant?.price ||
            item?.Triple_Variant?.price ||
            0,
        );
      } else {
        price = parseFloat(
          item?.Product_Variant?.price ||
            item?.Double_Variant?.price ||
            item?.Triple_Variant?.price ||
            0,
        );
      }

      const qty = parseFloat(item?.quantity || 0);
      const line_total = price * qty;

      // Accumulate tax per item
      total_tax += line_total * (tax_percentage / 100);

      return acc + line_total;
    }, 0);
  }

  const [email, setEmail] = useState();
  const [contact, setContact] = useState();

  return (
    <>
      <section className="Order_summery_holder">
        <div className="heading_holder">
          <h6>Order Summary</h6>
        </div>
        <div className="Order_summery_table">
          <div className="table-responsive">
            <Table>
              <tbody>
                <tr>
                  <td>SubTotal</td>
                  <td className="text-end">
                    {symbol} {Number(total_amount * rate).toFixed(2)}
                  </td>
                </tr>
                <tr>
                  <td>Discount</td>
                  <td className="text-end">₹ 0</td>
                </tr>

                <tr>
                  <td>Tax</td>
                  <td className="text-end">₹ {Number(total_tax).toFixed(2)}</td>
                </tr>

                {/* <tr>
                  <td>Shipping</td>
                  <td className="text-end">Free</td>
                </tr> */}

                <tr className="total_tr_holder">
                  <td>
                    <b>Total</b>
                  </td>
                  <td className="text-end">
                    <b>
                      {/* {symbol} {Number(total_amount * rate).toFixed(2)} */}
                      {symbol}{" "}
                      {Number(total_amount * rate + Number(total_tax)).toFixed(
                        2,
                      )}
                    </b>
                  </td>
                </tr>
              </tbody>
            </Table>
          </div>
        </div>
        <div className="btn_holder ">
          <Green_btn btnText={"Proceed to Checkout"} onClick={handleClick} />

          {/* <section className="Green_btn_holder">
            <Button className="Green_btn" onClick={handleClick}> 
              &nbsp;Proceed to Checkout
            </Button>
          </section> */}
          {error && <p style={{ color: "red", marginTop: "10px" }}>{error}</p>}
          {/* <Green_btn btnText={"Proceed to Checkout"} onClick={handleClick} /> */}
        </div>
      </section>
      <Login_Modal
        email={email}
        setEmail={setEmail}
        contact={contact}
        setContact={setContact}
        show={showLoginModal}
        onHide={() => {
          setShowLoginModal(false);
        }}
        setShowResetModal={() => setShowResetModal(true)}
        setShowAccountCreted={() => setShowAccountCreted(true)}
      />

      <Reset_Password_Modal
        email={email}
        setEmail={setEmail}
        contact={contact}
        setContact={setContact}
        show={showResetModal}
        onHide={() => {
          setShowResetModal(false);
        }}
        setShowSetPassModal={() => setShowSetPassModal(true)}
      />

      <Set_New_Password_Modal
        show={showSetPassModal}
        email={email}
        setEmail={setEmail}
        contact={contact}
        setContact={setContact}
        onHide={() => {
          setShowSetPassModal(false);
        }}
        setShowSucsessModal={() => setShowSucsessModal(true)}
      />

      <Success_Modal
        show={showSuccessModal}
        onHide={() => {
          setShowSucsessModal(false);
        }}
        successText="Password Reseted Successfully!"
      />

      <Success_Modal
        show={showAccountCreted}
        onHide={() => {
          setShowAccountCreted(false);
        }}
        successText="Account Created Successful!"
      />
    </>
  );
}

export default Order_summery_holder;
