import { Button } from "@minmon/ui/components/button";
import { StatusBadge } from "@minmon/ui/components/status-badge";
import { useMutation, useQuery } from "@tanstack/react-query";
import { createFileRoute, Link } from "@tanstack/react-router";
import { toast } from "sonner";

import { ConfirmDeleteIconButton, PageSection, QueryStateCard, ResourceListCard } from "@/components/dashboard-ui";
import { queryClient, trpc, trpcClient } from "@/utils/trpc";

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

function serverStatusVariant(status: "active" | "maintenance" | "inactive") {
  if (status === "active") return "success" as const;
  if (status === "maintenance") return "warning" as const;
  return "neutral" as const;
}

function RouteComponent() {
  const servers = useQuery(trpc.servers.list.queryOptions());
  const removeServer = useMutation({
    mutationFn: async (id: string) => trpcClient.servers.delete.mutate({ id }),
    onSuccess: async () => {
      toast.success("Server deleted");
      await queryClient.invalidateQueries();
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  if (servers.isLoading) {
    return (
      <QueryStateCard
        title="Loading servers"
        description="Fetching the current server inventory from the protected dashboard API."
      />
    );
  }

  if (servers.isError || !servers.data) {
    return (
      <QueryStateCard
        title="Servers unavailable"
        description="The server list could not be loaded right now."
      />
    );
  }

  return (
    <PageSection
      title="Servers"
      description="Manage server inventory, IP addresses, operating systems, and current status."
      action={
        <Link to="/dashboard/servers/new">
          <Button>Add server</Button>
        </Link>
      }
    >
      <ResourceListCard
        title="Server list"
        description="Each server can have many services and notes. Deleting a server also removes its related records."
        columns={[
          {
            key: "name",
            header: "Server",
            render: (item: (typeof servers.data)[number]) => (
              <div className="grid gap-1">
                <Link
                  to="/dashboard/servers/$serverId"
                  params={{ serverId: item.id }}
                  className="font-medium hover:underline"
                >
                  {item.name}
                </Link>
                <span className="text-xs text-muted-foreground">{item.description || "No description"}</span>
              </div>
            ),
          },
          {
            key: "primaryIpAddress",
            header: "Primary IP",
            render: (item: (typeof servers.data)[number]) => item.primaryIpAddress,
          },
          {
            key: "location",
            header: "Location / Provider",
            render: (item: (typeof servers.data)[number]) => [item.location, item.provider].filter(Boolean).join(" / ") || "-",
          },
          {
            key: "status",
            header: "Status",
            className: "w-32",
            render: (item: (typeof servers.data)[number]) => (
              <StatusBadge variant={serverStatusVariant(item.status)}>{item.status}</StatusBadge>
            ),
          },
          {
            key: "actions",
            header: "Actions",
            className: "w-16",
            render: (item: (typeof servers.data)[number]) => (
              <ConfirmDeleteIconButton
                itemLabel={`server ${item.name}`}
                disabled={removeServer.isPending}
                onConfirm={() => removeServer.mutate(item.id)}
              />
            ),
          },
        ]}
        items={servers.data}
        emptyTitle="No servers added"
        emptyDescription="Add your first server to start managing services, notes, and domains."
      />
    </PageSection>
  );
}
