import type { SystemHealthStatus } from "../../../types/types";
import StatusGridItem from "./statusGridItem/StatusGridItem";

type SystemHealthProps = {
  startTime: string;
  uptime: string;
  statuses: SystemHealthStatus[];
  isLoading: boolean;
  isError: boolean;
  dateUpdatedAt?: number;
};

const SystemHealth = ({ startTime, uptime, statuses, isLoading, isError, dateUpdatedAt }: SystemHealthProps) => {
  const updatedDate = dateUpdatedAt ? new Date(dateUpdatedAt).toLocaleString() : null;

  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 categoryDefault = statusCategories?.default ?? [];

  if (isError) {
    return <span className="text-red-500">Error loading system health.</span>;
  }
  if (isLoading) {
    return <span className="text-slate-500">Loading system health…</span>;
  }
  return (
    <div className="h-100 md:h-75 overflow-y-auto flex flex-col gap-4">
      <div className="p-2 border-b border-gray-600 grid grid-cols-2 justify-between">
        <div className="flex flex-col border border-gray-600 p-4 rounded-lg mr-4 hover:bg-[#233241]">
          <h3 className="text-lg">Start Time</h3> <span className="text-slate-300">{startTime}</span>
        </div>
        <div className="flex flex-col border border-gray-600 p-4 rounded-lg mr-4 hover:bg-[#233241]">
          <h3 className="text-lg">Up Time</h3> <span className="text-slate-300">{uptime}</span>
        </div>
      </div>
      <div className="overflow-auto gap-4">
        <StatusGridItem title={"Modules"} statusCategory={categoryDefault} />
      </div>
      <div className="border-t border-gray-500">
        <small className="italic text-gray-400">{`Last refeshed ${updatedDate}`}</small>
      </div>
    </div>
  );
};

export default SystemHealth;
