import React, { useState, useEffect } from "react";
import StatsCard from "./StatsCard";
import { FaUsers, FaProjectDiagram, FaBuilding, FaTasks } from "react-icons/fa";
import { buildApiUrl, API_ENDPOINTS } from "../../utils/config";

const StatsGrid = () => {
  const [totalEmployees, setTotalEmployees] = useState(0);
  const [totalProjects, setTotalProjects] = useState(0);
  const [totalDepartments, setTotalDepartments] = useState(0);
  const [completedTasks, setCompletedTasks] = useState(0);
  const [loading, setLoading] = useState(true);
  const [lastUpdated, setLastUpdated] = useState(new Date());

  // Fetch total employee, project, department, and completed tasks counts
  const fetchData = async () => {
    try {
      setLoading(true);

      // Fetch employee count
      const employeeResponse = await fetch(
        buildApiUrl(API_ENDPOINTS.EMPLOYEE_COUNT)
      );
      if (employeeResponse.ok) {
        const employeeData = await employeeResponse.json();
        setTotalEmployees(employeeData.total_employees);
      }

      // Fetch project count
      const projectResponse = await fetch(
        buildApiUrl(API_ENDPOINTS.ACTIVE_PROJECTS_COUNT)
      );
      if (projectResponse.ok) {
        const projectData = await projectResponse.json();
        setTotalProjects(projectData.active_projects);
      }

      // Fetch department count
      const departmentResponse = await fetch(
        buildApiUrl(API_ENDPOINTS.DIVISION_COUNT)
      );
      if (departmentResponse.ok) {
        const departmentData = await departmentResponse.json();
        setTotalDepartments(departmentData.total_departments);
      }

      // Fetch completed tasks count
      const tasksResponse = await fetch(
        buildApiUrl(API_ENDPOINTS.COMPLETED_TASKS_COUNT)
      );
      if (tasksResponse.ok) {
        const tasksData = await tasksResponse.json();
        setCompletedTasks(tasksData.completed_tasks);
      }

      setLastUpdated(new Date());
    } catch (error) {
      console.error("Error fetching data:", error);
      setTotalEmployees(0);
      setTotalProjects(0);
      setTotalDepartments(0);
      setCompletedTasks(0);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();

    // Auto-refresh every 5 minutes
    const interval = setInterval(fetchData, 5 * 60 * 1000);

    return () => clearInterval(interval);
  }, []);

  const statsData = [
    {
      title: "Total Employees",
      value: loading ? "..." : totalEmployees.toString(),
      icon: <FaUsers />,
      color: "blue",
      description: "Active team members",
    },
    {
      title: "Active Projects",
      value: loading ? "..." : totalProjects.toString(),
      icon: <FaProjectDiagram />,
      color: "green",
      description: "Ongoing initiatives",
    },
    {
      title: "Departments",
      value: loading ? "..." : totalDepartments.toString(),
      icon: <FaBuilding />,
      color: "purple",
      description: "Company divisions",
    },
    {
      title: "Completed Projects",
      value: loading ? "..." : completedTasks.toString(),
      icon: <FaTasks />,
      color: "orange",
      description: "Finished projects",
    },
  ];

  return (
    <div className="w-full">
      {/* Mobile: 2x2 Grid, Tablet: 2x2, Desktop: 1x4 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 lg:gap-6">
        {statsData.map((stat, index) => (
          <StatsCard key={index} stat={stat} />
        ))}
      </div>
    </div>
  );
};

export default StatsGrid;
