import type { SystemHealthStatus } from "../../../types/types";
import { useGetSystemHealth } from "../hooks/useGetSystemHealth";
import CameraStatus from "./cameraStatus/CameraStatus";
import SystemHealthCard from "./systemHealth/SystemHealthCard";
import SystemStatusCard from "./systemStatus/SystemStatusCard";
import { CAMERA_IDS } from "../../../app/config/cameraConfig";

const DashboardGrid = () => {
  const { query } = useGetSystemHealth();
  const startTime = query?.data?.StartTimeHumane;
  const uptime = query?.data?.UptimeHumane;
  const statuses: SystemHealthStatus[] = query?.data?.Status;
  const isLoading = query?.isLoading;
  const isError = query?.isError;
  const dateUpdatedAt = query?.dataUpdatedAt;
  const refetch = query?.refetch;

  const statusCategories = statuses?.reduce<Record<string, SystemHealthStatus[]>>(
    (acc, cur) => {
      if (cur?.groupID === "ChannelA") acc?.channelA?.push(cur);
      if (cur?.groupID === "ChannelB") acc?.channelB?.push(cur);
      if (cur?.groupID === "ChannelC") acc?.channelC?.push(cur);
      if (cur?.groupID === "Default") acc?.default?.push(cur);
      return acc;
    },
    {
      channelA: [],
      channelB: [],
      channelC: [],
      // todo: check if more cameras will be added later
      default: [],
    },
  );

  return (
    <div className="grid grid-cols-1 md:grid-rows-2 md:grid-cols-2 gap-4">
      <div className="grid grid-cols-1 md:grid-rows-0 md:grid-cols-2 gap-4 md:col-span-2">
        <SystemStatusCard />
        <SystemHealthCard
          startTime={startTime}
          uptime={uptime}
          statuses={statuses}
          isLoading={isLoading}
          isError={isError}
          dateUpdatedAt={dateUpdatedAt}
          refetch={refetch}
        />
      </div>

      <div className="grid grid-cols-1 md:col-span-2 md:grid-cols-[repeat(3,1fr)] gap-x-4">
        {CAMERA_IDS.map((cameraID) => (
          <CameraStatus
            key={cameraID}
            title={`Camera ${cameraID}`}
            category={statusCategories?.[`channel${cameraID}`] ?? []}
            isError={isError}
          />
        ))}
      </div>
    </div>
  );
};

export default DashboardGrid;
