// @File: src/pages/admin/cms/uptimerobot/CmsUptimeRobotUsage.tsx
// @Desc: Team plan usage dashboard with the 70%/85%/95% warning ladder
//        and an upgrade banner when any resource is exhausted.
import { useCallback, useEffect, useState } from "react";
import {
  BarChart3,
  AlertTriangle,
  ShieldCheck,
  RefreshCw,
  Loader2,
} from "lucide-react";
import { toast } from "sonner";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard } from "../ui";
import {
  adminGetTeamUsage,
  adminSyncNow,
  meterTone,
  percentOf,
  warningTone,
  type UptimeMeter,
  type UptimeTeamUsage,
} from "@/lib/uptimerobotApi";

function Meter({
  label,
  meter,
  description,
}: {
  label: string;
  meter: UptimeMeter;
  description?: string;
}) {
  const pct = percentOf(meter);
  const tone = meterTone(meter);
  return (
    <div
      className={`rounded-xl border ${tone.border} ${tone.bg} p-5 transition`}
    >
      <div className="flex items-start justify-between">
        <div>
          <div className="text-xs uppercase tracking-wide font-bold text-slate-500">
            {label}
          </div>
          <div className="text-3xl font-extrabold text-slate-900 mt-1">
            {meter.used}
            <span className="text-base font-semibold text-slate-400 ml-1">
              {meter.unlimited ? "/∞" : meter.total !== null ? `/${meter.total}` : "/—"}
            </span>
          </div>
          {description && (
            <div className="text-xs text-slate-500 mt-0.5">{description}</div>
          )}
        </div>
        {!meter.unlimited && meter.total !== null && (
          <div
            className={`px-2.5 py-1 rounded-full ${tone.bg} ${tone.text} text-xs font-bold border ${tone.border}`}
          >
            {pct}%
          </div>
        )}
      </div>
      <div className="mt-3 h-2 rounded-full bg-slate-200 overflow-hidden">
        <div
          className={`h-full transition-all ${tone.bar}`}
          style={{ width: `${meter.unlimited ? 30 : pct}%` }}
        />
      </div>
    </div>
  );
}

export default function CmsUptimeRobotUsage() {
  const [usage, setUsage] = useState<UptimeTeamUsage | null>(null);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const u = await adminGetTeamUsage();
      setUsage(u);
    } catch (e) {
      toast.error(`Load failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const sync = async () => {
    setSyncing(true);
    try {
      const r = await adminSyncNow();
      if (r.ok) {
        toast.success(`Sync complete. ${r.monitors_synced} monitors updated.`);
      } else {
        toast.warning(r.error ?? "Sync completed with warnings.");
      }
      await load();
    } catch (e) {
      toast.error(`Sync failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setSyncing(false);
    }
  };

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

  return (
    <CmsLayout>
      <PageHeader
        title="Team Plan Usage"
        description="How much of your UptimeRobot Team plan is allocated to active client subscriptions."
        icon={<BarChart3 className="w-6 h-6" />}
      />

      <SectionCard
        title="Overall"
        description="Warning thresholds: 70% (yellow), 85% (orange), 95%+ (red)."
        actions={
          <button
            onClick={sync}
            disabled={syncing}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#095a32] transition disabled:opacity-60"
          >
            {syncing ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <RefreshCw className="w-4 h-4" />
            )}
            Sync now
          </button>
        }
      >
        {loading ? (
          <div className="flex items-center gap-2 text-slate-500 text-sm">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading…
          </div>
        ) : usage ? (
          <>
            <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-bold text-base">{usage.warning_label}</div>
                <div className="opacity-90">
                  Plan:{" "}
                  <span className="font-semibold">
                    {usage.plan_name ?? "Unknown"}
                  </span>
                  {usage.snapshot_at && (
                    <>
                      {" · Last snapshot: "}
                      {new Date(usage.snapshot_at).toLocaleString()}
                    </>
                  )}
                </div>
                {showUpgrade && (
                  <div className="mt-2 text-xs">
                    Your Team plan is nearly or fully consumed. Upgrade in the
                    UptimeRobot dashboard to continue onboarding new clients.
                  </div>
                )}
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mt-5">
              <Meter
                label="Monitors"
                meter={usage.monitors}
                description="All http/ping/port/keyword/heartbeat monitors we create on behalf of clients."
              />
              <Meter
                label="Alert contacts"
                meter={usage.alert_contacts}
                description="Email/SMS/webhook destinations used by any client subscription."
              />
              <Meter
                label="Status pages"
                meter={usage.status_pages}
                description="Public status pages published for clients."
              />
              <Meter
                label="Maintenance windows"
                meter={usage.maintenance_windows}
                description="Scheduled maintenance windows in use across all clients."
              />
            </div>
          </>
        ) : null}
      </SectionCard>
    </CmsLayout>
  );
}