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-3 pe-0 col-md-2">
                    <p>Name : </p>
                  </div>
                  <div className="col-9  col-md-10">
                    <p>{singleAddress?.name}</p>
                  </div>
                </div>
                <div className="row">
                  <div className="col-3 pe-0  col-md-2">
                    <p className="mb-0">Address: </p>
                  </div>
                  <div className="col-9  col-md-10">
                    <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 payment_option ${
                      paymentValue === 1 ? "active" : ""
                    }`}
                    onClick={() => {
                      setPaymentValue(1);
                      setFieldValue("paymentOption", "cash");
                      setWalletError("");
                    }}
                  >
                    <Form.Check
                      type="radio"
                      id="cash"
                      label="Cash on Delivery"
                      name="paymentOption"
                      value="cash"
                      checked={paymentValue === 1}
                      onChange={() => {}}
                    />
                  </div>

                  <div
                    className={`col-md-4 payment_option ${
                      paymentValue === 2 ? "active" : ""
                    }`}
                    onClick={() => {
                      setPaymentValue(2);
                      setFieldValue("paymentOption", "online");
                      setWalletError("");
                    }}
                  >
                    <Form.Check
                      type="radio"
                      id="online"
                      label="Online"
                      name="paymentOption"
                      value="online"
                      checked={paymentValue === 2}
                      onChange={() => {}}
                    />
                  </div>

                  <div
                    className={`col-md-4 payment_option ${
                      paymentValue === 3 ? "active" : ""
                    }`}
                    onClick={() => {
                      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");
                        setWalletError("");
                      } else {
                        setWalletError(
                          "Insufficient wallet balance. Please add wallet amount.",
                        );
                      }
                    }}
                  >
                    <Form.Check
                      type="radio"
                      label="Wallet"
                      name="paymentOption"
                      id="wallet"
                      value="Wallet"
                      checked={paymentValue === 3}
                      onChange={() => {}}
                    />
                  </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;
