import { Card } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import type { MinimalServers } from "@/models/minimal_servers";
import { useQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/server_list")({
  component: RouteComponent,
});

function RouteComponent() {
  const { data: servers } = useQuery({
    queryKey: ["servers"],
    queryFn: async () => {
      let res = await fetch("/api/servers");
      return (await res.json()) as MinimalServers;
    },
  });
  return (
    <div className="p-2 flex justify-center items-center w-full">
      <Card className="w-full max-w-225 p-2">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[100px]">Name</TableHead>
              <TableHead>Hostname</TableHead>
              <TableHead>Nickame</TableHead>
              <TableHead className="text-right">Type/Template</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {servers?.map((server) => (
              <TableRow key={server.id}>
                <TableCell className="font-medium">{server.name}</TableCell>
                <TableCell>{server.hostname}</TableCell>
                <TableCell>{server.nickname}</TableCell>
                <TableCell className="text-right">
                  {server.template.name}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
          <TableFooter>
            <TableRow>
              <TableCell colSpan={3}>Total Servers</TableCell>
              <TableCell className="text-right">{servers?.length}</TableCell>
            </TableRow>
          </TableFooter>
        </Table>
      </Card>
    </div>
  );
}
