// @File: src/pages/admin/cms/bizmail/CmsBizmailHome.tsx
// @Desc: Landing page for the Bizmail360 Reseller Manager module. Shows a
//        health summary for the SmarterMail integration + tiles for plans,
//        subscriptions, audit log and API settings.
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  Inbox,
  ArrowRight,
  Layers,
  Users,
  FileSearch,
  KeyRound,
  AlertTriangle,
  ShieldCheck,
  Loader2,
} from "lucide-react";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Badge } from "../ui";
import {
  adminTestIntegration,
  type BizmailIntegrationTestResult,
} from "@/lib/bizmailApi";

const tiles = [
  {
    to: "/admin/cms/bizmail/plans",
    icon: Layers,
    title: "Plans",
    desc: "Create and publish the Bizmail360 mail plans you resell to clients.",
    tone: "from-emerald-600 to-emerald-500",
  },
  {
    to: "/admin/cms/bizmail/subscriptions",
    icon: Users,
    title: "Client Subscriptions",
    desc: "Provision, suspend, resume or cancel client mail subscriptions.",
    tone: "from-indigo-600 to-indigo-500",
  },
  {
    to: "/admin/cms/bizmail/audit-log",
    icon: FileSearch,
    title: "Audit Log",
    desc: "Every SmarterMail API call, status and error across the module.",
    tone: "from-amber-500 to-amber-400",
  },
  {
    to: "/admin/cms/api-hub",
    icon: KeyRound,
    title: "API Settings",
    desc: "Manage the SmarterMail admin credentials in the API Hub.",
    tone: "from-slate-700 to-slate-600",
  },
];

export default function CmsBizmailHome() {
  const [probe, setProbe] = useState<BizmailIntegrationTestResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

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

  return (
    <CmsLayout>
      <PageHeader
        icon={<Inbox className="w-6 h-6" />}
        title="Bizmail360 Reseller Manager"
        description="Resell SmarterMail-powered professional email hosting under your own brand."
      />

      <SectionCard
        title="Integration Health"
        description="SmarterMail admin API connectivity from this platform."
        actions={
          <button
            onClick={() => void runProbe()}
            disabled={loading}
            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"
          >
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <ShieldCheck className="w-4 h-4" />}
            Test Connection
          </button>
        }
      >
        {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>
        )}
        <div className="flex items-center justify-between flex-wrap gap-3">
          <div className="flex items-center gap-3">
            {probe?.ok ? (
              <Badge tone="green">Connected</Badge>
            ) : probe ? (
              <Badge tone="red">Offline</Badge>
            ) : (
              <Badge tone="slate">Unknown</Badge>
            )}
            <span className="text-sm text-slate-700">
              {probe?.message ?? (loading ? "Checking SmarterMail…" : "Run a test to check the connection.")}
            </span>
          </div>
          {probe?.latency_ms != null && (
            <span className="text-xs text-slate-500">Latency: {probe.latency_ms} ms</span>
          )}
        </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>
  );
}