// @File: src/pages/admin/cms/bizmail/CmsBizmailSubscriptions.tsx
// @Desc: Admin view of every Bizmail360 client subscription with lifecycle
//        actions (activate / suspend / resume / cancel).
import { useEffect, useMemo, useState } from "react";
import { Users, Loader2, AlertTriangle, Play, Pause, RefreshCw, Ban } from "lucide-react";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Badge, Select } from "../ui";
import {
  adminListSubscriptions,
  adminSubscriptionAction,
  type BizmailSubscription,
} from "@/lib/bizmailApi";
import { toast } from "sonner";

const STATUS_FILTERS: Array<{ value: string; label: string }> = [
  { value: "", label: "All statuses" },
  { value: "pending", label: "Pending" },
  { value: "active", label: "Active" },
  { value: "suspended", label: "Suspended" },
  { value: "cancelled", label: "Cancelled" },
];

function statusTone(status: string): "green" | "yellow" | "red" | "slate" {
  switch (status) {
    case "active":
      return "green";
    case "pending":
      return "yellow";
    case "suspended":
      return "red";
    case "cancelled":
      return "slate";
    default:
      return "slate";
  }
}

export default function CmsBizmailSubscriptions() {
  const [rows, setRows] = useState<BizmailSubscription[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState("");
  const [busy, setBusy] = useState<Record<number, string | null>>({});

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const list = await adminListSubscriptions(statusFilter || undefined);
      setRows(list);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load subscriptions");
    } finally {
      setLoading(false);
    }
  };

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

  const runAction = async (
    id: number,
    action: "activate" | "suspend" | "resume" | "cancel"
  ) => {
    setBusy((s) => ({ ...s, [id]: action }));
    try {
      const res = await adminSubscriptionAction(id, action);
      setRows((prev) => prev.map((r) => (r.id === id ? res.subscription : r)));
      toast.success(res.message);
    } catch (e) {
      toast.error(e instanceof Error ? e.message : `${action} failed`);
    } finally {
      setBusy((s) => ({ ...s, [id]: null }));
    }
  };

  const summary = useMemo(() => {
    const count = (s: string) => rows.filter((r) => r.status === s).length;
    return {
      total: rows.length,
      active: count("active"),
      pending: count("pending"),
      suspended: count("suspended"),
    };
  }, [rows]);

  return (
    <CmsLayout>
      <PageHeader
        icon={<Users className="w-6 h-6" />}
        title="Bizmail360 Subscriptions"
        description="Every client mail subscription, with full lifecycle control."
      />

      <div className="grid md:grid-cols-4 gap-4 mb-6">
        {[
          { label: "Total", value: summary.total, tone: "bg-slate-100 text-slate-700" },
          { label: "Active", value: summary.active, tone: "bg-emerald-50 text-emerald-700" },
          { label: "Pending", value: summary.pending, tone: "bg-amber-50 text-amber-700" },
          { label: "Suspended", value: summary.suspended, tone: "bg-rose-50 text-rose-700" },
        ].map((k) => (
          <div
            key={k.label}
            className={`rounded-2xl p-4 border border-slate-200 bg-white shadow-sm`}
          >
            <div className="text-xs text-slate-500 uppercase tracking-wider">{k.label}</div>
            <div className={`mt-1 inline-flex px-2.5 py-0.5 rounded-md text-2xl font-extrabold ${k.tone}`}>
              {k.value}
            </div>
          </div>
        ))}
      </div>

      <SectionCard
        title="Subscriptions"
        description="Filter by status and take action on any subscription."
        actions={
          <Select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="!w-48"
          >
            {STATUS_FILTERS.map((f) => (
              <option key={f.value} value={f.value}>
                {f.label}
              </option>
            ))}
          </Select>
        }
      >
        {error && (
          <div className="flex items-start gap-2 rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">
            <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
            <span>{error}</span>
          </div>
        )}
        {loading ? (
          <div className="flex items-center gap-2 text-slate-500 text-sm">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading subscriptions…
          </div>
        ) : rows.length === 0 ? (
          <div className="text-sm text-slate-500">No subscriptions match this filter.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-xs text-slate-500 uppercase tracking-wider border-b border-slate-200">
                  <th className="py-2 pr-3">Client</th>
                  <th className="py-2 pr-3">Domain</th>
                  <th className="py-2 pr-3">Plan</th>
                  <th className="py-2 pr-3">Cycle</th>
                  <th className="py-2 pr-3">Status</th>
                  <th className="py-2 pr-3">Mailboxes</th>
                  <th className="py-2 pr-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((r) => {
                  const working = busy[r.id];
                  return (
                    <tr key={r.id} className="border-b border-slate-100 last:border-0">
                      <td className="py-3 pr-3 align-top">
                        <div className="font-semibold text-slate-800">
                          {r.user_email || r.user_id}
                        </div>
                        <div className="text-xs text-slate-400">#{r.id}</div>
                      </td>
                      <td className="py-3 pr-3 align-top font-mono text-slate-700">
                        {r.domain_name}
                      </td>
                      <td className="py-3 pr-3 align-top">
                        {r.plan?.name ?? `Plan #${r.plan_id}`}
                      </td>
                      <td className="py-3 pr-3 align-top capitalize">{r.billing_cycle}</td>
                      <td className="py-3 pr-3 align-top">
                        <Badge tone={statusTone(r.status)}>{r.status}</Badge>
                      </td>
                      <td className="py-3 pr-3 align-top">
                        {r.mailboxes_used} / {r.mailbox_quota ?? r.plan?.mailbox_quota ?? "?"}
                      </td>
                      <td className="py-3 pl-3 align-top">
                        <div className="flex items-center justify-end gap-2 flex-wrap">
                          {(r.status === "pending" || r.status === "suspended") && (
                            <button
                              onClick={() =>
                                void runAction(
                                  r.id,
                                  r.status === "pending" ? "activate" : "resume"
                                )
                              }
                              disabled={!!working}
                              className="px-2.5 py-1.5 rounded-lg bg-emerald-600 text-white text-xs font-semibold hover:bg-emerald-700 transition disabled:opacity-60 inline-flex items-center gap-1"
                            >
                              {working === "activate" || working === "resume" ? (
                                <Loader2 className="w-3.5 h-3.5 animate-spin" />
                              ) : r.status === "pending" ? (
                                <Play className="w-3.5 h-3.5" />
                              ) : (
                                <RefreshCw className="w-3.5 h-3.5" />
                              )}
                              {r.status === "pending" ? "Activate" : "Resume"}
                            </button>
                          )}
                          {r.status === "active" && (
                            <button
                              onClick={() => void runAction(r.id, "suspend")}
                              disabled={!!working}
                              className="px-2.5 py-1.5 rounded-lg border border-amber-400 text-amber-700 bg-amber-50 text-xs font-semibold hover:bg-amber-100 transition disabled:opacity-60 inline-flex items-center gap-1"
                            >
                              {working === "suspend" ? (
                                <Loader2 className="w-3.5 h-3.5 animate-spin" />
                              ) : (
                                <Pause className="w-3.5 h-3.5" />
                              )}
                              Suspend
                            </button>
                          )}
                          {r.status !== "cancelled" && (
                            <button
                              onClick={() => {
                                if (
                                  !confirm(
                                    `Cancel subscription for ${r.domain_name}? The SmarterMail domain will be deleted.`
                                  )
                                )
                                  return;
                                void runAction(r.id, "cancel");
                              }}
                              disabled={!!working}
                              className="px-2.5 py-1.5 rounded-lg border border-rose-300 text-rose-600 text-xs font-semibold hover:bg-rose-50 transition disabled:opacity-60 inline-flex items-center gap-1"
                            >
                              {working === "cancel" ? (
                                <Loader2 className="w-3.5 h-3.5 animate-spin" />
                              ) : (
                                <Ban className="w-3.5 h-3.5" />
                              )}
                              Cancel
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>
    </CmsLayout>
  );
}