"use client";

import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { invoke } from "@tauri-apps/api/core";
import { toast } from "sonner";
import AppCard from "./app-card";

type App = {
  id: string;
  name: string;
  address: string;
  description?: string;
  ssh_address?: string;
};

export default function AppGrid() {
  const getApps = async () => {
    const apps: App[] = await invoke("get_app");
    return apps;
  };

  const {
    data: apps,
    isSuccess,
    isError,
    error,
  } = useQuery({
    queryKey: ["apps"],
    queryFn: getApps,
  });

  useEffect(() => {
    if (isError) {
      toast.error(`Error fetching apps: ${error}`);
    }
  }, [isError, error]);

  return (
    <div className="grid xs:grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 m-4">
      {isSuccess &&
        apps &&
        apps.map((app) => <AppCard app={app} key={app.id} />)}
      {isSuccess && apps && apps.length === 0 && (
        <div className="col-span-full text-center text-gray-500">
          No apps found. Click the "+" button to add a new app.
        </div>
      )}
    </div>
  );
}
