import React, { useState, useEffect, useContext } from "react";
import axios from "axios";
import { toast } from "react-toastify";
import BadgeDisplay from "./BadgeDisplay";
import { AuthContext } from "../context/AuthContext";

/**
 * BadgeCollection component - displays all available badges with filter/sort options
 */
const BadgeCollection = () => {
  const { auth } = useContext(AuthContext);
  const [badges, setBadges] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [filter, setFilter] = useState("all"); // all, earned, locked
  const [sortBy, setSortBy] = useState("rarity"); // rarity, name

  useEffect(() => {
    const fetchBadges = async () => {
      try {
        setLoading(true);
        setError(null);

        // Fetch all badges and user's progress
        const [allBadgesRes, progressRes] = await Promise.all([
          axios.get("/api/badges"),
          axios.get("/api/badges/progress"),
        ]);

        // Merge badge data with progress data
        const badgesWithProgress = allBadgesRes.data.map((badge) => {
          const progress = progressRes.data.find((p) => p._id === badge._id);
          return {
            ...badge,
            isEarned: progress?.isEarned || false,
            progress: progress?.progress || 0,
            threshold: progress?.threshold || badge.criteria?.threshold || 0,
          };
        });

        setBadges(badgesWithProgress);
      } catch (err) {
        console.error("Error fetching badges:", err);
        const errorMessage =
          err.response?.data?.msg ||
          err.response?.data?.message ||
          "Failed to load badges";
        setError(errorMessage);
        toast.error(errorMessage);
      } finally {
        setLoading(false);
      }
    };

    if (auth.isAuthenticated) {
      fetchBadges();
    }
  }, [auth.isAuthenticated]);

  // Filter badges based on selected filter
  const getFilteredBadges = () => {
    let filtered = [...badges];

    if (filter === "earned") {
      filtered = filtered.filter((badge) => badge.isEarned);
    } else if (filter === "locked") {
      filtered = filtered.filter((badge) => !badge.isEarned);
    }

    return filtered;
  };

  // Sort badges based on selected sort option
  const getSortedBadges = () => {
    const filtered = getFilteredBadges();

    if (sortBy === "rarity") {
      const rarityOrder = { legendary: 0, epic: 1, rare: 2, common: 3 };
      return filtered.sort(
        (a, b) => rarityOrder[a.rarity] - rarityOrder[b.rarity]
      );
    } else if (sortBy === "name") {
      return filtered.sort((a, b) => a.name.localeCompare(b.name));
    }

    return filtered;
  };

  const sortedBadges = getSortedBadges();
  const earnedCount = badges.filter((b) => b.isEarned).length;
  const totalCount = badges.length;

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

  if (error) {
    return (
      <div className="alert alert-danger m-3" role="alert">
        <h4 className="alert-heading">Error Loading Badges</h4>
        <p>{error}</p>
      </div>
    );
  }

  if (!auth.isAuthenticated) {
    return (
      <div className="alert alert-warning m-3" role="alert">
        <h4 className="alert-heading">Not Logged In</h4>
        <p>Please log in to view badges.</p>
      </div>
    );
  }

  return (
    <div className="badge-collection">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h2>Badge Collection</h2>
        <div>
          <span className="badge badge-primary badge-lg">
            {earnedCount} / {totalCount} Earned
          </span>
        </div>
      </div>

      {/* Filter and Sort Controls */}
      <div className="card mb-4">
        <div className="card-body">
          <div className="row">
            <div className="col-md-6">
              <label htmlFor="filterSelect" className="form-label">
                <strong>Filter:</strong>
              </label>
              <select
                id="filterSelect"
                className="form-control"
                value={filter}
                onChange={(e) => setFilter(e.target.value)}
              >
                <option value="all">All Badges</option>
                <option value="earned">Earned Only</option>
                <option value="locked">Locked Only</option>
              </select>
            </div>
            <div className="col-md-6">
              <label htmlFor="sortSelect" className="form-label">
                <strong>Sort By:</strong>
              </label>
              <select
                id="sortSelect"
                className="form-control"
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
              >
                <option value="rarity">Rarity</option>
                <option value="name">Name</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      {/* Badge Grid */}
      {sortedBadges.length === 0 ? (
        <div className="alert alert-info">
          <p className="mb-0">No badges found with the selected filter.</p>
        </div>
      ) : (
        <div className="row">
          {sortedBadges.map((badge) => (
            <div key={badge._id} className="col-md-4 col-lg-3 mb-4">
              <BadgeDisplay badge={badge} isEarned={badge.isEarned} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default BadgeCollection;
