"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 [os, setOs] = useState<"linux" | "windows">("linux");

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

  const command = os === "windows" ? result?.install_command_ps : result?.install_command;

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

  return (
    <div className="p-4 sm:p-6 lg: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 Vantage 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 Vantage 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>
              <div className="mb-4 flex gap-2">
                {(["linux", "windows"] as const).map((o) => (
                  <button
                    key={o}
                    onClick={() => { setOs(o); setCopied(false); }}
                    className={`rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors ${
                      os === o
                        ? "border-accent bg-accent/10 text-accent"
                        : "border-border bg-surface-2 text-text-secondary hover:border-accent/40 hover:text-text-primary"
                    }`}
                  >
                    {o === "linux" ? "Linux (bash)" : "Windows (PowerShell)"}
                  </button>
                ))}
              </div>

              <p className="mb-4 text-sm text-text-secondary">
                {os === "windows" ? (
                  <>Run this in an <strong className="text-text-primary">elevated PowerShell</strong> (Run as Administrator):</>
                ) : (
                  <>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-well 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">{os === "windows" ? "PS>" : "$"}</span>{" "}
                  <span className="text-text-primary">{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/vantage/config.yaml with the server ID and token",
                  "Installs and starts the vantage-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>
  );
}
