// @File: src/pages/admin/cms/cpanel/CmsCpanelPackages.tsx
// @Desc: Admin CRUD for cPanel reseller packages + "Sync from WHM" helper.
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 { 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 {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
  Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import {
  cpanelAdmin, type CpanelPackage, type CpanelPackageCreate, type CpanelServer,
} from "@/lib/cpanelApi";

function emptyForm(serverId: number | null): CpanelPackageCreate {
  return {
    server_id: serverId ?? 0,
    display_name: "",
    slug: "",
    description: "",
    monthly_price: "0.00",
    currency: "USD",
    whmcs_product_id: null,
    whm_package_name: "",
    disk_quota_mb: null,
    bandwidth_mb: null,
    max_email_accounts: null,
    max_ftp_accounts: null,
    max_databases: null,
    max_subdomains: null,
    max_addon_domains: null,
    max_parked_domains: null,
    has_ssl: true,
    has_backup: true,
    has_ssh: false,
    has_wordpress_tools: true,
    has_cloudlinux: false,
    cpu_limit_percent: null,
    memory_limit_mb: null,
    io_limit_kbps: null,
    iops_limit: null,
    ep_limit: null,
    nproc_limit: null,
    is_active: true,
    sort_order: 0,
  };
}

export default function CmsCpanelPackages() {
  const [servers, setServers] = useState<CpanelServer[]>([]);
  const [rows, setRows] = useState<CpanelPackage[]>([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);
  const [serverFilter, setServerFilter] = useState<string>("all");

  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<CpanelPackage | null>(null);
  const [form, setForm] = useState<CpanelPackageCreate>(emptyForm(null));
  const [saving, setSaving] = useState(false);
  const [syncing, setSyncing] = useState(false);

  const reload = async () => {
    setLoading(true);
    try {
      const [s, p] = await Promise.all([
        cpanelAdmin.listServers(),
        cpanelAdmin.listPackages(serverFilter !== "all" ? Number(serverFilter) : undefined),
      ]);
      setServers(s);
      setRows(p);
      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
  }, [serverFilter]);

  const serverById = useMemo(() => {
    const m = new Map<number, CpanelServer>();
    for (const s of servers) m.set(s.id, s);
    return m;
  }, [servers]);

  const openCreate = () => {
    if (servers.length === 0) {
      alert("Add a WHM server first.");
      return;
    }
    setEditing(null);
    setForm(emptyForm(servers[0].id));
    setOpen(true);
  };

  const openEdit = (p: CpanelPackage) => {
    setEditing(p);
    const { id: _id, created_at: _c, updated_at: _u, ...rest } = p;
    void _id; void _c; void _u;
    setForm({ ...rest });
    setOpen(true);
  };

  const submit = async () => {
    setSaving(true);
    setErr(null);
    try {
      const slug = form.slug || form.display_name.toLowerCase().replace(/[^a-z0-9-]+/g, "-").slice(0, 140);
      const payload = { ...form, slug };
      if (editing) {
        await cpanelAdmin.updatePackage(editing.id, payload);
      } else {
        await cpanelAdmin.createPackage(payload);
      }
      setOpen(false);
      await reload();
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Save failed");
    } finally {
      setSaving(false);
    }
  };

  const remove = async (p: CpanelPackage) => {
    if (!confirm(`Delete package '${p.display_name}'?`)) return;
    try {
      await cpanelAdmin.deletePackage(p.id);
      await reload();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Delete failed");
    }
  };

  const syncFromWhm = async () => {
    const serverId = serverFilter !== "all" ? Number(serverFilter) : servers[0]?.id;
    if (!serverId) return alert("Select a server first.");
    setSyncing(true);
    try {
      const res = await cpanelAdmin.syncPackagesFromWhm(serverId);
      alert(res.ok ? `Imported ${res.imported}, updated ${res.updated}` : res.message || "Sync failed");
      await reload();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Sync failed");
    } finally {
      setSyncing(false);
    }
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex flex-wrap items-center gap-3 justify-between">
        <h1 className="text-2xl font-bold">cPanel Packages</h1>
        <div className="flex gap-2 items-center">
          <Select value={serverFilter} onValueChange={setServerFilter}>
            <SelectTrigger className="w-56"><SelectValue placeholder="Filter by 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 variant="outline" disabled={syncing || servers.length === 0} onClick={syncFromWhm}>
            {syncing ? "Syncing…" : "Sync from WHM"}
          </Button>
          <Button onClick={openCreate}>+ Add package</Button>
        </div>
      </div>

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

      <Card>
        <CardHeader><CardTitle>Reseller plans</CardTitle></CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-sm text-muted-foreground">Loading…</p>
          ) : rows.length === 0 ? (
            <p className="text-sm text-muted-foreground">No packages defined.</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>Server</th>
                    <th>WHM pkg</th>
                    <th>Price</th>
                    <th>Disk</th>
                    <th>BW</th>
                    <th>Features</th>
                    <th>Active</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((p) => (
                    <tr key={p.id} className="border-t">
                      <td className="py-2 font-medium">{p.display_name}</td>
                      <td>{serverById.get(p.server_id)?.name ?? `#${p.server_id}`}</td>
                      <td className="font-mono text-xs">{p.whm_package_name}</td>
                      <td>{p.currency} {p.monthly_price}</td>
                      <td>{p.disk_quota_mb ? `${p.disk_quota_mb} MB` : "—"}</td>
                      <td>{p.bandwidth_mb ? `${p.bandwidth_mb} MB` : "—"}</td>
                      <td className="space-x-1">
                        {p.has_ssl && <Badge variant="outline">SSL</Badge>}
                        {p.has_backup && <Badge variant="outline">Backup</Badge>}
                        {p.has_ssh && <Badge variant="outline">SSH</Badge>}
                        {p.has_wordpress_tools && <Badge variant="outline">WP</Badge>}
                        {p.has_cloudlinux && <Badge variant="outline">CL</Badge>}
                      </td>
                      <td>{p.is_active ? "Yes" : "No"}</td>
                      <td className="text-right space-x-1">
                        <Button size="sm" variant="outline" onClick={() => openEdit(p)}>Edit</Button>
                        <Button size="sm" variant="destructive" onClick={() => remove(p)}>Delete</Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader><DialogTitle>{editing ? "Edit package" : "New package"}</DialogTitle></DialogHeader>
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <Label>Server</Label>
              <Select
                value={String(form.server_id || "")}
                onValueChange={(v) => setForm({ ...form, server_id: Number(v) })}
              >
                <SelectTrigger><SelectValue placeholder="Select server" /></SelectTrigger>
                <SelectContent>
                  {servers.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>WHM package name</Label>
              <Input
                placeholder="reseller_default_basic"
                value={form.whm_package_name}
                onChange={(e) => setForm({ ...form, whm_package_name: e.target.value })}
              />
            </div>
            <div>
              <Label>Display name</Label>
              <Input value={form.display_name} onChange={(e) => setForm({ ...form, display_name: e.target.value })} />
            </div>
            <div>
              <Label>Slug</Label>
              <Input
                placeholder="auto"
                value={form.slug}
                onChange={(e) => setForm({ ...form, slug: e.target.value })}
              />
            </div>
            <div>
              <Label>Monthly price</Label>
              <Input
                value={form.monthly_price}
                onChange={(e) => setForm({ ...form, monthly_price: e.target.value })}
              />
            </div>
            <div>
              <Label>Currency</Label>
              <Input value={form.currency} onChange={(e) => setForm({ ...form, currency: e.target.value.toUpperCase() })} />
            </div>
            <div>
              <Label>WHMCS product ID</Label>
              <Input
                type="number"
                value={form.whmcs_product_id ?? ""}
                onChange={(e) => setForm({ ...form, whmcs_product_id: e.target.value ? Number(e.target.value) : null })}
              />
            </div>
            <div>
              <Label>Sort order</Label>
              <Input
                type="number"
                value={form.sort_order}
                onChange={(e) => setForm({ ...form, sort_order: Number(e.target.value) || 0 })}
              />
            </div>
            <div>
              <Label>Disk quota (MB)</Label>
              <Input
                type="number"
                value={form.disk_quota_mb ?? ""}
                onChange={(e) => setForm({ ...form, disk_quota_mb: e.target.value ? Number(e.target.value) : null })}
              />
            </div>
            <div>
              <Label>Bandwidth (MB)</Label>
              <Input
                type="number"
                value={form.bandwidth_mb ?? ""}
                onChange={(e) => setForm({ ...form, bandwidth_mb: e.target.value ? Number(e.target.value) : null })}
              />
            </div>
            <div className="md:col-span-2">
              <Label>Description</Label>
              <Textarea
                rows={2}
                value={form.description ?? ""}
                onChange={(e) => setForm({ ...form, description: e.target.value })}
              />
            </div>
            <div className="md:col-span-2 grid grid-cols-2 md:grid-cols-3 gap-3">
              {[
                ["has_ssl", "SSL"],
                ["has_backup", "Backup"],
                ["has_ssh", "SSH"],
                ["has_wordpress_tools", "WordPress tools"],
                ["has_cloudlinux", "CloudLinux"],
                ["is_active", "Active"],
              ].map(([key, label]) => (
                <div key={key} className="flex items-center gap-2">
                  <Switch
                    checked={(form as unknown as Record<string, boolean>)[key]}
                    onCheckedChange={(v) => setForm({ ...form, [key]: Boolean(v) } as CpanelPackageCreate)}
                  />
                  <Label>{label}</Label>
                </div>
              ))}
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
            <Button
              onClick={submit}
              disabled={saving || !form.display_name || !form.whm_package_name || !form.server_id}
            >
              {saving ? "Saving…" : "Save"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}