import React, { useContext, useEffect, useState } from "react";
import "./Payment.css";
import { Formik, Field } from "formik";

import CheckoutStepFormContext from "../CheckoutStepFormContext";
import Green_Outline_Btn from "../../../common-components/common_btn/green_outline_btn/Green_Outline_Btn";

import { Form } from "react-bootstrap";
import {
  getSingleOrderAddress,
  OrderCalculation,
} from "../../../../features/order/orderSlice";
import { useDispatch, useSelector } from "react-redux";
import { getAllWalletHistory } from "../../../../features/wallet/walletSlice";

const Payment = ({ selectedAddressId, paymentValue, setPaymentValue }) => {
  const { next, prev } = useContext(CheckoutStepFormContext);

  const dispatch = useDispatch();
  const singleAddress = useSelector((state) => state.order.orderAddress);

  useEffect(() => {
    dispatch(getSingleOrderAddress({ id: selectedAddressId }));
  }, [dispatch, selectedAddressId]);

  const allWalletHistory = useSelector(
    (state) => state.wallet.allWalletHistory,
  );

  useEffect(() => {
    dispatch(getAllWalletHistory());
  }, [dispatch]);
  const [data, setData] = useState({});
  const orderCalculation = async (selectedAddressId) => {
    const data = {
      address_id: selectedAddressId,
    };

    const res = await dispatch(OrderCalculation(data));

    if (res.meta?.requestStatus === "fulfilled") {
      setData(res.payload.data);
    } else if (res.meta?.requestStatus === "rejected") {
    }
  };

  useEffect(() => {
    orderCalculation(selectedAddressId);
  }, [selectedAddressId]);
  const [walletError, setWalletError] = useState("");
  return (
    <Formik
      initialValues={{
        paymentOption: "",
      }}
      onSubmit={(values) => {
        next();
      }}
      validate={(values) => {
        const errors = {};
        if (!paymentValue) {
          errors.paymentOption = "Please select a payment option.";
        }
        return errors;
      }}
    >
      {({ handleSubmit, errors, touched, values, setFieldValue }) => (
        <Form className={"details__wrapper "} onSubmit={handleSubmit}>
          <div className="Payment_option_holder">
            <div className="inner_box_holder">
              <div className="user_info_holder">
                <div className="row">
                  <div className="col-md-2 col-sm-2 col-3 custom_col">
                    <p>Name : </p>
                  </div>
                  <div className="col-md-10 col-sm-10 col-9">
                    <p>{singleAddress?.name}</p>
                  </div>
                </div>
                <div className="row">
                  <div className="col-md-2 col-sm-2 col-3  custom_col">
                    <p className="mb-0">Address: </p>
                  </div>
                  <div className="col-md-10 col-sm-10 col-9">
                    <p className="mb-0">
                      {singleAddress?.building},{singleAddress?.street},
                      {singleAddress?.city_id?.label},
                      {singleAddress?.state_id?.label},
                      {singleAddress?.country_id?.label},
                      {singleAddress?.pincode_id?.label},
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <div className="inner_box_holder">
              <div className="Choose_Payment_Option">
                <h4>Choose Payment Option</h4>
                <div className="row">
                  <div className="col-sm-4">
                    <Form.Check
                      type="radio"
                      label="Cash on Delivery"
                      name="paymentOption"
                      value="cash"
                      onClick={() => setPaymentValue(1)}
                      checked={paymentValue === 1}
                      onChange={() => setFieldValue("paymentOption", "cash")}
                    />
                  </div>

                  <div className="col-sm-4">
                    <Form.Check
                      type="radio"
                      label="Online"
                      name="paymentOption"
                      value="online"
                      onClick={() => setPaymentValue(2)}
                      checked={paymentValue === 2}
                      onChange={() => setFieldValue("paymentOption", "online")}
                    />
                  </div>
                  <div className="col-sm-4">
                    <Form.Check
                      type="radio"
                      label="Wallet"
                      name="paymentOption"
                      value="Wallet"
                      checked={paymentValue === 3}
                      onChange={() => {
                        const walletAmount = parseFloat(
                          allWalletHistory?.user_wallet?.amount || 0,
                        );
                        const orderAmount = parseFloat(
                          data?.order_summary?.total_amount || 0,
                        );

                        if (walletAmount >= orderAmount) {
                          setPaymentValue(3);
                          setFieldValue("paymentOption", "wallet");
                        } else {
                          setWalletError(
                            "Insufficient wallet balance. Please add wallet amount.",
                          );
                          // alert(
                          //   "Insufficient wallet balance. Please add wallet amount."
                          // );
                        }
                      }}
                    />
                  </div>
                  {walletError && (
                    <small className="text-danger d-block mt-1">
                      {walletError}
                    </small>
                  )}
                </div>
              </div>

              {errors.paymentOption && touched.paymentOption && (
                <div className="text-danger mt-2">{errors.paymentOption}</div>
              )}
            </div>
          </div>

          <div className="form__item button__items d-flex justify-content-center">
            <Green_Outline_Btn btnText={"Back"} onClick={prev} />
            <Green_Outline_Btn btnText={"Save & Next"} onClick={handleSubmit} />
          </div>
        </Form>
      )}
    </Formik>
  );
};

export default Payment;
