import Image from "next/image";
import React, { useEffect, useState } from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { useDispatch, useSelector } from "react-redux";
import { getSession } from "next-auth/react";
import axios from "axios";
import { toast } from "react-toastify";
import { Loader } from "react-bootstrap-typeahead";
import { finishVendorOtpVerification } from "../../redux/actions/vendorActions";
import { useRouter } from "next/router";
// import { getCurrentEndUser } from "../../redux/actions/userActions";

const validationSchema = Yup.object().shape({
  customAmt: Yup.string().required("Full name is required"),
  code: Yup.string().required("Please Enter 4-Digit Code"),
  email: Yup.string().email("Invalid email").required("Email is required"),
  receiverEmail: Yup.string().email("Invalid email").required("Email is required"),
  message: Yup.string().required("Message is required")
});

let formik1;

const GiftCard = () => {
  const router = useRouter()
  const dispatch = useDispatch();
  // useEffect(() => {
  //   dispatch(getCurrentEndUser());
  // }, []);
  const [session, setSession] = useState(null);
  const [loading, setloading] = useState(null);

  useEffect(() => {
    const fetchSession = async () => {
      setSession(await getSession());
    };
    fetchSession();
    // dispatch(getLoggedInVendor());
  }, []);
  // const {loadedUser} = useSelector(state => state.loadedUser)
  // const { endUser } = useSelector(state => state.endUser);
  console.log("endUser", session);
  const [isStep1, setIsStep1] = useState(true);
  const [amount, setAmount] = useState(0);
  const [custom, setcustom] = useState(0);

  const [isStep2, setIsStep2] = useState(false);
  const [isResult, setIsResult] = useState(false);
  const [showTooltip1, setShowTooltip1] = useState(false); // State for first tooltip
  const [showTooltip2, setShowTooltip2] = useState(false); // State for second tooltip
  const tooltipText1 = "Enter your Email Id. We'll send you a 4-digit code to verify";
  const tooltipText2 = "Enter your Receiver’s Email Id whom you wish to send gift card.";
  const handleclose = () => {
    setIsResult(false);
    setIsStep1(true);
  };

  return (
    <section className="gift-card-session">
      <div className="container">
        <div className="row justify-content-center">
          <div className="col-md-10">
            {!isResult && (
              <div className="row">
                <div className="col-md-5">
                  <div className="gift-card-lt">
                    <div className="gift-box">
                      <img src="/images/zango-logo.svg" alt="Gift Card" />
                    </div>
                    <h3>Amount: ${amount}</h3>
                  </div>
                </div>
                <div className="col-md-7">
                  {isStep1 && (
                    <div className="gift-card-rt">
                      <div className="back-btn">
                        <a href="">
                          <span className="image-container">
                            <Image layout="fill" alt="" className="image img-fluid" src="/images/icons/arrow-left-02.svg" />
                          </span>
                        </a>
                      </div>
                      <Formik
                        initialValues={{
                          customAmt: "",
                          email: "",
                          receiverEmail: "",
                          message: ""
                        }}
                        enableReinitialize={true}
                        // validationSchema={validationSchema}
                        onSubmit={(values, { setSubmitting }) => {
                          // Handle form submission here
                        }}
                      >
                        {({ isSubmitting, values, handleChange, handleBlur, touched, errors }) => (
                          <Form action="" className="form-01">
                            <div className="title">Buy a gift card</div>
                            <div className="cl-gry">Please select an amount</div>
                            <div className="gift-card-amt">
                              <ul>
                                <li>
                                  <input
                                    name="amt"
                                    id="amt-250"
                                    type="radio"
                                    value=""
                                    data-gtm-Form-interact-field-id="1"
                                    onChange={e => {
                                      setAmount(250);
                                      setcustom(false);
                                    }}
                                  />
                                  <label for="amt-250">$250</label>
                                </li>
                                <li>
                                  <input
                                    name="amt"
                                    id="amt-500"
                                    type="radio"
                                    value=""
                                    data-gtm-form-interact-field-id="1"
                                    onChange={e => {
                                      setAmount(500);
                                      setcustom(false);
                                    }}
                                  />
                                  <label for="amt-500">$500</label>
                                </li>
                                <li>
                                  <input
                                    name="amt"
                                    id="amt-750"
                                    type="radio"
                                    value=""
                                    data-gtm-form-interact-field-id="1"
                                    onChange={e => {
                                      setAmount(750);
                                      setcustom(false);
                                    }}
                                  />
                                  <label for="amt-750">
                                    <span>Most Popular</span>
                                    <br /> $750
                                  </label>
                                </li>
                                <li>
                                  <input
                                    name="amt"
                                    id="amt-1000"
                                    type="radio"
                                    value=""
                                    data-gtm-form-interact-field-id="1"
                                    onChange={e => {
                                      setAmount(1000);
                                      setcustom(false);
                                    }}
                                  />
                                  <label for="amt-1000"> $1000</label>
                                </li>
                                <li>
                                  <input
                                    name="amt"
                                    id="amt-1500"
                                    type="radio"
                                    value=""
                                    data-gtm-form-interact-field-id="1"
                                    onChange={e => {
                                      setAmount(1500);
                                      setcustom(false);
                                    }}
                                  />
                                  <label for="amt-1500"> $1500</label>
                                </li>
                                <li>
                                  <input
                                    name="amt"
                                    id="amt-custom"
                                    type="radio"
                                    value=""
                                    data-gtm-form-interact-field-id="1"
                                    onChange={e => {
                                      setcustom(true);
                                      setAmount(null);
                                    }}
                                  />
                                  <label for="amt-custom"> $ Custom</label>
                                </li>
                              </ul>
                            </div>
                            <div className="row">
                              {custom && (
                                <div className="col-md-12 mb-4">
                                  <label htmlFor="">Custom Amount</label>
                                  <Field
                                    className="form-control"
                                    type="number"
                                    name="customAmt"
                                    placeholder="Enter your amount"
                                    onChange={e => {
                                      setAmount(e.target.value);
                                    }}
                                    onBlur={handleBlur}
                                    value={amount}
                                  />
                                  {touched.customAmt && errors.customAmt && <div className="text-danger">{errors.customAmt}</div>}
                                </div>
                              )}

                              <div className="col-md-12 mb-4">
                                <label htmlFor="">Email Id</label>
                                <Field
                                  className="form-control"
                                  type="email"
                                  name="email"
                                  placeholder="yourname@example.com"
                                  onChange={handleChange}
                                  onBlur={handleBlur}
                                  value={values.email}
                                />
                                {touched.email && errors.email && <div className="text-danger">{errors.email}</div>}
                                <div className="tooltip-wrapper">
                                  <a className="tooltip-btn" onMouseEnter={() => setShowTooltip1(true)} onMouseLeave={() => setShowTooltip1(false)}>
                                    <span className="image-container">
                                      <Image layout="fill" alt="" className="image img-fluid" src="/images/icons/info.svg" />
                                    </span>
                                  </a>

                                  {/* Tooltip */}
                                  {showTooltip1 && <div className="tooltips">{tooltipText1}</div>}
                                </div>
                              </div>

                              <div className="col-md-12 mb-4">
                                <label htmlFor="">Receiver’s Email Id</label>
                                <Field
                                  className="form-control"
                                  type="receiverEmail"
                                  name="receiverEmail"
                                  placeholder="yourname@example.com"
                                  onChange={handleChange}
                                  onBlur={handleBlur}
                                  value={values.receiverEmail}
                                />
                                {touched.receiverEmail && errors.receiverEmail && <div className="text-danger">{errors.receiverEmail}</div>}
                                <div className="tooltip-wrapper">
                                  <a className="tooltip-btn" onMouseEnter={() => setShowTooltip2(true)} onMouseLeave={() => setShowTooltip2(false)}>
                                    <span className="image-container">
                                      <Image layout="fill" alt="" className="image img-fluid" src="/images/icons/info.svg" />
                                    </span>
                                  </a>

                                  {showTooltip2 && <div className="tooltips">{tooltipText2}</div>}
                                </div>
                              </div>

                              <div className="col-md-12 mb-4">
                                <Field
                                  className="form-control"
                                  as="textarea"
                                  rows={7}
                                  name="message"
                                  placeholder="Type your message..."
                                  onChange={handleChange}
                                  onBlur={handleBlur}
                                  value={values.message}
                                />
                                {touched.message && errors.message && <div className="text-danger">{errors.message}</div>}
                              </div>
                              <div className="col-md-12 mb-3">
                                <button
                                  className="btn btn-primary w-100"
                                  onClick={async () => {
                                    setloading(true);
                                    if (!session) {
                                      toast.warning("Please log in to buy a gift card.");
                                      return;
                                    }
                                    const config = {
                                      headers: {
                                        "Content-Type": "application/json",
                                        Authorization: `Bearer ${session.jwt}`
                                      }
                                    };
                                    const data = {
                                      data: {
                                        userId: session.id
                                      }
                                    };
                                    const response = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/end-user/verify-gift-card-otp`, data, config);
                                    console.log("response", response.data);
                                    setloading(false);
                                    console.log(values);
                                    setIsStep2(true);
                                    setIsStep1(false);
                                  }}
                                  disabled={!amount > 0 || !values.receiverEmail || !values.email}
                                >
                                  {loading ? <Loader /> : "Continue"}
                                </button>
                              </div>
                              <div className="col-12">
                                <p>
                                  By continuing you agree to our <a href="">Terms</a> and <a href="">Privacy Policy</a>
                                </p>
                              </div>
                            </div>
                          </Form>
                        )}
                      </Formik>
                    </div>
                  )}

                  {isStep2 && (
                    <div className="gift-card-rt">
                      <div className="back-btn">
                        <a href="">
                          <span className="image-container">
                            <Image layout="fill" alt="" className="image img-fluid" src="/images/icons/arrow-left-02.svg" />
                          </span>
                        </a>
                      </div>
                      <Formik
                        initialValues={{
                          code: ""
                        }}
                        // validationSchema={validationSchema}
                        onSubmit={(values, { setSubmitting }) => {
                          // Handle form submission here
                          console.log(values);
                          setSubmitting(false);
                          setIsStep2(false);
                          setIsStep1(false);
                          setIsResult(true);
                        }}
                      >
                        {({ isSubmitting, values, handleChange, handleBlur, touched, errors }) => (
                          <Form action="" className="form-01">
                            <div className="title">We emailed you a 4-digit code</div>
                            <div className="cl-gry">Please enter it below to create or login into your account:</div>

                            <div className="row mt-4">
                              <div className="col-md-12 mb-4">
                                <label htmlFor="">Enter 4-Digit Code</label>
                                <Field
                                  className="form-control"
                                  type="text"
                                  name="code"
                                  placeholder="Enter the code we emailed you"
                                  onChange={handleChange}
                                  onBlur={handleBlur}
                                  value={values.code}
                                />
                                {touched.code && errors.code && <div className="text-danger">{errors.code}</div>}
                                <div className="link-a">
                                  <a href="">Resend Code</a>
                                </div>
                              </div>
                            </div>
                            <div className="row">
                              <div className="col-md-12 mb-3">
                                <button
                                  className="btn btn-primary w-100"
                                  onClick={async () => {
                                    const res = await await finishVendorOtpVerification({ email: session.user.email, oneTimePassword: values.code });
                                    console.log("res", res.data);
                                    if (!res.data.ok) {
                                      toast.error(res.data.message);
                                    }
                                    if (res.data.ok) {
                                      toast.success("OTP verified!");
                                    }
                                  }}
                                  disabled={isSubmitting}
                                >
                                  Confirm
                                </button>
                              </div>
                            </div>
                          </Form>
                        )}
                      </Formik>
                    </div>
                  )}
                </div>
              </div>
            )}

            {isResult && (
              <div className="row">
                <div className="col-12">
                  <div className="result-box">
                    <p>
                      Gift card sent for approval, please wait till the vendor contacts you
                      <br /> Thank you.
                    </p>
                    <div>
                      <button className="btn btn-primary" type="button" onClick={()=>{
                        router.push("/listing")
                      }}>
                        Browse Experiences
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
};

export default GiftCard;