import { useEffect } from "react";
import { useInfoSocket } from "../../../../app/context/WebSocketContext";
import Card from "../../../../ui/Card";
import CardHeader from "../../../../ui/CardHeader";
import DownloadLogButton from "./StatusItems/DownloadLogButton";
import StatusItemLocal from "./StatusItems/StatusItemLocal";
import StatusItemUTC from "./StatusItems/StatusItemUTC";
import StatusReads from "./StatusItems/StatusReads";
import { useGetStore } from "../../hooks/useGetStore";

const SystemStatusCard = () => {
  const { data: stats } = useInfoSocket();
  const { storeQuery } = useGetStore();

  const reads = storeQuery?.data;
  const isReadsLoading = storeQuery?.isFetching;
  const isError = storeQuery?.isError || !storeQuery?.data;

  useEffect(() => {
    storeQuery.refetch();
  }, [reads]);

  if (isError) {
    return (
      <Card className="p-4">
        <CardHeader title="System Status" />
        <span className="text-red-500">Error loading system status.</span>
      </Card>
    );
  }
  return (
    <Card className="p-4">
      <CardHeader title="System Status" />
      {stats ? (
        <div className="grid grid-cols-2 grid-rows-2 gap-4 col-span-2">
          <StatusItemUTC statusInfoItem={stats["system-clock-utc"]} description={"UTC Time"} />
          <StatusItemLocal statusInfoItem={stats["system-clock-local"]} description={"Local Time"} />
          <DownloadLogButton />
          <StatusReads reads={reads} isReadsLoading={isReadsLoading} />
        </div>
      ) : (
        <span className="text-slate-500">Loading system status…</span>
      )}
      <div className="text-sm flex gap-4"></div>
    </Card>
  );
};

export default SystemStatusCard;
