"use client";

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

interface ServerDetailContentProps {
  serverId: string;
}

export function ServerDetailContent({ serverId }: ServerDetailContentProps) {
  const t = useTranslations("servers");
  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["server", serverId],
    queryFn: () => getServer(serverId),
    refetchInterval: (query) => {
      const status = query.state.data?.status;
      if (!status) {
        return false;
      }
      return ["PROVISIONING", "INSTALLING", "STARTING", "STOPPING"].includes(status)
        ? 3000
        : false;
    },
  });

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

  if (isError || !data) {
    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>
        <div className="flex gap-2">
          <Button size="sm" variant="secondary" onClick={() => void refetch()}>
            {t("retry")}
          </Button>
          <Link
            href="/servers"
            className="inline-flex h-8 items-center rounded-md border border-zinc-300 bg-white px-3 text-sm font-medium text-zinc-900 hover:bg-zinc-50 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-100 dark:hover:bg-zinc-800"
          >
            {t("backToList")}
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight text-zinc-900 dark:text-zinc-50">
            {data.name}
          </h1>
          <p className="mt-1 text-sm text-zinc-600 dark:text-zinc-400">{t("detailSubtitle")}</p>
        </div>
        <Link
          href="/servers"
          className="inline-flex h-8 items-center text-sm font-medium text-sky-600 hover:text-sky-500 dark:text-sky-400"
        >
          {t("backToList")}
        </Link>
      </div>

      <ServerCard server={data} showDetailsLink={false} />
    </div>
  );
}
