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

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

/**
 * Rewards component displays available rewards and allows users to redeem them
 */
const Rewards = () => {
  const { auth } = useContext(AuthContext);
  const [rewards, setRewards] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [redeemingRewardId, setRedeemingRewardId] = useState(null);

  // Load rewards from API
  const loadRewards = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await axios.get("/api/rewards");
      setRewards(res.data);
    } catch (err) {
      console.error("Error loading rewards:", err);
      const errorMessage =
        err.response?.data?.msg ||
        err.response?.data?.message ||
        "Failed to load rewards. Please try again later.";
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadRewards();
  }, [loadRewards]);

  // Redeem a reward
  const redeemReward = async (id, rewardName, cost) => {
    if (!auth.isAuthenticated) {
      toast.warning("Please login to redeem rewards");
      return;
    }

    try {
      setRedeemingRewardId(id);
      const token = localStorage.getItem("token");
      await axios.post(
        `/api/rewards/redeem/${id}`,
        {},
        {
          headers: {
            "x-auth-token": token,
          },
        }
      );
      toast.success(
        `Reward "${rewardName}" redeemed successfully! ${cost} points deducted.`
      );
    } catch (err) {
      console.error("Error redeeming reward:", err);
      const errorMessage =
        err.response?.data?.msg ||
        err.response?.data?.message ||
        "Failed to redeem reward. Please try again.";
      toast.error(errorMessage);
    } finally {
      setRedeemingRewardId(null);
    }
  };

  if (loading) {
    return (
      <div className="text-center mt-5">
        <div className="spinner-border" role="status">
          <span className="sr-only">Loading...</span>
        </div>
        <p>Loading rewards...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="alert alert-danger m-3" role="alert">
        <h4 className="alert-heading">Error Loading Rewards</h4>
        <p>{error}</p>
        <hr />
        <button className="btn btn-primary" onClick={loadRewards}>
          Retry
        </button>
      </div>
    );
  }

  return (
    <div>
      <h1>Rewards</h1>

      {auth.user && (
        <div className="alert alert-info mb-4">
          <strong>Your Points:</strong>{" "}
          <span className="badge badge-primary">{auth.user.points || 0}</span>
        </div>
      )}

      {!auth.isAuthenticated && (
        <div className="alert alert-warning mb-4">
          Please log in to view and redeem rewards.
        </div>
      )}

      {rewards.length === 0 ? (
        <div className="alert alert-info">
          No rewards available at the moment. Check back later!
        </div>
      ) : (
        <div className="row">
          {rewards.map((reward) => {
            const canAfford =
              auth.isAuthenticated &&
              auth.user &&
              (auth.user.points || 0) >= reward.cost;
            const canRedeem =
              canAfford &&
              (!reward.isPremium ||
                (reward.isPremium && auth.user.isPremium));

            return (
              <div key={reward._id} className="col-md-6 col-lg-4 mb-4">
                <div className="card h-100">
                  <div className="card-body d-flex flex-column">
                    <h5 className="card-title">{reward.name}</h5>
                    <p className="card-text flex-grow-1">
                      {reward.description}
                    </p>

                    <div className="mb-2">
                      <strong>Cost:</strong>{" "}
                      <span
                        className={`badge badge-${
                          canAfford ? "success" : "warning"
                        }`}
                      >
                        {reward.cost} points
                      </span>
                    </div>

                    {reward.isPremium && (
                      <div className="mb-2">
                        <span className="badge badge-warning">
                          Premium Only
                        </span>
                      </div>
                    )}

                    {reward.quantity !== undefined && (
                      <div className="mb-2">
                        <small className="text-muted">
                          Available: {reward.quantity}
                        </small>
                      </div>
                    )}

                    {auth.isAuthenticated ? (
                      <button
                        className={`btn btn-${
                          canRedeem ? "primary" : "secondary"
                        } btn-block mt-2`}
                        onClick={() =>
                          redeemReward(reward._id, reward.name, reward.cost)
                        }
                        disabled={
                          !canRedeem ||
                          redeemingRewardId === reward._id ||
                          (reward.quantity !== undefined && reward.quantity <= 0)
                        }
                      >
                        {redeemingRewardId === reward._id ? (
                          <>
                            <span
                              className="spinner-border spinner-border-sm mr-2"
                              role="status"
                              aria-hidden="true"
                            ></span>
                            Redeeming...
                          </>
                        ) : !canAfford ? (
                          "Insufficient Points"
                        ) : reward.isPremium && !auth.user.isPremium ? (
                          "Premium Required"
                        ) : reward.quantity !== undefined &&
                          reward.quantity <= 0 ? (
                          "Out of Stock"
                        ) : (
                          "Redeem"
                        )}
                      </button>
                    ) : (
                      <button className="btn btn-secondary btn-block mt-2" disabled>
                        Login to Redeem
                      </button>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default Rewards;
