// @File: src/pages/admin/cms/whatsapp/CmsWhatsappHome.tsx
// @Desc: Landing page for the WhatsApp Reseller Manager admin module.
//        Shows an at-a-glance overview (packages, subscriptions, devices,
//        24h messages), the upstream integration health, and tiles that
//        route to the sub-consoles.
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  MessageSquare,
  ArrowRight,
  Layers,
  Users,
  FileSearch,
  KeyRound,
  AlertTriangle,
  ShieldCheck,
  Loader2,
  Activity,
  Server,
  Smartphone,
  Send,
} from "lucide-react";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Badge } from "../ui";
import {
  waAdminOverview,
  waAdminTestIntegration,
  type WhatsappAdminOverview,
  type WhatsappIntegrationResult,
} from "@/lib/whatsappApi";

const tiles = [
  {
    to: "/admin/cms/whatsapp/packages",
    icon: Layers,
    title: "Packages",
    desc: "Plan quotas, feature flags, pricing and WHMCS product linkage.",
    tone: "from-emerald-600 to-emerald-500",
  },
  {
    to: "/admin/cms/whatsapp/subscriptions",
    icon: Users,
    title: "Client Subscriptions",
    desc: "Suspend, resume or terminate any client's WhatsApp subscription.",
    tone: "from-indigo-600 to-indigo-500",
  },
  {
    to: "/admin/cms/whatsapp/audit-log",
    icon: FileSearch,
    title: "Audit & API Log",
    desc: "Every admin action and every upstream WhatsApp API call.",
    tone: "from-amber-500 to-amber-400",
  },
  {
    to: "/admin/cms/whatsapp/sync",
    icon: Activity,
    title: "Data Fetch",
    desc: "Scheduled import of clients, devices and domains from upstream.",
    tone: "from-sky-600 to-sky-500",
  },
  {
    to: "/admin/cms/api-hub/integrations",
    icon: KeyRound,
    title: "Upstream Credentials",
    desc: "Manage the whatsapp_server credentials in the API Hub.",
    tone: "from-slate-700 to-slate-600",
  },
];

function StatCard({
  icon: Icon,
  label,
  value,
  sub,
  tone = "text-[#0b6e3e]",
}: {
  icon: typeof Layers;
  label: string;
  value: number | string;
  sub?: string;
  tone?: string;
}) {
  return (
    <div className="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
      <div className="flex items-center gap-2 text-[11px] uppercase tracking-wider font-bold text-slate-500">
        <Icon className={`w-4 h-4 ${tone}`} />
        {label}
      </div>
      <div className="text-3xl font-extrabold text-slate-900 mt-2">{value}</div>
      {sub && <div className="text-xs text-slate-500 mt-1">{sub}</div>}
    </div>
  );
}

export default function CmsWhatsappHome() {
  const [overview, setOverview] = useState<WhatsappAdminOverview | null>(null);
  const [overviewError, setOverviewError] = useState<string | null>(null);
  const [probe, setProbe] = useState<WhatsappIntegrationResult | null>(null);
  const [probeError, setProbeError] = useState<string | null>(null);
  const [probing, setProbing] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const o = await waAdminOverview();
        setOverview(o);
      } catch (e) {
        setOverviewError(e instanceof Error ? e.message : "Failed to load overview");
      }
    })();
  }, []);

  const runProbe = async () => {
    setProbing(true);
    setProbeError(null);
    try {
      const res = await waAdminTestIntegration();
      setProbe(res);
    } catch (e) {
      setProbeError(e instanceof Error ? e.message : "Integration test failed");
      setProbe(null);
    } finally {
      setProbing(false);
    }
  };

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

  return (
    <CmsLayout>
      <PageHeader
        icon={<MessageSquare className="w-6 h-6" />}
        title="WhatsApp Reseller Manager"
        description="Resell WhatsApp Business API access under your brand — packages, devices, campaigns & automation."
      />

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <StatCard
          icon={Layers}
          label="Packages"
          value={overview ? `${overview.active_packages}/${overview.total_packages}` : "—"}
          sub="active / total"
        />
        <StatCard
          icon={Users}
          label="Subscriptions"
          value={overview ? `${overview.active_subscriptions}/${overview.total_subscriptions}` : "—"}
          sub={
            overview
              ? `${overview.suspended_subscriptions} suspended · ${overview.terminated_subscriptions} terminated`
              : "—"
          }
        />
        <StatCard
          icon={Smartphone}
          label="Devices"
          value={overview ? `${overview.connected_devices}/${overview.total_devices}` : "—"}
          sub="connected / total"
          tone="text-indigo-600"
        />
        <StatCard
          icon={Send}
          label="Msgs (24h)"
          value={overview ? overview.messages_last_24h.toLocaleString() : "—"}
          tone="text-amber-600"
        />
      </div>

      {overviewError && (
        <div className="mb-6 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>{overviewError}</span>
        </div>
      )}

      <SectionCard
        title="Upstream Integration Health"
        description="Connectivity to the WhatsApp server configured in the API Hub."
        actions={
          <button
            onClick={() => void runProbe()}
            disabled={probing}
            className="px-3 py-2 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold hover:bg-[#0a8048] transition disabled:opacity-60 inline-flex items-center gap-2"
          >
            {probing ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <ShieldCheck className="w-4 h-4" />
            )}
            Test Connection
          </button>
        }
      >
        {probeError && (
          <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>{probeError}</span>
          </div>
        )}
        <div className="flex items-center justify-between flex-wrap gap-3">
          <div className="flex items-center gap-3 min-w-0">
            {probe?.ok ? (
              <Badge tone="green">Online</Badge>
            ) : probe ? (
              <Badge tone="red">Offline</Badge>
            ) : (
              <Badge tone="slate">Unknown</Badge>
            )}
            <span className="text-sm text-slate-700 truncate">
              {probe?.message ??
                (probing ? "Checking upstream WhatsApp server…" : "Run a test to check connectivity.")}
            </span>
          </div>
          <div className="flex items-center gap-3 text-xs text-slate-500">
            {probe?.upstream_base_url && (
              <span className="inline-flex items-center gap-1">
                <Server className="w-3.5 h-3.5" /> {probe.upstream_base_url}
              </span>
            )}
            {probe?.latency_ms != null && <span>Latency: {probe.latency_ms} ms</span>}
          </div>
        </div>
      </SectionCard>

      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5 mt-6">
        {tiles.map((c) => {
          const Icon = c.icon;
          return (
            <Link
              key={c.to}
              to={c.to}
              className="group bg-white rounded-2xl border border-slate-200 p-6 shadow-sm hover:shadow-xl hover:-translate-y-0.5 transition"
            >
              <div
                className={`w-12 h-12 rounded-xl bg-gradient-to-br ${c.tone} text-white flex items-center justify-center mb-4 shadow`}
              >
                <Icon className="w-6 h-6" />
              </div>
              <div className="text-lg font-bold text-slate-900">{c.title}</div>
              <p className="text-sm text-slate-500 mt-1 mb-4">{c.desc}</p>
              <span className="text-sm font-semibold text-[#0b6e3e] inline-flex items-center gap-1 group-hover:gap-2 transition-all">
                Open <ArrowRight className="w-4 h-4" />
              </span>
            </Link>
          );
        })}
      </div>
    </CmsLayout>
  );
}