// @File: src/pages/admin/cms/cpanel/CmsCpanelAccounts.tsx
// @Desc: Admin account table with lifecycle actions, provisioning and SSO.
import { useEffect, useMemo, 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 { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
  Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import {
  cpanelAdmin,
  type CpanelAccount,
  type CpanelPackage,
  type CpanelServer,
} from "@/lib/cpanelApi";

const STATUS_COLORS: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
  active: "default",
  pending: "outline",
  suspended: "secondary",
  failed: "destructive",
  terminated: "destructive",
};

export default function CmsCpanelAccounts() {
  const [servers, setServers] = useState<CpanelServer[]>([]);
  const [packages, setPackages] = useState<CpanelPackage[]>([]);
  const [rows, setRows] = useState<CpanelAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);
  const [filterStatus, setFilterStatus] = useState<string>("all");
  const [filterServer, setFilterServer] = useState<string>("all");

  // create dialog
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({
    user_id: "",
    server_id: 0,
    package_id: 0,
    main_domain: "",
    contact_email: "",
    whmcs_service_id: "" as string | number,
    whmcs_client_id: "" as string | number,
  });

  const reload = async () => {
    setLoading(true);
    try {
      const [s, p, a] = await Promise.all([
        cpanelAdmin.listServers(),
        cpanelAdmin.listPackages(),
        cpanelAdmin.listAccounts({
          status: filterStatus !== "all" ? filterStatus : undefined,
          server_id: filterServer !== "all" ? Number(filterServer) : undefined,
        }),
      ]);
      setServers(s);
      setPackages(p);
      setRows(a);
      setErr(null);
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Failed to load");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void reload();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterStatus, filterServer]);

  const serverById = useMemo(() => new Map(servers.map((s) => [s.id, s])), [servers]);
  const pkgById = useMemo(() => new Map(packages.map((p) => [p.id, p])), [packages]);

  const openCreate = () => {
    setForm({
      user_id: "",
      server_id: servers[0]?.id ?? 0,
      package_id: packages[0]?.id ?? 0,
      main_domain: "",
      contact_email: "",
      whmcs_service_id: "",
      whmcs_client_id: "",
    });
    setOpen(true);
  };

  const submit = async () => {
    setSaving(true);
    try {
      const res = await cpanelAdmin.createAccount({
        user_id: form.user_id,
        server_id: Number(form.server_id),
        package_id: Number(form.package_id),
        main_domain: form.main_domain,
        contact_email: form.contact_email || undefined,
        whmcs_service_id: form.whmcs_service_id ? Number(form.whmcs_service_id) : undefined,
        whmcs_client_id: form.whmcs_client_id ? Number(form.whmcs_client_id) : undefined,
      });
      alert(res.ok ? res.message : "Provisioning failed");
      setOpen(false);
      await reload();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Provision failed");
    } finally {
      setSaving(false);
    }
  };

  const action = async (
    kind: "suspend" | "unsuspend" | "terminate" | "sso",
    id: number,
  ) => {
    try {
      if (kind === "suspend") {
        const reason = prompt("Suspension reason? (optional)") ?? undefined;
        await cpanelAdmin.suspend(id, reason || undefined);
      } else if (kind === "unsuspend") {
        await cpanelAdmin.unsuspend(id);
      } else if (kind === "terminate") {
        if (!confirm("Terminate this account? This is permanent.")) return;
        await cpanelAdmin.terminate(id);
      } else if (kind === "sso") {
        const res = await cpanelAdmin.adminSso(id);
        window.open(res.url, "_blank", "noopener,noreferrer");
        return;
      }
      await reload();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Action failed");
    }
  };

  const changePkg = async (a: CpanelAccount) => {
    const options = packages.filter((p) => p.server_id === a.server_id);
    if (options.length === 0) return alert("No other packages on this server.");
    const list = options.map((p, i) => `${i + 1}. ${p.display_name} (${p.whm_package_name})`).join("\n");
    const raw = prompt(`Choose new package:\n${list}\n\nEnter number:`);
    if (!raw) return;
    const idx = Number(raw) - 1;
    if (Number.isNaN(idx) || !options[idx]) return;
    try {
      await cpanelAdmin.changePackage(a.id, options[idx].id);
      await reload();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Failed");
    }
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h1 className="text-2xl font-bold">cPanel Accounts</h1>
        <div className="flex gap-2">
          <Select value={filterStatus} onValueChange={setFilterStatus}>
            <SelectTrigger className="w-40"><SelectValue placeholder="Status" /></SelectTrigger>
            <SelectContent>
              {["all", "active", "pending", "suspended", "terminated", "failed"].map((s) => (
                <SelectItem key={s} value={s}>{s}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={filterServer} onValueChange={setFilterServer}>
            <SelectTrigger className="w-48"><SelectValue placeholder="Server" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All servers</SelectItem>
              {servers.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
            </SelectContent>
          </Select>
          <Button onClick={openCreate}>+ Provision</Button>
        </div>
      </div>

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

      <Card>
        <CardHeader><CardTitle>Accounts</CardTitle></CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-sm text-muted-foreground">Loading…</p>
          ) : rows.length === 0 ? (
            <p className="text-sm text-muted-foreground">No accounts.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="text-left text-muted-foreground">
                  <tr>
                    <th className="py-2">User</th>
                    <th>Domain</th>
                    <th>cPanel user</th>
                    <th>Server</th>
                    <th>Package</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((a) => (
                    <tr key={a.id} className="border-t">
                      <td className="py-2 text-xs">{a.user_id}</td>
                      <td className="font-mono text-xs">{a.main_domain}</td>
                      <td className="font-mono text-xs">{a.cpanel_username}</td>
                      <td className="text-xs">{serverById.get(a.server_id)?.name ?? `#${a.server_id}`}</td>
                      <td className="text-xs">{a.package_id ? (pkgById.get(a.package_id)?.display_name ?? `#${a.package_id}`) : "—"}</td>
                      <td><Badge variant={STATUS_COLORS[a.status] || "outline"}>{a.status}</Badge></td>
                      <td className="text-xs text-muted-foreground">{new Date(a.created_at).toLocaleDateString()}</td>
                      <td className="text-right space-x-1">
                        <Button size="sm" variant="outline" onClick={() => action("sso", a.id)}>Login</Button>
                        <Button size="sm" variant="outline" onClick={() => changePkg(a)}>Plan</Button>
                        {a.status === "active" && (
                          <Button size="sm" variant="outline" onClick={() => action("suspend", a.id)}>Suspend</Button>
                        )}
                        {a.status === "suspended" && (
                          <Button size="sm" variant="outline" onClick={() => action("unsuspend", a.id)}>Unsuspend</Button>
                        )}
                        {a.status !== "terminated" && (
                          <Button size="sm" variant="destructive" onClick={() => action("terminate", a.id)}>Terminate</Button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-xl">
          <DialogHeader><DialogTitle>Provision cPanel account</DialogTitle></DialogHeader>
          <div className="grid gap-3 md:grid-cols-2">
            <div className="md:col-span-2">
              <Label>User ID (DoItEasy user)</Label>
              <Input value={form.user_id} onChange={(e) => setForm({ ...form, user_id: e.target.value })} />
            </div>
            <div>
              <Label>Server</Label>
              <Select
                value={String(form.server_id || "")}
                onValueChange={(v) => setForm({ ...form, server_id: Number(v) })}
              >
                <SelectTrigger><SelectValue placeholder="Server" /></SelectTrigger>
                <SelectContent>
                  {servers.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>Package</Label>
              <Select
                value={String(form.package_id || "")}
                onValueChange={(v) => setForm({ ...form, package_id: Number(v) })}
              >
                <SelectTrigger><SelectValue placeholder="Package" /></SelectTrigger>
                <SelectContent>
                  {packages
                    .filter((p) => !form.server_id || p.server_id === Number(form.server_id))
                    .map((p) => <SelectItem key={p.id} value={String(p.id)}>{p.display_name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="md:col-span-2">
              <Label>Main domain</Label>
              <Input
                placeholder="clientdomain.com"
                value={form.main_domain}
                onChange={(e) => setForm({ ...form, main_domain: e.target.value })}
              />
            </div>
            <div className="md:col-span-2">
              <Label>Contact email</Label>
              <Input
                value={form.contact_email}
                onChange={(e) => setForm({ ...form, contact_email: e.target.value })}
              />
            </div>
            <div>
              <Label>WHMCS service ID</Label>
              <Input
                value={form.whmcs_service_id as string}
                onChange={(e) => setForm({ ...form, whmcs_service_id: e.target.value })}
              />
            </div>
            <div>
              <Label>WHMCS client ID</Label>
              <Input
                value={form.whmcs_client_id as string}
                onChange={(e) => setForm({ ...form, whmcs_client_id: e.target.value })}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
            <Button
              onClick={submit}
              disabled={saving || !form.user_id || !form.main_domain || !form.server_id || !form.package_id}
            >
              {saving ? "Provisioning…" : "Provision"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}