import React, { useEffect, useState, useContext } from "react";
import axios from "axios";
import { AuthContext } from '../helpers/AuthContext';
import { Link } from 'react-router-dom';
import { Modal, Button } from 'react-bootstrap';
import { useNavigate } from "react-router-dom";
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";



function AccountInfo() {
  const [error, setError] = useState('');
  const [user, setUser] = useState({});
  // const { authState } = useContext(AuthContext);
  const [show, setShow] = useState(false);
  const [showDeactivate, setShowDeactivate] = useState(false);
  const [subscription, setSubscription] = useState({})
  let navigate = useNavigate();
  const [cancelError, setCancelError] = useState('');
  const [profileError, setProfileError] = useState('');
  const [referralError, setReferralError] = useState('');
  const { authState, setAuthState } = useContext(AuthContext);
  const [deactivateError, setDeactivateError] = useState('');
  const [subscriptionDetails, setSubscriptionDetails] = useState({});
  const [appliedPromos, setAppliedPromos] = useState([]);
  const [previousInvoices, setPreviousInvoices] = useState([]);
  const [subDetailsError, setSubDetailsError] = useState('');

  const successAlert = (message) => {
    // window.alert("Invalid Credentials");
    toast.success(message, {
      position: "top-center",
      autoClose: 2000,
      hideProgressBar: false,
      closeOnClick: true,
      pauseOnHover: false,
      draggable: true,
      progress: undefined,
    });
  }

  const initialValues = {
    referralEmail: ""
  };

  const validationSchema = Yup.object().shape({
    referralEmail: Yup.string().email("Email must be valid").min(3).max(50).required("You must input a email"),
  });

  useEffect(() => {
    axios.get(`/api/profile`, {
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('accessToken')
      }
    }).then((response) => {
      setUser(response.data);
    })
      .catch((error) => {
        if (error.response.data.message) {
          setProfileError(error.response.data.message);
        }
      });

  }, [authState]);

  useEffect(() => {

    axios.get(`/api/stripe/getSubscription`, {
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('accessToken')
      }
    }).then((response) => {
      let price = response.data.price / 100.00
      response.data.price = price.toFixed(2)
      setSubscription(response.data)
    })
      .catch((error) => {
        setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
      });
  }, [authState]);

  useEffect(() => {

    axios.get(`/api/profile/subscriptionDetails`, {
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('accessToken')
      }
    }).then((response) => {
      console.log(response.data)
      setSubscriptionDetails(response.data)
      setAppliedPromos(response.data.appliedPromos)
      setPreviousInvoices(response.data.previousInvoicePdfLink)

    })
      .catch((error) => {
        setSubDetailsError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
      });
  }, [authState]);

  const handleClose = (event) => {
    if (event.target.value === "true") {
      axios.delete(`/api/stripe/cancelSubscription`, {
        headers: {
          Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
      }).then((response) => {
        successAlert("Your subscription was cancelled!");
        navigate("/");
      })
        .catch((error) => {
          if (error.response.data.message) {
            setCancelError(error.response.data.message);
          }
        });
    }
    setShow(false)
  };

  const onSubmit = () => {
    setShow(true);
  };

  const onDeactivate = () => {
    setShowDeactivate(true);
  };

  const handleDeactivate = (event) => {
    if (event.target.value === "true") {
      axios.delete(`/api/profile`, {
        headers: {
          Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
      }).then((response) => {
        localStorage.clear();
        setAuthState({
          loggedIn: false
        });
        successAlert("Your account was deactivated!");
        navigate("/");
      })
        .catch((error) => {
          setDeactivateError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
        });
    }
    setShowDeactivate(false)

  }

  const refer = (data) => {
    console.log("here")
    console.log(data)
    axios.post(`/api/referrals/`, data, {
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('accessToken')
      }
    }).then((response) => {
      console.log(response.data)
      successAlert("Your referral was processed!");
      navigate("/");
    })
      .catch((error) => {
        setReferralError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
      });
  }



  return (
    <div className="container mt-3 p-lg-5 w-75 bg-light rounded-3">
      <h1 className="text-center">Account Info</h1>
      <div className="d-flex flex-column justify-content-center">

        <div className="row">

          <div className="col-md-6">
            <div class="card m-3 shadow-custom">
              <h5 class="card-header nav-bg">Profile</h5>
              <div class="card-body">
                <div className="text-danger">{profileError}</div>
                <h6 class="card-subtitle mb-2 text-muted">Username: <span className="fst-italic fw-bolder">{user.username}</span></h6>
                <h6 className="card-subtitle mb-2 text-muted">Email: <span className="fst-italic fw-bolder">{user.email}</span></h6>
                <h6 className="card-subtitle mb-2 text-muted">First Name: <span className="fst-italic fw-bolder">{user.firstName}</span></h6>
                <h6 className="card-subtitle mb-2 text-muted">Last Name: <span className="fst-italic fw-bolder">{user.lastName}</span></h6>
                <Link to={"/profile"}><button className="btn btn-velo">Update Profile</button></Link>
              </div>
            </div>
          </div>

          <div className="col-md-6">
            <div className="card m-3 shadow-custom" >
              <h5 class="card-header nav-bg">Referrals</h5>
              <div className="card-body">
                {subscription.startDate ?
                  <>
                    <Formik initialValues={initialValues} onSubmit={refer} validationSchema={validationSchema}>
                      <Form>
                        <div className="text-danger">{referralError}</div>
                        <label>Enter the email for your referral: </label>
                        <Field className="form-control" name="referralEmail" type="email" />
                        <ErrorMessage name="referralEmail" component="div" className='error-text' />
                        <Button
                          variant="mt-2" className="btn-velo mt-4" type="submit">
                          Refer a Friend
                        </Button>
                      </Form>
                    </Formik>
                  </> : <div>You need a subscription to make referals.</div>
                }
              </div>
            </div>
          </div>
        </div>

        <div class="card m-3 shadow-custom">
          <h5 class="card-header nav-bg">Subscription/Billing</h5>
          <div class="card-body">
            {subscription.startDate && (
              <>
                <div className="text-danger">{subDetailsError}</div>
                <h6 className="card-subtitle mb-2 text-muted">Start Date: <span className="fst-italic fw-bolder">{subscription.startDate}</span></h6>
                <h6 className="card-subtitle mb-2 text-muted">Type: <span className="fst-italic fw-bolder">{subscription.type}</span></h6>  </>)}
            <div>{subscriptionDetails.message}</div>
            <h6 className="card-subtitle mb-2 text-muted">Subscription Price: <span className="fst-italic fw-bolder">{subscriptionDetails.basePrice} per month</span></h6>
            <h6 className="card-subtitle mb-2 text-muted">Overage Price: <span className="fst-italic fw-bolder"> 3$ per 30 minutes</span></h6>
            <h6 className="card-subtitle mb-2 text-muted">Overage Minutes: <span className="fst-italic fw-bolder">{subscriptionDetails.overageMinutes}</span></h6>
            <h6 className="card-subtitle mb-2 text-muted">Overage Fees: <span className="fst-italic fw-bolder">{subscriptionDetails.overageFees}</span></h6>
            <h6 className="card-subtitle mb-2 text-muted">Rental Station Discounts: <span className="fst-italic fw-bolder">{subscriptionDetails.rentalStationDiscounts}</span></h6>
            <h6 className="card-subtitle mb-2 text-muted">Applied Promos: </h6>
            <ul>
              {appliedPromos && appliedPromos.map((value) => (
                <li className="fst-italic fw-bolder">{value}</li>
              ))}
            </ul>
            <h6 className="card-subtitle mb-2 text-muted">Current estimate for next invoice: <span className="fst-italic fw-bolder">{subscriptionDetails.currentEstimate}</span></h6>
            <h6 className="card-subtitle mb-2 text-muted">Next Payment Date: <span className="fst-italic fw-bolder">{subscription.nextPaymentDate}</span></h6>
            <h6 className="card-subtitle mb-2 text-muted">Previous Invoices: </h6>
            <ul>
              {previousInvoices && previousInvoices.map((value, index) => (
                <li><a href={value} >Download Invoice {index + 1}</a></li>
              ))}
            </ul>

            {subscription.startDate ?
              <Button variant="danger" onClick={onSubmit}>
                Cancel Subscription
              </Button> : <Link to={"/pricing"}><button className="btn btn-primary green-btn">Subscribe</button></Link>}
            <div>
              <div className="text-danger">{error}</div>
            </div>
          </div>
        </div>

        <div className="">



          <div className="card m-3 shadow-custom" >
            <h5 class="card-header nav-bg">Deactivate your account</h5>
            <div className="card-body">
              <label>Press here to park your ride for good</label>
              <br />
              <Button className="align-self-center my-2" variant="danger" onClick={onDeactivate}>
                Deactivate
              </Button>
              <br />
              <small>There's no going back after this...</small>
            </div>
          </div>
        </div>

        <Modal centered show={show} onHide={handleClose}>
          <Modal.Header closeButton value={false} onClick={handleClose}>
            <Modal.Title>Cancel User's Subscription</Modal.Title>
          </Modal.Header>
          <div className="text-danger">{cancelError}</div>
          <Modal.Body>Are you sure you wish to proceed with cancelling your HelloVelo subscription?</Modal.Body>
          <Modal.Footer>
            <Button value={false} variant="secondary" onClick={handleClose}>
              Not right now
            </Button>
            <Button value={true} variant="danger" onClick={handleClose}>
              Proceed to Cancel
            </Button>
          </Modal.Footer>
        </Modal>

        <Modal centered show={showDeactivate} onHide={handleDeactivate}>
          <Modal.Header closeButton value={false} onClick={handleDeactivate}>
            <Modal.Title>Deactivate User Account </Modal.Title>
          </Modal.Header>
          <div className="text-danger">{deactivateError}</div>
          <Modal.Body>Are you sure you wish to proceed with deactivating your HelloVelo account?</Modal.Body>
          <Modal.Footer>
            <Button value={false} variant="secondary" onClick={handleDeactivate}>
              Not right now
            </Button>
            <Button value={true} variant="danger" onClick={handleDeactivate}>
              Proceed to Deactivate
            </Button>
          </Modal.Footer>
        </Modal>
      </div>
    </div>
  )
}

export default AccountInfo