// @File: src/pages/admin/cms/cpanel/CmsCpanelHome.tsx
// @Desc: Admin dashboard for the WHM/cPanel Reseller Manager — KPI cards,
//        quick links to servers/packages/accounts, and a one-click probe
//        that surfaces the most recently tested WHM server health.
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { cpanelAdmin, type CpanelServer, type CpanelAccount } from "@/lib/cpanelApi";

export default function CmsCpanelHome() {
  const [servers, setServers] = useState<CpanelServer[]>([]);
  const [accounts, setAccounts] = useState<CpanelAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);
  const [testingId, setTestingId] = useState<number | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const [s, a] = await Promise.all([cpanelAdmin.listServers(), cpanelAdmin.listAccounts({})]);
        setServers(s);
        setAccounts(a);
      } catch (e) {
        setErr(e instanceof Error ? e.message : "Failed to load");
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const stats = useMemo(() => {
    const counts = { active: 0, suspended: 0, terminated: 0, pending: 0, failed: 0, total: accounts.length };
    for (const a of accounts) {
      counts[a.status as keyof typeof counts] = (counts[a.status as keyof typeof counts] || 0) + 1;
    }
    return counts;
  }, [accounts]);

  const probe = async (id: number) => {
    setTestingId(id);
    try {
      const res = await cpanelAdmin.testServer(id);
      const next = await cpanelAdmin.listServers();
      setServers(next);
      alert(res.ok ? `OK: ${res.message}` : `Failed: ${res.message}`);
    } catch (e) {
      alert(e instanceof Error ? e.message : "Probe failed");
    } finally {
      setTestingId(null);
    }
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">cPanel Reseller Manager</h1>
          <p className="text-sm text-muted-foreground">
            Provision, suspend and monitor cPanel hosting accounts across your WHM servers.
          </p>
        </div>
        <div className="flex gap-2">
          <Button asChild variant="outline"><Link to="/admin/cms/cpanel/servers">Servers</Link></Button>
          <Button asChild variant="outline"><Link to="/admin/cms/cpanel/packages">Packages</Link></Button>
          <Button asChild><Link to="/admin/cms/cpanel/accounts">Accounts</Link></Button>
        </div>
      </div>

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

      <div className="grid gap-4 md:grid-cols-5">
        {(["total", "active", "suspended", "pending", "failed"] as const).map((key) => (
          <Card key={key}>
            <CardHeader className="pb-2"><CardDescription className="capitalize">{key} accounts</CardDescription></CardHeader>
            <CardContent><div className="text-3xl font-bold">{stats[key] ?? 0}</div></CardContent>
          </Card>
        ))}
      </div>

      <Card>
        <CardHeader>
          <CardTitle>WHM Servers</CardTitle>
          <CardDescription>Connection health of every configured WHM endpoint.</CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-sm text-muted-foreground">Loading…</p>
          ) : servers.length === 0 ? (
            <p className="text-sm text-muted-foreground">
              No WHM servers yet. <Link className="underline" to="/admin/cms/cpanel/servers">Add one</Link> to start provisioning.
            </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>Hostname</th>
                    <th>Status</th>
                    <th>Last Test</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {servers.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>
                        <Badge variant={s.is_active ? "default" : "secondary"}>{s.is_active ? "active" : "disabled"}</Badge>{" "}
                        {s.last_test_status && (
                          <Badge 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">
                        <Button size="sm" variant="outline" disabled={testingId === s.id} onClick={() => probe(s.id)}>
                          {testingId === s.id ? "Testing…" : "Test"}
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader><CardTitle>Packages</CardTitle></CardHeader>
          <CardContent>
            <p className="text-sm text-muted-foreground mb-3">
              Create reseller plans and map them to WHM packages.
            </p>
            <Button asChild variant="outline" size="sm"><Link to="/admin/cms/cpanel/packages">Manage packages</Link></Button>
          </CardContent>
        </Card>
        <Card>
          <CardHeader><CardTitle>Accounts</CardTitle></CardHeader>
          <CardContent>
            <p className="text-sm text-muted-foreground mb-3">
              Suspend, unsuspend, change plan or terminate client accounts.
            </p>
            <Button asChild variant="outline" size="sm"><Link to="/admin/cms/cpanel/accounts">Open accounts</Link></Button>
          </CardContent>
        </Card>
        <Card>
          <CardHeader><CardTitle>Audit log</CardTitle></CardHeader>
          <CardContent>
            <p className="text-sm text-muted-foreground mb-3">
              Every provisioning and lifecycle event, with admin and target identities.
            </p>
            <Button asChild variant="outline" size="sm"><Link to="/admin/cms/cpanel/audit-log">View log</Link></Button>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}