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

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

/**
 * Profile component displays user profile information, adopted streets, and badges
 */
const Profile = () => {
  const { auth } = useContext(AuthContext);
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Load user profile from API
  const loadProfile = useCallback(async () => {
    if (!auth.user) {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      const userId = auth.user.id || auth.user._id;
      const res = await axios.get(`/api/users/${userId}`);
      setUser(res.data);
    } catch (err) {
      console.error("Error loading profile:", err);
      const errorMessage =
        err.response?.data?.msg ||
        err.response?.data?.message ||
        "Failed to load profile. Please try again later.";
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, [auth.user]);

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

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

  if (error) {
    return (
      <div className="alert alert-danger m-3" role="alert">
        <h4 className="alert-heading">Error Loading Profile</h4>
        <p>{error}</p>
        <hr />
        <button className="btn btn-primary" onClick={loadProfile}>
          Retry
        </button>
      </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 your profile.</p>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="alert alert-info m-3" role="alert">
        <h4 className="alert-heading">No Profile Data</h4>
        <p>Unable to load profile information.</p>
        <button className="btn btn-primary" onClick={loadProfile}>
          Retry
        </button>
      </div>
    );
  }

  return (
    <div data-testid="profile-container">
      <h1>{user.name}'s Profile</h1>

      <div className="card mb-4" data-testid="profile-info-card">
        <div className="card-body">
          <h5 className="card-title">Profile Information</h5>
          <p className="card-text" data-testid="profile-email">
            <strong>Email:</strong> {user.email}
          </p>
          <p className="card-text" data-testid="profile-points">
            <strong>Points:</strong>{" "}
            <span className="badge badge-primary">{user.points || 0}</span>
          </p>
          {user.isPremium && (
            <p className="card-text" data-testid="premium-badge">
              <span className="badge badge-warning">Premium Member</span>
            </p>
          )}
        </div>
      </div>

      <div className="card mb-4" data-testid="adopted-streets-card">
        <div className="card-body">
          <h5 className="card-title">Adopted Streets</h5>
          {user.adoptedStreets && user.adoptedStreets.length > 0 ? (
            <ul className="list-group" data-testid="streets-list">
              {user.adoptedStreets.map((street) => (
                <li key={street._id || street} className="list-group-item" data-testid={`street-item-${street._id || street}`}>
                  {street.name || street}
                  {street.status && (
                    <span
                      className={`badge badge-${
                        street.status === "available" ? "success" : "primary"
                      } ml-2`}
                      data-testid={`street-status-${street._id || street}`}
                    >
                      {street.status}
                    </span>
                  )}
                </li>
              ))}
            </ul>
          ) : (
            <p className="text-muted" data-testid="no-streets-message">
              You haven't adopted any streets yet. Visit the map to adopt a
              street!
            </p>
          )}
        </div>
      </div>

      <div className="card mb-4" data-testid="badges-card">
        <div className="card-body">
          <h5 className="card-title">Badges</h5>
          {user.badges && user.badges.length > 0 ? (
            <ul className="list-group" data-testid="badges-list">
              {user.badges.map((badge, index) => (
                <li key={index} className="list-group-item" data-testid={`badge-item-${index}`}>
                  <span className="badge badge-success mr-2" data-testid={`badge-${badge}`}>
                    {badge}
                  </span>
                </li>
              ))}
            </ul>
          ) : (
            <p className="text-muted" data-testid="no-badges-message">
              No badges earned yet. Complete tasks and participate in events to
              earn badges!
            </p>
          )}
        </div>
      </div>

      {user.tasksCompleted !== undefined && (
        <div className="card mb-4" data-testid="statistics-card">
          <div className="card-body">
            <h5 className="card-title">Statistics</h5>
            <p className="card-text" data-testid="tasks-completed">
              <strong>Tasks Completed:</strong>{" "}
              <span className="badge badge-info">{user.tasksCompleted}</span>
            </p>
            {user.eventsAttended !== undefined && (
              <p className="card-text" data-testid="events-attended">
                <strong>Events Attended:</strong>{" "}
                <span className="badge badge-info">{user.eventsAttended}</span>
              </p>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default Profile;
