import React, { useState, useEffect } from "react";
import axios from "axios";
import ActivityChart from "./ActivityChart";
import ContributorsList from "./ContributorsList";
import StreetStatsChart from "./StreetStatsChart";
import PersonalStats from "./PersonalStats";
import "./Analytics.css";

const Analytics = () => {
  const [overview, setOverview] = useState(null);
  const [activity, setActivity] = useState(null);
  const [contributors, setContributors] = useState([]);
  const [streetStats, setStreetStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [timeframe, setTimeframe] = useState("30d");
  const [groupBy, setGroupBy] = useState("day");
  const [activeTab, setActiveTab] = useState("overview");

  const fetchAnalyticsData = async () => {
    setLoading(true);
    setError(null);

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

      const [overviewRes, activityRes, contributorsRes, streetStatsRes] = await Promise.all([
        axios.get(`/api/analytics/overview?timeframe=${timeframe}`, config),
        axios.get(`/api/analytics/activity?timeframe=${timeframe}&groupBy=${groupBy}`, config),
        axios.get(`/api/analytics/top-contributors?limit=10&timeframe=${timeframe}`, config),
        axios.get(`/api/analytics/street-stats?timeframe=${timeframe}`, config),
      ]);

      setOverview(overviewRes.data.overview);
      setActivity(activityRes.data);
      setContributors(contributorsRes.data.contributors);
      setStreetStats(streetStatsRes.data);
    } catch (err) {
      console.error("Error fetching analytics:", err);
      setError(err.response?.data?.msg || "Failed to load analytics data");
    } finally {
      setLoading(false);
    }
  };

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

  const handleTimeframeChange = (e) => {
    setTimeframe(e.target.value);
  };

  const handleGroupByChange = (e) => {
    setGroupBy(e.target.value);
  };

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

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

  return (
    <div className="analytics-container">
      <div className="analytics-header">
        <h1>Analytics Dashboard</h1>
        <div className="analytics-controls">
          <div className="form-group">
            <label htmlFor="timeframe">Timeframe:</label>
            <select
              id="timeframe"
              className="form-select"
              value={timeframe}
              onChange={handleTimeframeChange}
            >
              <option value="7d">Last 7 Days</option>
              <option value="30d">Last 30 Days</option>
              <option value="90d">Last 90 Days</option>
              <option value="all">All Time</option>
            </select>
          </div>
          {activeTab === "activity" && (
            <div className="form-group">
              <label htmlFor="groupBy">Group By:</label>
              <select
                id="groupBy"
                className="form-select"
                value={groupBy}
                onChange={handleGroupByChange}
              >
                <option value="day">Day</option>
                <option value="week">Week</option>
                <option value="month">Month</option>
              </select>
            </div>
          )}
        </div>
      </div>

      <ul className="nav nav-tabs mb-4">
        <li className="nav-item">
          <button
            className={`nav-link ${activeTab === "overview" ? "active" : ""}`}
            onClick={() => setActiveTab("overview")}
          >
            Overview
          </button>
        </li>
        <li className="nav-item">
          <button
            className={`nav-link ${activeTab === "activity" ? "active" : ""}`}
            onClick={() => setActiveTab("activity")}
          >
            Activity
          </button>
        </li>
        <li className="nav-item">
          <button
            className={`nav-link ${activeTab === "personal" ? "active" : ""}`}
            onClick={() => setActiveTab("personal")}
          >
            My Stats
          </button>
        </li>
      </ul>

      {activeTab === "overview" && overview && (
        <div className="overview-tab">
          <div className="row">
            <div className="col-md-3 mb-4">
              <div className="stat-card">
                <div className="stat-icon bg-primary">
                  <i className="fas fa-users"></i>
                </div>
                <div className="stat-content">
                  <h3>{overview.totalUsers}</h3>
                  <p>Total Users</p>
                </div>
              </div>
            </div>

            <div className="col-md-3 mb-4">
              <div className="stat-card">
                <div className="stat-icon bg-success">
                  <i className="fas fa-road"></i>
                </div>
                <div className="stat-content">
                  <h3>{overview.adoptedStreets}</h3>
                  <p>Streets Adopted</p>
                  <small className="text-muted">
                    {overview.availableStreets} available
                  </small>
                </div>
              </div>
            </div>

            <div className="col-md-3 mb-4">
              <div className="stat-card">
                <div className="stat-icon bg-info">
                  <i className="fas fa-tasks"></i>
                </div>
                <div className="stat-content">
                  <h3>{overview.completedTasks}</h3>
                  <p>Tasks Completed</p>
                  <small className="text-muted">
                    {overview.pendingTasks} pending
                  </small>
                </div>
              </div>
            </div>

            <div className="col-md-3 mb-4">
              <div className="stat-card">
                <div className="stat-icon bg-warning">
                  <i className="fas fa-calendar"></i>
                </div>
                <div className="stat-content">
                  <h3>{overview.activeEvents}</h3>
                  <p>Active Events</p>
                  <small className="text-muted">
                    {overview.completedEvents} completed
                  </small>
                </div>
              </div>
            </div>
          </div>

          <div className="row mt-4">
            <div className="col-md-3 mb-4">
              <div className="stat-card">
                <div className="stat-icon bg-secondary">
                  <i className="fas fa-comments"></i>
                </div>
                <div className="stat-content">
                  <h3>{overview.totalPosts}</h3>
                  <p>Total Posts</p>
                </div>
              </div>
            </div>

            <div className="col-md-3 mb-4">
              <div className="stat-card">
                <div className="stat-icon bg-danger">
                  <i className="fas fa-star"></i>
                </div>
                <div className="stat-content">
                  <h3>{overview.totalPoints.toLocaleString()}</h3>
                  <p>Total Points</p>
                </div>
              </div>
            </div>

            <div className="col-md-3 mb-4">
              <div className="stat-card">
                <div className="stat-icon bg-dark">
                  <i className="fas fa-chart-line"></i>
                </div>
                <div className="stat-content">
                  <h3>{overview.averagePointsPerUser}</h3>
                  <p>Avg Points/User</p>
                </div>
              </div>
            </div>
          </div>

          <div className="row mt-4">
            <div className="col-lg-8 mb-4">
              <div className="card">
                <div className="card-header">
                  <h5>Street Statistics</h5>
                </div>
                <div className="card-body">
                  {streetStats && <StreetStatsChart data={streetStats} />}
                </div>
              </div>
            </div>

            <div className="col-lg-4 mb-4">
              <div className="card">
                <div className="card-header">
                  <h5>Top Contributors</h5>
                </div>
                <div className="card-body">
                  <ContributorsList contributors={contributors} />
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === "activity" && activity && (
        <div className="activity-tab">
          <div className="card">
            <div className="card-header">
              <h5>Activity Over Time</h5>
            </div>
            <div className="card-body">
              <ActivityChart data={activity.activity} groupBy={groupBy} />
            </div>
          </div>

          <div className="row mt-4">
            <div className="col-md-3">
              <div className="stat-card small">
                <h4>{activity.summary.totalTasks}</h4>
                <p>Total Tasks</p>
              </div>
            </div>
            <div className="col-md-3">
              <div className="stat-card small">
                <h4>{activity.summary.totalPosts}</h4>
                <p>Total Posts</p>
              </div>
            </div>
            <div className="col-md-3">
              <div className="stat-card small">
                <h4>{activity.summary.totalEvents}</h4>
                <p>Total Events</p>
              </div>
            </div>
            <div className="col-md-3">
              <div className="stat-card small">
                <h4>{activity.summary.totalStreetsAdopted}</h4>
                <p>Streets Adopted</p>
              </div>
            </div>
          </div>
        </div>
      )}

      {activeTab === "personal" && (
        <div className="personal-tab">
          <PersonalStats timeframe={timeframe} />
        </div>
      )}
    </div>
  );
};

export default Analytics;
