// @File: src/pages/admin/cms/whatsapp/CmsWhatsappSubscriptions.tsx
// @Desc: Admin view of all client WhatsApp subscriptions with lifecycle
//        actions (suspend / resume / terminate).
import { useEffect, useMemo, useState } from "react";
import { Users, Loader2, RefreshCw, Search, Pause, Play, Ban } from "lucide-react";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Badge, TextInput, Select } from "../ui";
import {
  waAdminListSubscriptions,
  waAdminSubscriptionAction,
  type WhatsappSubscription,
} from "@/lib/whatsappApi";

const STATUS_TONES: Record<string, "green" | "amber" | "red" | "slate"> = {
  active: "green",
  suspended: "amber",
  terminated: "red",
};

function fmtDate(iso: string | null): string {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleString();
  } catch {
    return iso;
  }
}

export default function CmsWhatsappSubscriptions() {
  const [rows, setRows] = useState<WhatsappSubscription[]>([]);
  const [loading, setLoading] = useState(false);
  const [statusFilter, setStatusFilter] = useState<string>("");
  const [search, setSearch] = useState("");
  const [actingId, setActingId] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);

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

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

  const act = async (sub: WhatsappSubscription, action: "suspend" | "resume" | "terminate") => {
    if (action === "terminate" && !confirm(`Terminate ${sub.user_email ?? sub.user_id}?`)) return;
    setActingId(sub.id);
    setError(null);
    setNotice(null);
    try {
      const res = await waAdminSubscriptionAction(sub.id, action);
      setNotice(res.message);
      await load();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Action failed");
    } finally {
      setActingId(null);
    }
  };

  const counts = useMemo(() => {
    const out = { active: 0, suspended: 0, terminated: 0 };
    for (const r of rows) {
      if (r.status in out) out[r.status as keyof typeof out] += 1;
    }
    return out;
  }, [rows]);

  return (
    <CmsLayout>
      <PageHeader
        icon={<Users className="w-6 h-6" />}
        title="WhatsApp Subscriptions"
        description="Every client subscription to a WhatsApp package — suspend, resume or terminate from here."
      />

      <SectionCard
        title={`Subscriptions (${rows.length})`}
        description={`${counts.active} active · ${counts.suspended} suspended · ${counts.terminated} terminated`}
        actions={
          <button
            type="button"
            onClick={() => void load()}
            className="px-3 py-2 rounded-lg border border-slate-300 bg-white text-xs font-semibold text-slate-700 hover:bg-slate-100 transition inline-flex items-center gap-2"
          >
            <RefreshCw className="w-4 h-4" />
            Refresh
          </button>
        }
      >
        <div className="flex flex-wrap gap-3">
          <div className="relative flex-1 min-w-[220px]">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
            <TextInput
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") void load();
              }}
              placeholder="Search by email…"
              className="!pl-9"
            />
          </div>
          <Select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="max-w-[180px]"
          >
            <option value="">All statuses</option>
            <option value="active">Active</option>
            <option value="suspended">Suspended</option>
            <option value="terminated">Terminated</option>
          </Select>
          <button
            type="button"
            onClick={() => void load()}
            className="px-3 py-2 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold hover:bg-[#0a8048] transition"
          >
            Search
          </button>
        </div>

        {error && (
          <div className="rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">
            {error}
          </div>
        )}
        {notice && (
          <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-700">
            {notice}
          </div>
        )}

        <div className="overflow-x-auto rounded-xl border border-slate-200">
          <table className="min-w-full text-sm">
            <thead className="bg-slate-50 text-slate-600">
              <tr>
                <th className="text-left p-3 font-semibold">Client</th>
                <th className="text-left p-3 font-semibold">Package</th>
                <th className="text-left p-3 font-semibold">Usage</th>
                <th className="text-left p-3 font-semibold">Status</th>
                <th className="text-left p-3 font-semibold">Activated</th>
                <th className="text-right p-3 font-semibold">Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading && (
                <tr>
                  <td colSpan={6} className="p-6 text-center text-slate-500">
                    <Loader2 className="w-4 h-4 animate-spin inline mr-2" /> Loading…
                  </td>
                </tr>
              )}
              {!loading && rows.length === 0 && (
                <tr>
                  <td colSpan={6} className="p-6 text-center text-slate-500">
                    No subscriptions yet.
                  </td>
                </tr>
              )}
              {rows.map((s) => (
                <tr key={s.id} className="border-t border-slate-200">
                  <td className="p-3 align-top">
                    <div className="font-semibold text-slate-900">
                      {s.user_email || <span className="text-slate-400">—</span>}
                    </div>
                    <div className="text-[11px] text-slate-500 font-mono">#{s.user_id}</div>
                    {s.whmcs_service_id != null && (
                      <div className="text-[11px] text-slate-400">
                        WHMCS svc #{s.whmcs_service_id}
                      </div>
                    )}
                  </td>
                  <td className="p-3 align-top">
                    <div className="font-semibold text-slate-900">
                      {s.package?.name ?? `#${s.package_id}`}
                    </div>
                    <div className="text-[11px] text-slate-500">
                      {s.package?.slug}
                    </div>
                  </td>
                  <td className="p-3 align-top text-xs text-slate-700 space-y-0.5">
                    <div>Devices: {s.devices_used}</div>
                    <div>Msgs (month): {s.messages_used_month.toLocaleString()}</div>
                    <div>Contacts: {s.contacts_used.toLocaleString()}</div>
                    <div>Campaigns: {s.campaigns_used}</div>
                  </td>
                  <td className="p-3 align-top">
                    <Badge tone={STATUS_TONES[s.status] ?? "slate"}>
                      {s.status}
                    </Badge>
                  </td>
                  <td className="p-3 align-top text-xs text-slate-600">
                    {fmtDate(s.activated_at)}
                  </td>
                  <td className="p-3 align-top text-right">
                    <div className="inline-flex gap-1">
                      {s.status !== "suspended" && s.status !== "terminated" && (
                        <button
                          disabled={actingId === s.id}
                          onClick={() => void act(s, "suspend")}
                          className="px-2 py-1.5 rounded-lg border border-amber-200 hover:bg-amber-50 text-amber-700 text-xs inline-flex items-center gap-1 disabled:opacity-50"
                          title="Suspend"
                        >
                          <Pause className="w-3.5 h-3.5" /> Suspend
                        </button>
                      )}
                      {s.status === "suspended" && (
                        <button
                          disabled={actingId === s.id}
                          onClick={() => void act(s, "resume")}
                          className="px-2 py-1.5 rounded-lg border border-emerald-200 hover:bg-emerald-50 text-emerald-700 text-xs inline-flex items-center gap-1 disabled:opacity-50"
                          title="Resume"
                        >
                          <Play className="w-3.5 h-3.5" /> Resume
                        </button>
                      )}
                      {s.status !== "terminated" && (
                        <button
                          disabled={actingId === s.id}
                          onClick={() => void act(s, "terminate")}
                          className="px-2 py-1.5 rounded-lg border border-rose-200 hover:bg-rose-50 text-rose-700 text-xs inline-flex items-center gap-1 disabled:opacity-50"
                          title="Terminate"
                        >
                          <Ban className="w-3.5 h-3.5" /> Terminate
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>
    </CmsLayout>
  );
}