import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import DepartmentCard from "./DepartmentCard";
import DepartmentHeader from "./DepartmentHeader";
import DepartmentEmployeesModal from "./DepartmentEmployeesModal";
import DepartmentProjectsModal from "./DepartmentProjectsModal";
import { FaSpinner, FaExclamationTriangle } from "react-icons/fa";
import { buildApiUrl, API_ENDPOINTS } from "../../utils/config";

const DepartmentsGrid = () => {
  const { isLight } = useTheme();
  const [departmentsData, setDepartmentsData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Modal state
  const [employeesModalOpen, setEmployeesModalOpen] = useState(false);
  const [projectsModalOpen, setProjectsModalOpen] = useState(false);
  const [selectedDepartment, setSelectedDepartment] = useState(null);

  // Color mapping for different departments
  const departmentColors = {
    "software and lms": "blue",
    hr: "green",
    marketing: "purple",
    finance: "yellow",
    operations: "red",
    design: "pink",
    sales: "indigo",
  };

  const getColorForDepartment = (name) => {
    const key = name.toLowerCase();
    return departmentColors[key] || "gray";
  };

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

      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.DIVISION_EMPLOYEE_COUNT_BY_NAME_ACCURATE)
      );

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const apiData = await response.json();

      // Map API data to format expected by DepartmentCard
      const mappedData = apiData.map((dept) => ({
        id: dept.division_id,
        name: dept.division_name,
        employees: dept.employee_count,
        projects: dept.project_count,
        color: getColorForDepartment(dept.division_name),
      }));

      setDepartmentsData(mappedData);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

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

  // Handle opening employees modal
  const handleOpenEmployeesModal = (department) => {
    setSelectedDepartment(department);
    setEmployeesModalOpen(true);
  };

  // Handle opening projects modal
  const handleOpenProjectsModal = (department) => {
    setSelectedDepartment(department);
    setProjectsModalOpen(true);
  };

  // Handle closing modals
  const handleCloseEmployeesModal = () => {
    setEmployeesModalOpen(false);
    setSelectedDepartment(null);
  };

  const handleCloseProjectsModal = () => {
    setProjectsModalOpen(false);
    setSelectedDepartment(null);
  };

  if (loading) {
    return (
      <div className="space-y-3">
        <DepartmentHeader />
        <div
          className={`flex items-center justify-center py-12 ${
            isLight ? "text-amber-600" : "text-gray-300"
          }`}
        >
          <FaSpinner className="animate-spin text-2xl mr-3" />
          <span className="text-lg">Loading departments...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-3">
        <DepartmentHeader />
        <div
          className={`flex flex-col items-center justify-center py-12 ${
            isLight ? "text-red-600" : "text-red-400"
          }`}
        >
          <FaExclamationTriangle className="text-3xl mb-3" />
          <h3 className="text-lg font-semibold mb-2">
            Error Loading Departments
          </h3>
          <p className="text-sm mb-4">{error}</p>
          <button
            onClick={fetchDepartments}
            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
              isLight
                ? "bg-amber-500 hover:bg-amber-600 text-white"
                : "bg-blue-600 hover:bg-blue-700 text-white"
            }`}
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  if (departmentsData.length === 0) {
    return (
      <div className="space-y-3">
        <DepartmentHeader />
        <div
          className={`text-center py-12 ${
            isLight ? "text-amber-600" : "text-gray-300"
          }`}
        >
          <h3 className="text-lg font-semibold mb-2">No Departments Found</h3>
          <p className="text-sm">
            No department data is ailable at the moment.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <DepartmentHeader />
      <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
        {departmentsData.map((department) => (
          <DepartmentCard
            key={department.id}
            department={department}
            onOpenEmployeesModal={handleOpenEmployeesModal}
            onOpenProjectsModal={handleOpenProjectsModal}
          />
        ))}
      </div>

      {/* Single Employees Modal */}
      {selectedDepartment && (
        <DepartmentEmployeesModal
          isOpen={employeesModalOpen}
          onClose={handleCloseEmployeesModal}
          department={selectedDepartment}
        />
      )}

      {/* Single Projects Modal */}
      {selectedDepartment && (
        <DepartmentProjectsModal
          isOpen={projectsModalOpen}
          onClose={handleCloseProjectsModal}
          department={selectedDepartment}
        />
      )}
    </div>
  );
};

export default DepartmentsGrid;
