"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Server, Loader2, Lock, KeyRound } from "lucide-react";
import { Shell } from "@/components/layout/shell";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";

export default function NewDeployTargetPage() {
  const [form, setForm] = useState({
    name: "",
    host: "",
    sshPort: "22",
    sshUser: "root",
    authMode: "password" as "password" | "key",
    password: "",
    privateKey: "",
    composePath: "/opt/{name}/docker-compose.yml",
    notes: "",
  });
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const router = useRouter();

  function set<K extends keyof typeof form>(k: K, v: (typeof form)[K]) {
    setForm((p) => ({ ...p, [k]: v }));
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitting(true);
    setError(null);
    const body = {
      name: form.name,
      host: form.host,
      sshPort: parseInt(form.sshPort, 10) || 22,
      sshUser: form.sshUser,
      authMode: form.authMode,
      password: form.authMode === "password" ? form.password : undefined,
      privateKey: form.authMode === "key" ? form.privateKey : undefined,
      composePath: form.composePath,
      notes: form.notes || undefined,
    };
    const res = await fetch("/api/deploy-targets", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    if (res.ok) {
      router.push("/deploy-targets");
    } else {
      const err = await res.json().catch(() => ({}));
      setError(err.error ?? "lưu thất bại");
      setSubmitting(false);
    }
  }

  return (
    <Shell
      crumbs={[
        { label: "Tổng quan", href: "/" },
        { label: "Máy chủ deploy", href: "/deploy-targets" },
        { label: "Thêm mới" },
      ]}
    >
      <div className="mx-auto max-w-2xl">
        <Card>
          <CardHeader>
            <div className="flex items-center gap-3">
              <span className="flex h-9 w-9 items-center justify-center rounded-md bg-primary/15 text-primary">
                <Server className="h-4 w-4" />
              </span>
              <div>
                <CardTitle>Thêm máy chủ deploy</CardTitle>
                <CardDescription>
                  Nhập thông tin SSH và đường dẫn compose mẫu.
                </CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <form onSubmit={onSubmit} className="space-y-5">
              <div className="space-y-2">
                <Label htmlFor="name">Tên máy chủ</Label>
                <Input
                  id="name"
                  value={form.name}
                  onChange={(e) => set("name", e.target.value)}
                  placeholder="prod-lxc"
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="host">Host</Label>
                <Input
                  id="host"
                  value={form.host}
                  onChange={(e) => set("host", e.target.value)}
                  placeholder="192.168.40.20 hoặc tên miền"
                  className="font-mono"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-2">
                  <Label htmlFor="sshPort">Cổng SSH</Label>
                  <Input
                    id="sshPort"
                    type="number"
                    value={form.sshPort}
                    onChange={(e) => set("sshPort", e.target.value)}
                    className="font-mono"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="sshUser">Tài khoản SSH</Label>
                  <Input
                    id="sshUser"
                    value={form.sshUser}
                    onChange={(e) => set("sshUser", e.target.value)}
                    className="font-mono"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label>Cách xác thực</Label>
                <div className="grid grid-cols-2 gap-2">
                  <AuthOption
                    icon={<Lock className="h-4 w-4" />}
                    label="Mật khẩu"
                    active={form.authMode === "password"}
                    onClick={() => set("authMode", "password")}
                  />
                  <AuthOption
                    icon={<KeyRound className="h-4 w-4" />}
                    label="Khoá riêng"
                    active={form.authMode === "key"}
                    onClick={() => set("authMode", "key")}
                  />
                </div>
              </div>

              {form.authMode === "password" ? (
                <div className="space-y-2">
                  <Label htmlFor="password">Mật khẩu</Label>
                  <Input
                    id="password"
                    type="password"
                    value={form.password}
                    onChange={(e) => set("password", e.target.value)}
                    required
                  />
                </div>
              ) : (
                <div className="space-y-2">
                  <Label htmlFor="privateKey">Khoá riêng (PEM đầy đủ)</Label>
                  <textarea
                    id="privateKey"
                    value={form.privateKey}
                    onChange={(e) => set("privateKey", e.target.value)}
                    rows={6}
                    className="flex w-full rounded-md border border-input bg-surface px-3 py-2 text-sm font-mono transition-colors placeholder:text-muted-foreground/70 focus-visible:outline-none focus-visible:border-primary/60 focus-visible:ring-2 focus-visible:ring-ring/40"
                    placeholder="-----BEGIN OPENSSH PRIVATE KEY-----…"
                    required
                  />
                </div>
              )}

              <div className="space-y-2">
                <Label htmlFor="composePath">Đường dẫn compose</Label>
                <Input
                  id="composePath"
                  value={form.composePath}
                  onChange={(e) => set("composePath", e.target.value)}
                  className="font-mono"
                />
                <p className="text-xs text-muted-foreground">
                  <code className="text-mono text-foreground/80">{`{name}`}</code> sẽ được thay bằng tên dự án.
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="notes">Ghi chú (tuỳ chọn)</Label>
                <Input
                  id="notes"
                  value={form.notes}
                  onChange={(e) => set("notes", e.target.value)}
                />
              </div>

              {error && (
                <p className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
                  {error}
                </p>
              )}

              <div className="flex justify-end gap-2 border-t border-border/60 pt-4">
                <Button
                  type="button"
                  variant="ghost"
                  onClick={() => router.back()}
                  disabled={submitting}
                >
                  Huỷ
                </Button>
                <Button type="submit" disabled={submitting}>
                  {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
                  {submitting ? "Đang lưu…" : "Lưu máy chủ"}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </Shell>
  );
}

function AuthOption({
  icon,
  label,
  active,
  onClick,
}: {
  icon: React.ReactNode;
  label: string;
  active: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        "flex items-center gap-2 rounded-md border px-3 py-2.5 text-sm font-medium transition-colors",
        active
          ? "border-primary/50 bg-primary/10 text-primary"
          : "border-border bg-surface text-muted-foreground hover:border-border/80 hover:text-foreground",
      )}
    >
      {icon}
      {label}
    </button>
  );
}
