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-4">
                    <p>Name : </p>
                  </div>
                  <div className="col-md-8">
                    <p>{singleAddress?.name}</p>
                  </div>
                </div>
                <div className="row">
                  <div className="col-md-4">
                    <p className="mb-0">Address: </p>
                  </div>
                  <div className="col-md-8">
                    <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-md-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-md-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-md-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>
                  )}

                  {/* {parseFloat(allWalletHistory?.user_wallet?.amount) >= parseFloat(data?.order_summary?.total_amount) && (
                    <div className="col-md-4">
                      <Form.Check
                        type="radio"
                        label="Wallet"
                        name="paymentOption"
                        value="Wallet"
                        onClick={() => setPaymentValue(3)}
                        checked={paymentValue === 3}
                        onChange={() =>
                          setFieldValue("paymentOption", "wallet")
                        }
                      />
                    </div>
                  )} */}
                </div>
              </div>

              {/* <div className="Pay_with_credit_card">
                <h6>Pay with Credit Card</h6>
                <div className="row">
                  {["visa", "mastercard"].map((option, i) => (
                    <div className="col-md-4" key={i}>
                      <Form.Group className="input_group">
                        <Form.Check
                          type="radio"
                          name="paymentOption"
                          checked={values.paymentOption === option}
                          onChange={() =>
                            setFieldValue("paymentOption", option)
                          }
                        />
                        <div className="payment_image_holder">
                          <img
                            src={`${process.env.PUBLIC_URL}/assets/images/payment/${option}.png`}
                            className="payment_image"
                            alt={`${option} image`}
                          />
                        </div>
                      </Form.Group>
                    </div>
                  ))}
                </div>
              </div>

              <div className="Pay_with_credit_card">
                <h6>Pay with UPI</h6>
                <div className="row">
                  {["gpay", "phonepe", "paytm"].map((option, i) => (
                    <div className="col-md-4" key={i}>
                      <Form.Group className="input_group">
                        <Form.Check
                          type="radio"
                          name="paymentOption"
                          checked={values.paymentOption === option}
                          onChange={() =>
                            setFieldValue("paymentOption", option)
                          }
                        />
                        <div className="payment_image_holder">
                          <img
                            src={`${process.env.PUBLIC_URL}/assets/images/payment/${option}.png`}
                            className="payment_image"
                            alt={`${option} image`}
                          />
                        </div>
                      </Form.Group>
                    </div>
                  ))}
                </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;
