import React, { useCallback, useEffect } from "react";
import { useSelector } from "react-redux";
import { useDashboardTeamsCardData } from "../../hooks/useDashboard_Data";
import eventBus from "../../services/eventBus";
import { useQueryClient } from "@tanstack/react-query";
import { useSelectedProject } from "../../slices/apiDataManager";
import { TeamsSkeleton } from "./DashboardSkeleton";

const Teams = () => {
  const queryClient = useQueryClient();
  const projectId = useSelectedProject();

  const {
    data: teamsCardData,
    isLoading,
    isError,
    error,
    isFetching,
    refetch,
  } = useDashboardTeamsCardData(projectId);

  // Handle real-time updates via eventBus
  const handler = useCallback(
    (msg) => {
      if (msg.activity === 1) {
        queryClient.setQueryData(["dashboardTeams", projectId], (old) => {
          if (!old) return old;
          return {
            ...old,
            inToday: (old.inToday || 0) + 1,
          };
        });
      }
    },
    [queryClient, projectId]
  );

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

  const inToday = teamsCardData?.inToday ?? 0;
  const totalEmployees = teamsCardData?.totalEmployees ?? 0;

  if (isLoading) return <TeamsSkeleton />;
  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>

      {isError ? (
        <div className="d-flex flex-column justify-content-center align-items-center  p-1">
          <i className="bx bx-error-circle bx-sm fs-2 "></i>

          <small className="text-muted mb-2">
            {error?.message || "Unable to load data at the moment."}
          </small>
          <span
            className={`text-muted ${
              isFetching ? "cursor-wait" : "cursor-pointer"
            }`}
            onClick={refetch}
          >
            <i
              className={`bx bx-refresh me-1 ${isFetching ? "bx-spin" : ""}`}
            ></i>{" "}
            Retry
          </span>
        </div>
      ) : (
        <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;
