import React, { useState, useContext } from "react";
import axios from "axios";
import { toast } from "react-toastify";

import { AuthContext } from "../context/AuthContext";

/**
 * Premium component displays premium subscription information and allows users to subscribe
 */
const Premium = () => {
  const { auth } = useContext(AuthContext);
  const [subscribing, setSubscribing] = useState(false);

  // Subscribe to premium
  const subscribe = async () => {
    if (!auth.isAuthenticated) {
      toast.warning("Please login to subscribe to premium");
      return;
    }

    if (auth.user?.isPremium) {
      toast.info("You are already a premium member!");
      return;
    }

    try {
      setSubscribing(true);
      const token = localStorage.getItem("token");
      const res = await axios.post(
        "/api/payments/subscribe",
        {},
        {
          headers: {
            "x-auth-token": token,
          },
        }
      );
      toast.success(
        res.data.message || "Subscription successful! Welcome to premium!"
      );
    } catch (err) {
      console.error("Error subscribing:", err);
      const errorMessage =
        err.response?.data?.msg ||
        err.response?.data?.message ||
        "Failed to subscribe. Please try again.";
      toast.error(errorMessage);
    } finally {
      setSubscribing(false);
    }
  };

  return (
    <div>
      <h1>Premium Subscription</h1>

      {auth.user?.isPremium ? (
        <div className="alert alert-success mb-4">
          <h4 className="alert-heading">You are a Premium Member!</h4>
          <p>
            Thank you for your support! You have access to all premium features.
          </p>
        </div>
      ) : (
        <div className="alert alert-info mb-4">
          <h4 className="alert-heading">Upgrade to Premium</h4>
          <p>
            Unlock exclusive rewards and features by subscribing to our premium
            plan.
          </p>
        </div>
      )}

      <div className="row">
        <div className="col-md-8 offset-md-2">
          <div className="card">
            <div className="card-body">
              <h3 className="card-title text-center mb-4">Premium Benefits</h3>

              <ul className="list-group list-group-flush mb-4">
                <li className="list-group-item">
                  <strong>Exclusive Rewards:</strong> Access to premium-only
                  rewards in the rewards catalog
                </li>
                <li className="list-group-item">
                  <strong>Priority Support:</strong> Get faster responses from
                  our support team
                </li>
                <li className="list-group-item">
                  <strong>Advanced Features:</strong> Unlock advanced analytics
                  and reporting tools
                </li>
                <li className="list-group-item">
                  <strong>Special Badge:</strong> Display your premium status
                  with a special badge
                </li>
                <li className="list-group-item">
                  <strong>Early Access:</strong> Be the first to try new
                  features and updates
                </li>
                <li className="list-group-item">
                  <strong>Ad-Free Experience:</strong> Enjoy the platform
                  without any advertisements
                </li>
              </ul>

              <div className="text-center mb-4">
                <h2 className="text-primary">$9.99/month</h2>
                <p className="text-muted">Cancel anytime, no commitments</p>
              </div>

              {!auth.isAuthenticated ? (
                <div className="alert alert-warning text-center">
                  <p className="mb-2">
                    Please log in to subscribe to premium.
                  </p>
                  <a href="/login" className="btn btn-primary">
                    Log In
                  </a>
                </div>
              ) : auth.user?.isPremium ? (
                <div className="text-center">
                  <button className="btn btn-success btn-lg" disabled>
                    Already Subscribed
                  </button>
                </div>
              ) : (
                <div className="text-center">
                  <button
                    className="btn btn-primary btn-lg"
                    onClick={subscribe}
                    disabled={subscribing}
                  >
                    {subscribing ? (
                      <>
                        <span
                          className="spinner-border spinner-border-sm mr-2"
                          role="status"
                          aria-hidden="true"
                        ></span>
                        Processing...
                      </>
                    ) : (
                      "Subscribe Now"
                    )}
                  </button>
                  <p className="text-muted mt-3">
                    <small>
                      Note: This is a mock subscription for development
                      purposes. No actual payment will be processed.
                    </small>
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      <div className="row mt-5">
        <div className="col-md-12">
          <h3 className="text-center mb-4">Frequently Asked Questions</h3>

          <div className="accordion" id="faqAccordion">
            <div className="card">
              <div className="card-header" id="faq1">
                <h5 className="mb-0">
                  <button
                    className="btn btn-link"
                    type="button"
                    data-toggle="collapse"
                    data-target="#collapse1"
                    aria-expanded="true"
                    aria-controls="collapse1"
                  >
                    Can I cancel my subscription anytime?
                  </button>
                </h5>
              </div>
              <div
                id="collapse1"
                className="collapse"
                aria-labelledby="faq1"
                data-parent="#faqAccordion"
              >
                <div className="card-body">
                  Yes! You can cancel your premium subscription at any time.
                  Your premium benefits will remain active until the end of your
                  current billing period.
                </div>
              </div>
            </div>

            <div className="card">
              <div className="card-header" id="faq2">
                <h5 className="mb-0">
                  <button
                    className="btn btn-link collapsed"
                    type="button"
                    data-toggle="collapse"
                    data-target="#collapse2"
                    aria-expanded="false"
                    aria-controls="collapse2"
                  >
                    What payment methods do you accept?
                  </button>
                </h5>
              </div>
              <div
                id="collapse2"
                className="collapse"
                aria-labelledby="faq2"
                data-parent="#faqAccordion"
              >
                <div className="card-body">
                  We accept all major credit cards (Visa, MasterCard, American
                  Express) and PayPal. All payments are processed securely
                  through Stripe.
                </div>
              </div>
            </div>

            <div className="card">
              <div className="card-header" id="faq3">
                <h5 className="mb-0">
                  <button
                    className="btn btn-link collapsed"
                    type="button"
                    data-toggle="collapse"
                    data-target="#collapse3"
                    aria-expanded="false"
                    aria-controls="collapse3"
                  >
                    Will my points carry over if I upgrade?
                  </button>
                </h5>
              </div>
              <div
                id="collapse3"
                className="collapse"
                aria-labelledby="faq3"
                data-parent="#faqAccordion"
              >
                <div className="card-body">
                  Absolutely! All your existing points, badges, and adopted
                  streets will remain unchanged when you upgrade to premium.
                  You'll simply gain access to additional premium features and
                  rewards.
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Premium;
