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";

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: [],
      default: [],
    },
  );

  const categoryA = statusCategories?.channelA ?? [];
  const categoryB = statusCategories?.channelB ?? [];
  const categoryC = statusCategories?.channelC ?? [];

  return (
    <div className="grid grid-cols-1 md:grid-rows-2 md:grid-cols-2">
      <SystemStatusCard />
      <SystemHealthCard
        startTime={startTime}
        uptime={uptime}
        statuses={statuses}
        isLoading={isLoading}
        isError={isError}
        dateUpdatedAt={dateUpdatedAt}
        refetch={refetch}
      />
      <div className="grid grid-cols-1 md:col-span-2 md:grid-cols-3">
        <CameraStatus title="Camera A" category={categoryA} />
        <CameraStatus title="Camera B" category={categoryB} />
        <CameraStatus title="Camera C" category={categoryC} />
      </div>
    </div>
  );
};

export default DashboardGrid;
