// client/src/features/machines/AddMachineModal.tsx
import { useEffect, useState } from "react";
import type { AptProxyMode, MachineKind, OsFamily } from "@shared/types.js";
import type { DefaultAptProxy } from "../../lib/api.js";
import { api } from "../../lib/api.js";

interface Props { onClose: () => void; onCreated: () => void; }

const OS_OPTIONS: { value: OsFamily; label: string }[] = [
  { value: "debian", label: "Debian" },
  { value: "ubuntu", label: "Ubuntu" },
  { value: "proxmox", label: "Proxmox VE" },
  { value: "raspbian", label: "Raspberry Pi OS" },
  { value: "unknown", label: "Autre / auto" },
];
const KIND_OPTIONS: { value: MachineKind; label: string }[] = [
  { value: "vm", label: "VM" },
  { value: "physical", label: "Physique" },
  { value: "proxmox_host", label: "Hôte Proxmox" },
  { value: "lxc", label: "LXC / conteneur" },
  { value: "raspberry_pi", label: "Raspberry Pi" },
  { value: "workstation", label: "Workstation / GPU" },
  { value: "unknown", label: "Inconnu" },
];

export function AddMachineModal({ onClose, onCreated }: Props) {
  const [form, setForm] = useState({
    name: "", hostname: "", port: 22, username: "", password: "", sudoPassword: "",
    osFamily: "debian" as OsFamily, machineKind: "vm" as MachineKind,
  });
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [proxyDefault, setProxyDefault] = useState<DefaultAptProxy | null>(null);
  const [useProxy, setUseProxy] = useState(false);
  const set = (k: string, v: string | number) => setForm({ ...form, [k]: v });

  useEffect(() => {
    void (async () => {
      try {
        const s = await api.getSettings();
        if (s.defaultAptProxy.url) {
          setProxyDefault(s.defaultAptProxy);
          setUseProxy(true);
        }
      } catch {
        /* pas de défaut configuré */
      }
    })();
  }, []);

  async function submit() {
    setBusy(true); setError(null);
    try {
      const proxy = useProxy && proxyDefault?.url
        ? { aptProxyMode: proxyDefault.mode === "direct" ? "runtime" : proxyDefault.mode, aptProxyUrl: proxyDefault.url }
        : {};
      await api.createMachine({ ...form, port: Number(form.port), sudoPassword: form.sudoPassword || null, ...proxy });
      onCreated(); onClose();
    } catch (e) { setError((e as Error).message); } finally { setBusy(false); }
  }

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.5)", display: "grid", placeItems: "center" }}>
      <div className="glass-strong" style={{ padding: 20, borderRadius: 12, width: 380, display: "grid", gap: 10 }}>
        <div className="label">AJOUTER UNE MACHINE</div>
        {(["name", "hostname", "username"] as const).map((k) => (
          <input key={k} placeholder={k} value={form[k]} onChange={(e) => set(k, e.target.value)} />
        ))}
        <input placeholder="port" type="number" value={form.port} onChange={(e) => set("port", e.target.value)} />
        <label style={{ display: "grid", gap: 4 }}>
          <span className="label">OS</span>
          <select value={form.osFamily} onChange={(e) => setForm({ ...form, osFamily: e.target.value as OsFamily })}>
            {OS_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </label>
        <label style={{ display: "grid", gap: 4 }}>
          <span className="label">Type machine</span>
          <select value={form.machineKind} onChange={(e) => setForm({ ...form, machineKind: e.target.value as MachineKind })}>
            {KIND_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </label>
        <input placeholder="password" type="password" value={form.password} onChange={(e) => set("password", e.target.value)} />
        <input placeholder="sudo password (optionnel)" type="password" value={form.sudoPassword} onChange={(e) => set("sudoPassword", e.target.value)} />
        {proxyDefault?.url && (
          <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--ink-2)" }}>
            <input type="checkbox" checked={useProxy} onChange={(e) => setUseProxy(e.target.checked)} />
            <span>Proxy APT par défaut <span className="mono">{proxyDefault.url}</span></span>
          </label>
        )}
        <div style={{ fontSize: 11, color: "var(--ink-3)" }}>
          « Autre / auto » détecte l'OS via os-release. Détection complète (type, virt) ensuite via ⚙ Sonder.
        </div>
        {error && <div style={{ color: "var(--err)", fontSize: 12 }}>{error}</div>}
        <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
          <button onClick={onClose}>Annuler</button>
          <button className="interactive" disabled={busy} onClick={submit}>{busy ? "Test…" : "Ajouter"}</button>
        </div>
      </div>
    </div>
  );
}
