// @File: src/pages/admin/cms/cpanel/CmsCpanelServers.tsx
// @Desc: Admin CRUD + health probe UI for WHM server endpoints.
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { cpanelAdmin, type CpanelServer, type CpanelServerCreate } from "@/lib/cpanelApi";

const EMPTY: CpanelServerCreate = {
  name: "",
  hostname: "",
  port: 2087,
  username: "root",
  api_token: "",
  verify_tls: true,
  is_active: true,
  notes: "",
};

export default function CmsCpanelServers() {
  const [rows, setRows] = useState<CpanelServer[]>([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<CpanelServer | null>(null);
  const [form, setForm] = useState<CpanelServerCreate>(EMPTY);
  const [saving, setSaving] = useState(false);

  const reload = async () => {
    setLoading(true);
    try {
      setRows(await cpanelAdmin.listServers());
      setErr(null);
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Failed to load");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void reload();
  }, []);

  const openCreate = () => {
    setEditing(null);
    setForm(EMPTY);
    setOpen(true);
  };
  const openEdit = (s: CpanelServer) => {
    setEditing(s);
    setForm({
      name: s.name,
      hostname: s.hostname,
      port: s.port,
      username: s.username,
      api_token: "",
      verify_tls: s.verify_tls,
      is_active: s.is_active,
      notes: s.notes ?? "",
    });
    setOpen(true);
  };

  const submit = async () => {
    setSaving(true);
    setErr(null);
    try {
      if (editing) {
        const payload: Partial<CpanelServerCreate> = { ...form };
        if (!payload.api_token) delete payload.api_token;
        await cpanelAdmin.updateServer(editing.id, payload);
      } else {
        await cpanelAdmin.createServer(form);
      }
      setOpen(false);
      await reload();
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Save failed");
    } finally {
      setSaving(false);
    }
  };

  const remove = async (s: CpanelServer) => {
    if (!confirm(`Delete WHM server '${s.name}'?`)) return;
    try {
      await cpanelAdmin.deleteServer(s.id);
      await reload();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Delete failed");
    }
  };

  const test = async (s: CpanelServer) => {
    try {
      const res = await cpanelAdmin.testServer(s.id);
      alert(res.ok ? `OK: ${res.message}${res.whm_version ? ` (${res.whm_version})` : ""}` : `Failed: ${res.message}`);
      await reload();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Probe failed");
    }
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">WHM Servers</h1>
        <Button onClick={openCreate}>+ Add server</Button>
      </div>

      {err && <Alert variant="destructive"><AlertDescription>{err}</AlertDescription></Alert>}

      <Card>
        <CardHeader><CardTitle>Configured endpoints</CardTitle></CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-sm text-muted-foreground">Loading…</p>
          ) : rows.length === 0 ? (
            <p className="text-sm text-muted-foreground">No servers yet.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="text-left text-muted-foreground">
                  <tr>
                    <th className="py-2">Name</th>
                    <th>Host</th>
                    <th>User</th>
                    <th>TLS</th>
                    <th>Status</th>
                    <th>Last Test</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((s) => (
                    <tr key={s.id} className="border-t">
                      <td className="py-2 font-medium">{s.name}</td>
                      <td className="font-mono text-xs">{s.hostname}:{s.port}</td>
                      <td>{s.username}</td>
                      <td>{s.verify_tls ? "verify" : "skip"}</td>
                      <td>
                        <Badge variant={s.is_active ? "default" : "secondary"}>{s.is_active ? "active" : "disabled"}</Badge>
                        {s.last_test_status && (
                          <Badge
                            className="ml-2"
                            variant={s.last_test_status === "ok" ? "default" : "destructive"}
                          >
                            {s.last_test_status}
                          </Badge>
                        )}
                      </td>
                      <td className="text-xs text-muted-foreground">
                        {s.last_tested_at ? new Date(s.last_tested_at).toLocaleString() : "never"}
                      </td>
                      <td className="text-right space-x-1">
                        <Button size="sm" variant="outline" onClick={() => test(s)}>Test</Button>
                        <Button size="sm" variant="outline" onClick={() => openEdit(s)}>Edit</Button>
                        <Button size="sm" variant="destructive" onClick={() => remove(s)}>Delete</Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editing ? "Edit WHM server" : "Add WHM server"}</DialogTitle>
            <DialogDescription>
              Store credentials for a WHM endpoint. Tokens are encrypted at rest.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 md:grid-cols-2">
            <div className="md:col-span-2">
              <Label>Name</Label>
              <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
            </div>
            <div className="md:col-span-2">
              <Label>Hostname</Label>
              <Input
                placeholder="whm.example.com"
                value={form.hostname}
                onChange={(e) => setForm({ ...form, hostname: e.target.value })}
              />
            </div>
            <div>
              <Label>Port</Label>
              <Input
                type="number"
                value={form.port}
                onChange={(e) => setForm({ ...form, port: Number(e.target.value) || 2087 })}
              />
            </div>
            <div>
              <Label>Username</Label>
              <Input value={form.username} onChange={(e) => setForm({ ...form, username: e.target.value })} />
            </div>
            <div className="md:col-span-2">
              <Label>API token {editing && <span className="text-xs text-muted-foreground">(leave blank to keep)</span>}</Label>
              <Input
                type="password"
                value={form.api_token}
                onChange={(e) => setForm({ ...form, api_token: e.target.value })}
              />
            </div>
            <div className="flex items-center gap-2">
              <Switch
                checked={form.verify_tls}
                onCheckedChange={(v) => setForm({ ...form, verify_tls: Boolean(v) })}
              />
              <Label>Verify TLS</Label>
            </div>
            <div className="flex items-center gap-2">
              <Switch
                checked={form.is_active}
                onCheckedChange={(v) => setForm({ ...form, is_active: Boolean(v) })}
              />
              <Label>Active</Label>
            </div>
            <div className="md:col-span-2">
              <Label>Notes</Label>
              <Textarea
                rows={2}
                value={form.notes ?? ""}
                onChange={(e) => setForm({ ...form, notes: e.target.value })}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
            <Button onClick={submit} disabled={saving || !form.name || !form.hostname}>
              {saving ? "Saving…" : "Save"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}