"use client";

import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { api, NewServerResponse } from "@/lib/api";
import { Button, Card, CardHeader, CardTitle } from "@/components/ui";

export default function NewServerPage() {
  const [result, setResult] = useState<NewServerResponse | null>(null);
  const [copied, setCopied] = useState(false);

  const { mutate: createServer, isPending, error } = useMutation({
    mutationFn: api.createServer,
    onSuccess: (data) => setResult(data),
  });

  const handleCopy = async () => {
    if (!result?.install_command) return;
    await navigator.clipboard.writeText(result.install_command);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="p-8">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-text-primary">Add Server</h1>
        <p className="mt-1 text-sm text-text-secondary">
          Generate an install command to register a new server with the KeyManager agent.
        </p>
      </div>

      <div className="max-w-2xl space-y-6">
        {!result ? (
          <Card>
            <CardHeader>
              <CardTitle>Generate Install Command</CardTitle>
            </CardHeader>
            <p className="mb-6 text-sm text-text-secondary leading-relaxed">
              Click the button below to generate a one-time install command. The command
              contains a short-lived token (valid for 1 hour) that registers your server
              and installs the KeyManager agent automatically.
            </p>

            {error && (
              <div className="mb-4 rounded-lg border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">
                Failed to generate install command. Make sure the backend is running.
              </div>
            )}

            <Button
              variant="primary"
              loading={isPending}
              onClick={() => createServer()}
            >
              Generate Install Command
            </Button>
          </Card>
        ) : (
          <>
            <Card>
              <CardHeader>
                <CardTitle>Install Command</CardTitle>
                <span className="rounded-full bg-success/15 px-2.5 py-0.5 text-xs font-medium text-success border border-success/30">
                  Valid for 1 hour
                </span>
              </CardHeader>
              <p className="mb-4 text-sm text-text-secondary">
                Run this command on the target server as <code className="rounded bg-surface-2 px-1 py-0.5 text-xs font-mono text-text-primary">root</code>:
              </p>

              <div className="relative rounded-lg border border-border bg-[#0a0c14] p-4 font-mono text-sm">
                <pre className="overflow-x-auto whitespace-pre-wrap break-all text-text-secondary leading-relaxed">
                  <span className="text-accent">$</span>{" "}
                  <span className="text-text-primary">{result.install_command}</span>
                </pre>
                <button
                  onClick={handleCopy}
                  className="absolute right-3 top-3 rounded-md border border-border bg-surface-2 px-2.5 py-1 text-xs font-medium text-text-secondary transition-colors hover:border-accent/50 hover:text-text-primary"
                >
                  {copied ? (
                    <span className="text-success">Copied!</span>
                  ) : (
                    "Copy"
                  )}
                </button>
              </div>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Server Details</CardTitle>
              </CardHeader>
              <dl className="space-y-3 text-sm">
                <div className="flex items-center justify-between">
                  <dt className="text-text-secondary">Server ID</dt>
                  <dd className="font-mono text-text-primary">{result.server_id}</dd>
                </div>
                <div className="flex items-center justify-between border-t border-border pt-3">
                  <dt className="text-text-secondary">Status</dt>
                  <dd className="text-warning">Pending registration</dd>
                </div>
              </dl>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>What happens next?</CardTitle>
              </CardHeader>
              <ol className="space-y-3 text-sm text-text-secondary">
                {[
                  "The install script detects your CPU architecture (amd64 / arm64)",
                  "Downloads and verifies the latest agent binary from the Gitea release",
                  "Writes /etc/keymanager/config.yaml with the server ID and token",
                  "Installs and starts the keymanager-agent systemd service",
                  "The agent calls Register() to obtain a persistent auth token",
                  "The server status changes to active on the first successful sync",
                ].map((step, i) => (
                  <li key={i} className="flex gap-3">
                    <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-accent/20 text-xs font-semibold text-accent">
                      {i + 1}
                    </span>
                    {step}
                  </li>
                ))}
              </ol>
            </Card>

            <div className="flex gap-3">
              <Button variant="secondary" onClick={() => { setResult(null); setCopied(false); }}>
                Generate Another
              </Button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
