import React, { useCallback, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { useDashboardTeamsCardData } from "../../hooks/useDashboard_Data";
import eventBus from "../../services/eventBus";

const Teams = () => {
  const projectId = useSelector((store) => store.localVariables?.projectId);
  const { teamsCardData, loading, error } = useDashboardTeamsCardData(projectId);

  const [totalEmployees, setTotalEmployee] = useState(0);
  const [inToday, setInToday] = useState(0);

  // Update state when API data arrives
  useEffect(() => {
    setTotalEmployee(teamsCardData?.totalEmployees || 0);
    setInToday(teamsCardData?.inToday || 0);
  }, [teamsCardData]);

  // Handle real-time updates via eventBus
  const handler = useCallback((msg) => {
    if (msg.activity === 1) {
      setInToday((prev) => prev + 1);
    }
  }, []);

  useEffect(() => {
    eventBus.on("attendance", handler);
    return () => eventBus.off("attendance", handler);
  }, [handler]);

  return (
    <div className="card p-3 h-100 text-center d-flex justify-content-between">
      <div className="d-flex justify-content-start align-items-center mb-3">
        <h5 className="fw-bold mb-0 ms-2">
          <i className="bx bx-group text-warning"></i> Teams
        </h5>
      </div>

      {loading ? (
        // Blue spinner loader
        <div className="d-flex justify-content-center align-items-center flex-grow-1">
          <div className="spinner-border text-primary" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
        </div>
      ) : error ? (
        // Error message if data fetching fails
        <div className="text-danger flex-grow-1 d-flex justify-content-center align-items-center">{error}</div>
      ) : (
        // Display data once loaded
        <div className="d-flex justify-content-around align-items-start mt-n2">
          <div>
            <h4 className="mb-0 fw-bold">{totalEmployees.toLocaleString()}</h4>
            <small className="text-muted">Total Employees</small>
          </div>
          <div>
            <h4 className="mb-0 fw-bold">{inToday.toLocaleString()}</h4>
            <small className="text-muted">In Today</small>
          </div>
        </div>
      )}
    </div>
  );
};

export default Teams;