"use client";

import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle } from "@hexahost/ui";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { Link } from "@/i18n/navigation";
import { ApiError } from "@/lib/api/auth";
import {
  type Server,
  startServer,
  stopServer,
} from "@/lib/api/servers";
import { ServerStatusBadge } from "./server-status-badge";

interface ServerCardProps {
  server: Server;
  showDetailsLink?: boolean;
}

export function ServerCard({ server, showDetailsLink = true }: ServerCardProps) {
  const t = useTranslations("servers");
  const queryClient = useQueryClient();
  const [actionError, setActionError] = useState<string | null>(null);

  const startMutation = useMutation({
    mutationFn: () => startServer(server.id),
    onSuccess: () => {
      setActionError(null);
      void queryClient.invalidateQueries({ queryKey: ["servers"] });
      void queryClient.invalidateQueries({ queryKey: ["server", server.id] });
    },
    onError: (error: unknown) => {
      setActionError(error instanceof ApiError ? (error.detail ?? error.title) : t("errors.generic"));
    },
  });

  const stopMutation = useMutation({
    mutationFn: () => stopServer(server.id),
    onSuccess: () => {
      setActionError(null);
      void queryClient.invalidateQueries({ queryKey: ["servers"] });
      void queryClient.invalidateQueries({ queryKey: ["server", server.id] });
    },
    onError: (error: unknown) => {
      setActionError(error instanceof ApiError ? (error.detail ?? error.title) : t("errors.generic"));
    },
  });

  const canStart = server.status === "STOPPED";
  const canStop = server.status === "RUNNING";
  const isBusy = ["PROVISIONING", "INSTALLING", "STARTING", "STOPPING"].includes(server.status);
  const address =
    server.hostPort !== null ? `localhost:${server.hostPort}` : t("addressPending");

  return (
    <Card>
      <CardHeader className="flex flex-row items-start justify-between gap-4 space-y-0">
        <div className="min-w-0 space-y-1">
          <CardTitle className="truncate text-lg">{server.name}</CardTitle>
          <CardDescription>
            {server.softwareFamily} · {server.minecraftVersion}
          </CardDescription>
        </div>
        <ServerStatusBadge status={server.status} label={t(`status.${server.status}`)} />
      </CardHeader>
      <CardContent className="space-y-4">
        <dl className="grid gap-2 text-sm sm:grid-cols-2">
          <div>
            <dt className="text-zinc-500 dark:text-zinc-400">{t("address")}</dt>
            <dd className="font-mono text-zinc-900 dark:text-zinc-100">{address}</dd>
          </div>
          <div>
            <dt className="text-zinc-500 dark:text-zinc-400">{t("ram")}</dt>
            <dd className="text-zinc-900 dark:text-zinc-100">{server.ramMb} MB</dd>
          </div>
        </dl>

        {actionError ? (
          <p className="text-sm text-red-600 dark:text-red-400" role="alert">
            {actionError}
          </p>
        ) : null}

        <div className="flex flex-wrap gap-2">
          <Button
            size="sm"
            onClick={() => startMutation.mutate()}
            disabled={!canStart || isBusy || startMutation.isPending || stopMutation.isPending}
          >
            {t("start")}
          </Button>
          <Button
            size="sm"
            variant="secondary"
            onClick={() => stopMutation.mutate()}
            disabled={!canStop || isBusy || startMutation.isPending || stopMutation.isPending}
          >
            {t("stop")}
          </Button>
          {showDetailsLink ? (
            <Link
              href={`/servers/${server.id}`}
              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("details")}
            </Link>
          ) : null}
        </div>
      </CardContent>
    </Card>
  );
}
