"use client";

import { Button } from "@hexahost/ui";
import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { Link } from "@/i18n/navigation";
import { listServers } from "@/lib/api/servers";
import { ServerCard } from "./server-card";

export function ServerList() {
  const t = useTranslations("servers");
  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["servers"],
    queryFn: listServers,
  });

  if (isLoading) {
    return <p className="text-sm text-zinc-600 dark:text-zinc-400">{t("loading")}</p>;
  }

  if (isError) {
    return (
      <div className="space-y-3 rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-900 dark:bg-red-950/40">
        <p className="text-sm text-red-700 dark:text-red-300">{t("errors.loadFailed")}</p>
        <Button size="sm" variant="secondary" onClick={() => void refetch()}>
          {t("retry")}
        </Button>
      </div>
    );
  }

  const servers = data?.servers ?? [];

  if (servers.length === 0) {
    return (
      <div className="rounded-lg border border-dashed border-zinc-300 p-8 text-center dark:border-zinc-700">
        <h2 className="text-lg font-medium text-zinc-900 dark:text-zinc-50">{t("emptyTitle")}</h2>
        <p className="mt-2 text-sm text-zinc-600 dark:text-zinc-400">{t("emptyDescription")}</p>
        <Link
          href="/servers/new"
          className="mt-4 inline-flex h-10 items-center rounded-md bg-sky-600 px-4 text-sm font-medium text-white hover:bg-sky-500 dark:bg-sky-500 dark:hover:bg-sky-400"
        >
          {t("create")}
        </Link>
      </div>
    );
  }

  return (
    <div className="grid gap-4 md:grid-cols-2">
      {servers.map((server) => (
        <ServerCard key={server.id} server={server} />
      ))}
    </div>
  );
}
