// @File: src/pages/admin/cms/uptimerobot/CmsUptimeRobotHome.tsx
// @Desc: Landing page for the UptimeRobot Reseller Manager module. Shows
//        a Team-plan health summary + tiles to the sub-pages (packages,
//        subscriptions, usage, API settings, diagnostics).
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
  Server,
  ArrowRight,
  Layers,
  Users,
  BarChart3,
  KeyRound,
  FileSearch,
  AlertTriangle,
  ShieldCheck,
  Loader2,
} from "lucide-react";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard } from "../ui";
import {
  adminGetTeamUsage,
  warningTone,
  type UptimeTeamUsage,
} from "@/lib/uptimerobotApi";

const tiles = [
  {
    to: "/admin/cms/uptimerobot/packages",
    icon: Layers,
    title: "Packages",
    desc: "Create and publish the monitoring plans you resell to clients.",
    tone: "from-emerald-600 to-emerald-500",
  },
  {
    to: "/admin/cms/uptimerobot/subscriptions",
    icon: Users,
    title: "Client Subscriptions",
    desc: "Assign, upgrade, suspend or terminate client subscriptions.",
    tone: "from-indigo-600 to-indigo-500",
  },
  {
    to: "/admin/cms/uptimerobot/usage",
    icon: BarChart3,
    title: "Team Plan Usage",
    desc: "Monitor consumption of your UptimeRobot Team plan quotas.",
    tone: "from-amber-500 to-amber-400",
  },
  {
    to: "/admin/cms/uptimerobot/api-settings",
    icon: KeyRound,
    title: "API Settings",
    desc: "Rotate the master API key, test the connection, sync on demand.",
    tone: "from-slate-700 to-slate-600",
  },
  {
    to: "/admin/cms/uptimerobot/diagnostics",
    icon: FileSearch,
    title: "Diagnostics",
    desc: "Inspect every outbound UptimeRobot API call, errors and latency.",
    tone: "from-rose-600 to-rose-500",
  },
];

export default function CmsUptimeRobotHome() {
  const [usage, setUsage] = useState<UptimeTeamUsage | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    adminGetTeamUsage()
      .then((u) => {
        if (!cancelled) setUsage(u);
      })
      .catch((e) => {
        if (!cancelled) setError(e instanceof Error ? e.message : String(e));
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const tone = usage ? warningTone(usage.warning_state) : warningTone("ok");
  const showUpgrade =
    usage &&
    (usage.warning_state === "upgrade_required" ||
      usage.warning_state === "critical_95");

  return (
    <CmsLayout>
      <PageHeader
        title="UptimeRobot Reseller"
        description="A single DoItEasy-branded control panel for reselling UptimeRobot monitoring plans."
        icon={<Server className="w-6 h-6" />}
      />

      <SectionCard
        title="Team plan health"
        description="A quick look at how much of your UptimeRobot Team plan is already allocated to clients."
      >
        {loading ? (
          <div className="flex items-center gap-2 text-slate-500 text-sm">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading usage…
          </div>
        ) : error ? (
          <div className="flex items-start gap-3 p-4 rounded-xl border border-red-200 bg-red-50 text-red-700 text-sm">
            <AlertTriangle className="w-5 h-5 shrink-0 mt-0.5" />
            <div>
              <div className="font-semibold">Could not load usage.</div>
              <div className="text-red-600/80">{error}</div>
            </div>
          </div>
        ) : usage ? (
          <div className="space-y-4">
            <div
              className={`flex items-start gap-3 p-4 rounded-xl border ${tone.border} ${tone.bg} ${tone.text}`}
            >
              {showUpgrade ? (
                <AlertTriangle className="w-5 h-5 shrink-0 mt-0.5" />
              ) : (
                <ShieldCheck className="w-5 h-5 shrink-0 mt-0.5" />
              )}
              <div className="text-sm">
                <div className="font-semibold">{usage.warning_label}</div>
                <div className="opacity-80">
                  Plan:{" "}
                  <span className="font-semibold">
                    {usage.plan_name ?? "Unknown"}
                  </span>
                  {usage.snapshot_at && (
                    <>
                      {" · Last snapshot: "}
                      {new Date(usage.snapshot_at).toLocaleString()}
                    </>
                  )}
                </div>
              </div>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
              <UsageChip
                label="Monitors"
                used={usage.monitors.used}
                total={usage.monitors.total}
              />
              <UsageChip
                label="Alert contacts"
                used={usage.alert_contacts.used}
                total={usage.alert_contacts.total}
              />
              <UsageChip
                label="Status pages"
                used={usage.status_pages.used}
                total={usage.status_pages.total}
              />
              <UsageChip
                label="Maintenance windows"
                used={usage.maintenance_windows.used}
                total={usage.maintenance_windows.total}
              />
            </div>
          </div>
        ) : null}
      </SectionCard>

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 mt-6">
        {tiles.map((t) => {
          const Icon = t.icon;
          return (
            <Link
              key={t.to}
              to={t.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 ${t.tone} text-white flex items-center justify-center shadow-md`}
              >
                <Icon className="w-6 h-6" />
              </div>
              <div className="mt-4 text-lg font-bold text-slate-900 flex items-center gap-2">
                {t.title}
                <ArrowRight className="w-4 h-4 opacity-0 group-hover:opacity-100 transition" />
              </div>
              <div className="text-sm text-slate-500 mt-1">{t.desc}</div>
            </Link>
          );
        })}
      </div>
    </CmsLayout>
  );
}

function UsageChip({
  label,
  used,
  total,
}: {
  label: string;
  used: number;
  total: number | null;
}) {
  const pct =
    total && total > 0 ? Math.min(100, Math.round((used / total) * 100)) : null;
  return (
    <div className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
      <div className="text-[11px] uppercase tracking-wide text-slate-500 font-semibold">
        {label}
      </div>
      <div className="text-xl font-bold text-slate-900 mt-1">
        {used}
        <span className="text-slate-400 text-sm font-normal">
          {" / "}
          {total ?? "—"}
        </span>
      </div>
      {pct !== null && (
        <div className="mt-2 h-1.5 rounded-full bg-slate-200 overflow-hidden">
          <div
            className={`h-full ${
              pct >= 95
                ? "bg-red-500"
                : pct >= 85
                  ? "bg-orange-500"
                  : pct >= 70
                    ? "bg-amber-500"
                    : "bg-emerald-500"
            }`}
            style={{ width: `${pct}%` }}
          />
        </div>
      )}
    </div>
  );
}