import React, { useState, useEffect, useContext } from "react";
import axios from "axios";
import { AuthContext } from "../context/AuthContext";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
} from "recharts";
import "./PersonalStats.css";

const PersonalStats = ({ timeframe }) => {
  const { user } = useContext(AuthContext);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchPersonalStats = async () => {
    if (!user) return;

    setLoading(true);
    setError(null);

    try {
      const token = localStorage.getItem("token");
      const config = {
        headers: {
          "x-auth-token": token,
        },
      };

      const res = await axios.get(
        `/api/analytics/user/${user._id}?timeframe=${timeframe}`,
        config
      );

      setStats(res.data);
    } catch (err) {
      console.error("Error fetching personal stats:", err);
      setError(err.response?.data?.msg || "Failed to load personal statistics");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPersonalStats();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [timeframe, user]);

  if (loading) {
    return (
      <div className="text-center">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="alert alert-danger" role="alert">
        {error}
      </div>
    );
  }

  if (!stats) return null;

  const chartData = [
    { name: "Streets", value: stats.stats.streetsAdopted },
    { name: "Tasks", value: stats.stats.tasksCompleted },
    { name: "Posts", value: stats.stats.postsCreated },
    { name: "Events", value: stats.stats.eventsParticipated },
    { name: "Badges", value: stats.stats.badgesEarned },
  ];

  return (
    <div className="personal-stats">
      <div className="row mb-4">
        <div className="col-md-12">
          <div className="user-header">
            <h3>{stats.user.name}</h3>
            <div className="user-badges">
              {stats.user.isPremium && (
                <span className="badge bg-warning text-dark">Premium</span>
              )}
              <span className="badge bg-primary">{stats.user.points} Points</span>
            </div>
          </div>
        </div>
      </div>

      <div className="row mb-4">
        <div className="col-md-2">
          <div className="stat-box">
            <h4>{stats.stats.streetsAdopted}</h4>
            <p>Streets</p>
          </div>
        </div>
        <div className="col-md-2">
          <div className="stat-box">
            <h4>{stats.stats.tasksCompleted}</h4>
            <p>Tasks</p>
          </div>
        </div>
        <div className="col-md-2">
          <div className="stat-box">
            <h4>{stats.stats.postsCreated}</h4>
            <p>Posts</p>
          </div>
        </div>
        <div className="col-md-2">
          <div className="stat-box">
            <h4>{stats.stats.eventsParticipated}</h4>
            <p>Events</p>
          </div>
        </div>
        <div className="col-md-2">
          <div className="stat-box">
            <h4>{stats.stats.badgesEarned}</h4>
            <p>Badges</p>
          </div>
        </div>
        <div className="col-md-2">
          <div className="stat-box">
            <h4>{stats.stats.totalLikesReceived}</h4>
            <p>Likes</p>
          </div>
        </div>
      </div>

      <div className="row mb-4">
        <div className="col-md-6">
          <div className="card">
            <div className="card-header">
              <h5>Activity Overview</h5>
            </div>
            <div className="card-body">
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={chartData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Bar dataKey="value" fill="#0d6efd" />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>

        <div className="col-md-6">
          <div className="card">
            <div className="card-header">
              <h5>Points Summary</h5>
            </div>
            <div className="card-body">
              <div className="points-summary">
                <div className="points-row">
                  <span className="points-label">Points Earned:</span>
                  <span className="points-value text-success">
                    +{stats.stats.pointsEarned}
                  </span>
                </div>
                <div className="points-row">
                  <span className="points-label">Points Spent:</span>
                  <span className="points-value text-danger">
                    -{stats.stats.pointsSpent}
                  </span>
                </div>
                <hr />
                <div className="points-row">
                  <span className="points-label">
                    <strong>Current Balance:</strong>
                  </span>
                  <span className="points-value">
                    <strong>{stats.user.points}</strong>
                  </span>
                </div>
              </div>

              <div className="mt-4">
                <h6>Engagement Metrics</h6>
                <div className="engagement-metrics">
                  <div className="metric">
                    <span className="metric-icon">
                      <i className="fas fa-heart"></i>
                    </span>
                    <span className="metric-value">
                      {stats.stats.totalLikesReceived}
                    </span>
                    <span className="metric-label">Likes Received</span>
                  </div>
                  <div className="metric">
                    <span className="metric-icon">
                      <i className="fas fa-comment"></i>
                    </span>
                    <span className="metric-value">
                      {stats.stats.totalCommentsReceived}
                    </span>
                    <span className="metric-label">Comments Received</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {stats.recentActivity && (
        <div className="row">
          <div className="col-md-12">
            <div className="card">
              <div className="card-header">
                <h5>Recent Activity</h5>
              </div>
              <div className="card-body">
                <div className="row">
                  <div className="col-md-4">
                    <h6>Recent Tasks</h6>
                    {stats.recentActivity.tasks.length > 0 ? (
                      <ul className="list-unstyled">
                        {stats.recentActivity.tasks.map((task) => (
                          <li key={task._id} className="mb-2">
                            <small className="text-muted">
                              {new Date(task.completedAt || task.createdAt).toLocaleDateString()}
                            </small>
                            <div>{task.description}</div>
                          </li>
                        ))}
                      </ul>
                    ) : (
                      <p className="text-muted">No recent tasks</p>
                    )}
                  </div>

                  <div className="col-md-4">
                    <h6>Recent Posts</h6>
                    {stats.recentActivity.posts.length > 0 ? (
                      <ul className="list-unstyled">
                        {stats.recentActivity.posts.map((post) => (
                          <li key={post._id} className="mb-2">
                            <small className="text-muted">
                              {new Date(post.createdAt).toLocaleDateString()}
                            </small>
                            <div>{post.content.substring(0, 50)}...</div>
                          </li>
                        ))}
                      </ul>
                    ) : (
                      <p className="text-muted">No recent posts</p>
                    )}
                  </div>

                  <div className="col-md-4">
                    <h6>Recent Events</h6>
                    {stats.recentActivity.events.length > 0 ? (
                      <ul className="list-unstyled">
                        {stats.recentActivity.events.map((event) => (
                          <li key={event._id} className="mb-2">
                            <small className="text-muted">
                              {new Date(event.date).toLocaleDateString()}
                            </small>
                            <div>{event.title}</div>
                          </li>
                        ))}
                      </ul>
                    ) : (
                      <p className="text-muted">No recent events</p>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default PersonalStats;
