"use client";
import * as React from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Server, ChevronDown, Check } from "lucide-react";
import { cn } from "@/lib/utils";

interface Target {
  id: string;
  name: string;
  host: string;
}

export function TargetSelector({
  projectId,
  currentTargetId,
  targets,
}: {
  projectId: string;
  currentTargetId: string | null;
  targets: Target[];
}) {
  const router = useRouter();
  const [open, setOpen] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const ref = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, [open]);

  const current = targets.find((t) => t.id === currentTargetId);

  const onSelect = async (id: string) => {
    setSaving(true);
    setOpen(false);
    await fetch(`/api/projects/${projectId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ deployTargetId: id }),
    });
    setSaving(false);
    router.refresh();
  };

  if (targets.length === 0) {
    return (
      <div className="rounded-md border border-border bg-surface/40 p-3 text-xs">
        <p className="text-muted-foreground">Chưa có máy chủ deploy nào.</p>
        <Link
          href="/deploy-targets/new"
          className="mt-1 inline-block font-medium text-primary hover:underline"
        >
          Thêm máy chủ →
        </Link>
      </div>
    );
  }

  return (
    <div className="space-y-1.5">
      <label className="text-2xs font-medium uppercase tracking-wider text-muted-foreground">
        Máy chủ deploy
      </label>
      <div ref={ref} className="relative">
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          disabled={saving}
          className={cn(
            "flex w-full items-center gap-2 rounded-md border border-input bg-surface px-3 py-2 text-sm text-foreground/90 transition-colors hover:border-border/80",
            "disabled:opacity-60 disabled:cursor-not-allowed",
            open && "border-primary/40",
          )}
        >
          <Server className="h-4 w-4 shrink-0 text-muted-foreground" />
          <span className="min-w-0 flex-1 truncate text-left">
            {current ? (
              <>
                <span className="font-medium">{current.name}</span>
                <span className="ml-2 text-mono text-xs text-muted-foreground">
                  {current.host}
                </span>
              </>
            ) : (
              <span className="text-muted-foreground">Chọn máy chủ…</span>
            )}
          </span>
          <ChevronDown
            className={cn(
              "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",
              open && "rotate-180",
            )}
          />
        </button>
        {open && (
          <ul className="absolute z-10 mt-1 max-h-64 w-full overflow-auto rounded-md border border-border bg-surface-elevated shadow-lg animate-fade-in">
            {targets.map((t) => {
              const active = t.id === currentTargetId;
              return (
                <li key={t.id}>
                  <button
                    type="button"
                    onClick={() => onSelect(t.id)}
                    className={cn(
                      "flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition-colors hover:bg-accent",
                      active && "bg-accent/40",
                    )}
                  >
                    <span className="min-w-0 flex-1">
                      <span className="block truncate font-medium text-foreground">
                        {t.name}
                      </span>
                      <span className="block truncate text-mono text-2xs text-muted-foreground">
                        {t.host}
                      </span>
                    </span>
                    {active && <Check className="h-3.5 w-3.5 shrink-0 text-primary" />}
                  </button>
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </div>
  );
}
