// @File: src/pages/admin/cms/uptimerobot/CmsUptimeRobotSubscriptions.tsx
// @Desc: Admin view of all client subscriptions. Supports filter by
//        status/user, change package, suspend/resume/terminate, and an
//        inline drill-down to a subscription's monitors.
import { useCallback, useEffect, useState } from "react";
import {
  Users,
  Loader2,
  Pause,
  Play,
  XCircle,
  Plus,
  Eye,
  X,
  ShieldCheck,
  AlertTriangle,
} from "lucide-react";
import { toast } from "sonner";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, Select } from "../ui";
import {
  adminCreateSubscription,
  adminListPackages,
  adminListSubscriptionMonitors,
  adminListSubscriptions,
  adminResumeSubscription,
  adminSuspendSubscription,
  adminTerminateSubscription,
  adminUpdateSubscription,
  type UptimeMonitor,
  type UptimePackage,
  type UptimeSubscription,
} from "@/lib/uptimerobotApi";

function StatusBadge({ status }: { status: string }) {
  const s = status.toLowerCase();
  const tone =
    s === "active"
      ? "bg-emerald-50 text-emerald-700 border-emerald-200"
      : s === "suspended"
        ? "bg-amber-50 text-amber-700 border-amber-200"
        : "bg-slate-100 text-slate-600 border-slate-200";
  return (
    <span
      className={`px-2 py-0.5 rounded-full text-xs font-semibold border ${tone}`}
    >
      {status}
    </span>
  );
}

export default function CmsUptimeRobotSubscriptions() {
  const [subs, setSubs] = useState<UptimeSubscription[]>([]);
  const [packages, setPackages] = useState<UptimePackage[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState<string>("");
  const [userIdFilter, setUserIdFilter] = useState<string>("");
  const [creating, setCreating] = useState(false);
  const [busyId, setBusyId] = useState<number | null>(null);
  const [viewingMonitorsFor, setViewingMonitorsFor] =
    useState<UptimeSubscription | null>(null);
  const [monitors, setMonitors] = useState<UptimeMonitor[] | null>(null);

  const [showCreate, setShowCreate] = useState(false);
  const [newForm, setNewForm] = useState({
    user_id: "",
    user_email: "",
    package_id: 0,
    whmcs_service_id: "",
    whmcs_product_id: "",
    notes: "",
  });

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [s, p] = await Promise.all([
        adminListSubscriptions({
          status: statusFilter || undefined,
          user_id: userIdFilter || undefined,
        }),
        adminListPackages(),
      ]);
      setSubs(s);
      setPackages(p);
      if (!newForm.package_id && p.length > 0) {
        setNewForm((f) => ({ ...f, package_id: p[0].id }));
      }
    } catch (e) {
      toast.error(`Failed to load: ${e instanceof Error ? e.message : e}`);
    } finally {
      setLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [statusFilter, userIdFilter]);

  useEffect(() => {
    load();
  }, [load]);

  const changePackage = async (sub: UptimeSubscription, newPackageId: number) => {
    if (newPackageId === sub.package_id) return;
    setBusyId(sub.id);
    try {
      await adminUpdateSubscription(sub.id, { package_id: newPackageId });
      toast.success("Package updated.");
      await load();
    } catch (e) {
      toast.error(
        `Change package failed: ${e instanceof Error ? e.message : e}`,
      );
    } finally {
      setBusyId(null);
    }
  };

  const doAction = async (
    sub: UptimeSubscription,
    action: "suspend" | "resume" | "terminate",
  ) => {
    if (action === "terminate" && !confirm("Terminate this subscription?")) {
      return;
    }
    setBusyId(sub.id);
    try {
      if (action === "suspend") await adminSuspendSubscription(sub.id);
      if (action === "resume") await adminResumeSubscription(sub.id);
      if (action === "terminate") await adminTerminateSubscription(sub.id);
      toast.success(`${action}ed subscription.`);
      await load();
    } catch (e) {
      toast.error(`${action} failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setBusyId(null);
    }
  };

  const submitCreate = async () => {
    if (!newForm.user_id || !newForm.package_id) {
      toast.error("User id and package are required.");
      return;
    }
    setCreating(true);
    try {
      await adminCreateSubscription({
        user_id: newForm.user_id,
        user_email: newForm.user_email || undefined,
        package_id: newForm.package_id,
        whmcs_service_id: newForm.whmcs_service_id
          ? Number(newForm.whmcs_service_id)
          : undefined,
        whmcs_product_id: newForm.whmcs_product_id
          ? Number(newForm.whmcs_product_id)
          : undefined,
        notes: newForm.notes || undefined,
      });
      toast.success("Subscription created.");
      setShowCreate(false);
      setNewForm({
        user_id: "",
        user_email: "",
        package_id: packages[0]?.id ?? 0,
        whmcs_service_id: "",
        whmcs_product_id: "",
        notes: "",
      });
      await load();
    } catch (e) {
      toast.error(`Create failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setCreating(false);
    }
  };

  const openMonitors = async (sub: UptimeSubscription) => {
    setViewingMonitorsFor(sub);
    setMonitors(null);
    try {
      const rows = await adminListSubscriptionMonitors(sub.id);
      setMonitors(rows);
    } catch (e) {
      toast.error(`Load monitors failed: ${e instanceof Error ? e.message : e}`);
      setMonitors([]);
    }
  };

  return (
    <CmsLayout>
      <PageHeader
        title="Client Subscriptions"
        description="Assign packages to clients, change plans, and manage the active/suspended/terminated lifecycle."
        icon={<Users className="w-6 h-6" />}
      />

      <SectionCard
        title="All subscriptions"
        description={`${subs.length} subscription(s) loaded.`}
        actions={
          <button
            onClick={() => setShowCreate(true)}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#095a32] transition"
          >
            <Plus className="w-4 h-4" /> Assign package
          </button>
        }
      >
        <div className="flex flex-wrap items-end gap-3 pb-4 border-b border-slate-100">
          <div className="min-w-[180px]">
            <Field label="Status filter">
              <Select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
              >
                <option value="">All</option>
                <option value="active">Active</option>
                <option value="suspended">Suspended</option>
                <option value="terminated">Terminated</option>
              </Select>
            </Field>
          </div>
          <div className="min-w-[220px]">
            <Field label="User id contains">
              <TextInput
                value={userIdFilter}
                onChange={(e) => setUserIdFilter(e.target.value)}
                placeholder="uuid fragment"
              />
            </Field>
          </div>
          <button
            onClick={load}
            className="px-4 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold"
          >
            Apply
          </button>
        </div>

        {loading ? (
          <div className="flex items-center gap-2 text-slate-500 text-sm pt-4">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading…
          </div>
        ) : subs.length === 0 ? (
          <div className="text-sm text-slate-500 pt-4">No subscriptions found.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-xs uppercase text-slate-500 border-b border-slate-200">
                  <th className="py-2 pr-4">User</th>
                  <th className="py-2 pr-4">Package</th>
                  <th className="py-2 pr-4">Usage</th>
                  {/* WHMCS column hidden — self-service signup is used instead. */}
                  <th className="py-2 pr-4">Status</th>
                  <th className="py-2" />
                </tr>
              </thead>
              <tbody>
                {subs.map((s) => {
                  const busy = busyId === s.id;
                  return (
                    <tr key={s.id} className="border-b border-slate-100 align-top">
                      <td className="py-2 pr-4">
                        <div className="font-semibold text-slate-900">
                          {s.user_email ?? "—"}
                        </div>
                        <div className="text-[11px] text-slate-500 break-all">
                          {s.user_id}
                        </div>
                      </td>
                      <td className="py-2 pr-4">
                        <Select
                          value={s.package_id}
                          disabled={busy || s.status === "terminated"}
                          onChange={(e) =>
                            changePackage(s, Number(e.target.value))
                          }
                        >
                          {packages.map((p) => (
                            <option key={p.id} value={p.id}>
                              {p.name}
                            </option>
                          ))}
                        </Select>
                      </td>
                      <td className="py-2 pr-4 text-xs text-slate-600">
                        <div>Monitors: {s.monitors_used}</div>
                        <div>Contacts: {s.alert_contacts_used}</div>
                        <div>Pages: {s.status_pages_used}</div>
                      </td>
                      {/* WHMCS column hidden — self-service signup is used instead. */}
                      <td className="py-2 pr-4">
                        <StatusBadge status={s.status} />
                      </td>
                      <td className="py-2 text-right whitespace-nowrap space-x-1">
                        <button
                          onClick={() => openMonitors(s)}
                          className="px-2.5 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold inline-flex items-center gap-1"
                        >
                          <Eye className="w-3 h-3" /> Monitors
                        </button>
                        {s.status === "active" && (
                          <button
                            onClick={() => doAction(s, "suspend")}
                            disabled={busy}
                            className="px-2.5 py-1.5 rounded-lg bg-amber-50 hover:bg-amber-100 text-amber-700 text-xs font-semibold inline-flex items-center gap-1 disabled:opacity-60"
                          >
                            <Pause className="w-3 h-3" /> Suspend
                          </button>
                        )}
                        {s.status === "suspended" && (
                          <button
                            onClick={() => doAction(s, "resume")}
                            disabled={busy}
                            className="px-2.5 py-1.5 rounded-lg bg-emerald-50 hover:bg-emerald-100 text-emerald-700 text-xs font-semibold inline-flex items-center gap-1 disabled:opacity-60"
                          >
                            <Play className="w-3 h-3" /> Resume
                          </button>
                        )}
                        {s.status !== "terminated" && (
                          <button
                            onClick={() => doAction(s, "terminate")}
                            disabled={busy}
                            className="px-2.5 py-1.5 rounded-lg bg-red-50 hover:bg-red-100 text-red-700 text-xs font-semibold inline-flex items-center gap-1 disabled:opacity-60"
                          >
                            <XCircle className="w-3 h-3" /> Terminate
                          </button>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>

      {showCreate && (
        <div className="fixed inset-0 bg-slate-900/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-lg w-full">
            <div className="flex items-center justify-between p-5 border-b border-slate-200">
              <h3 className="text-lg font-bold text-slate-900">Assign package</h3>
              <button
                onClick={() => setShowCreate(false)}
                className="p-2 rounded-lg hover:bg-slate-100"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-5 space-y-4">
              <Field label="DoItEasy user id (UUID)" required>
                <TextInput
                  value={newForm.user_id}
                  onChange={(e) =>
                    setNewForm({ ...newForm, user_id: e.target.value })
                  }
                />
              </Field>
              <Field label="User email (optional, for audit log)">
                <TextInput
                  value={newForm.user_email}
                  onChange={(e) =>
                    setNewForm({ ...newForm, user_email: e.target.value })
                  }
                />
              </Field>
              <Field label="Package" required>
                <Select
                  value={newForm.package_id}
                  onChange={(e) =>
                    setNewForm({
                      ...newForm,
                      package_id: Number(e.target.value),
                    })
                  }
                >
                  {packages.map((p) => (
                    <option key={p.id} value={p.id}>
                      {p.name}
                    </option>
                  ))}
                </Select>
              </Field>
              {/* WHMCS fields are intentionally hidden — this deployment uses
                  Atoms self-service signup, not WHMCS billing. The backend still
                  accepts these optional fields for legacy records, but we don't
                  expose them in the UI. */}
              <Field label="Notes">
                <TextInput
                  value={newForm.notes}
                  onChange={(e) =>
                    setNewForm({ ...newForm, notes: e.target.value })
                  }
                />
              </Field>
              <div className="flex justify-end gap-2">
                <button
                  onClick={() => setShowCreate(false)}
                  className="px-4 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold"
                >
                  Cancel
                </button>
                <button
                  onClick={submitCreate}
                  disabled={creating}
                  className="px-4 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#095a32] inline-flex items-center gap-2 disabled:opacity-60"
                >
                  {creating ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <ShieldCheck className="w-4 h-4" />
                  )}
                  Create
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {viewingMonitorsFor && (
        <div className="fixed inset-0 bg-slate-900/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-5 border-b border-slate-200 sticky top-0 bg-white">
              <div>
                <h3 className="text-lg font-bold text-slate-900">
                  Monitors for {viewingMonitorsFor.user_email ?? "user"}
                </h3>
                <p className="text-xs text-slate-500">
                  Subscription #{viewingMonitorsFor.id}
                </p>
              </div>
              <button
                onClick={() => {
                  setViewingMonitorsFor(null);
                  setMonitors(null);
                }}
                className="p-2 rounded-lg hover:bg-slate-100"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-5">
              {monitors === null ? (
                <div className="flex items-center gap-2 text-slate-500 text-sm">
                  <Loader2 className="w-4 h-4 animate-spin" /> Loading…
                </div>
              ) : monitors.length === 0 ? (
                <div className="flex items-start gap-3 p-4 rounded-xl border border-slate-200 bg-slate-50 text-slate-600 text-sm">
                  <AlertTriangle className="w-5 h-5 shrink-0 mt-0.5" />
                  No monitors under this subscription yet.
                </div>
              ) : (
                <table className="w-full text-sm">
                  <thead>
                    <tr className="text-left text-xs uppercase text-slate-500 border-b border-slate-200">
                      <th className="py-2 pr-4">Name</th>
                      <th className="py-2 pr-4">Type</th>
                      <th className="py-2 pr-4">Target</th>
                      <th className="py-2 pr-4">Status</th>
                      <th className="py-2 pr-4">Uptime 30d</th>
                    </tr>
                  </thead>
                  <tbody>
                    {monitors.map((m) => (
                      <tr key={m.id} className="border-b border-slate-100">
                        <td className="py-2 pr-4 font-semibold text-slate-900">
                          {m.friendly_name}
                        </td>
                        <td className="py-2 pr-4">{m.monitor_type}</td>
                        <td className="py-2 pr-4 break-all text-slate-600">
                          {m.url ?? "—"}
                        </td>
                        <td className="py-2 pr-4">{m.status}</td>
                        <td className="py-2 pr-4">
                          {m.uptime_ratio_30d ?? "—"}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        </div>
      )}
    </CmsLayout>
  );
}