"use client";

/**
 * Settings → Usage
 * ────────────────
 * Real usage meters sourced from /api/me/plan (current plan + limits
 * + brand/AI-credit usage) and /api/organizations/members (seat
 * count). Bars colour-code to three bands:
 *   green  <60% used
 *   orange 60–80% used  (plus amber text)
 *   red    >80% used    (triggers the upgrade banner)
 *
 * Limits shown reflect the effectivePlan — an expired trial flips to
 * Growth limits automatically via resolveEffectivePlan in the server
 * handler. Unlimited tiers render an infinity glyph instead of a bar.
 */

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  BarChart3, Sparkles, FileText, Layers, AlertTriangle, Infinity as InfinityIcon,
  Users, Search, Globe, Database, Mail,
} from "lucide-react";
import { usePlan, usePlanContext } from "@/context/plan-context";
import { useBrand } from "@/context/brand-context";
import { PLANS } from "@/lib/plan-config";

interface MemberCount { total: number }

export default function UsageTab() {
  const { plan, loading } = usePlan();
  const { openUpgrade } = usePlanContext();
  const { orgId } = useBrand();
  const [members, setMembers] = useState<MemberCount | null>(null);

  // Seat count = number of OrgMemberships for the active org.
  useEffect(() => {
    if (!orgId) return;
    fetch(`/api/organizations/members?orgId=${orgId}`)
      .then((r) => (r.ok ? r.json() : []))
      .then((rows) => setMembers({ total: Array.isArray(rows) ? rows.length : 0 }))
      .catch(() => setMembers({ total: 0 }));
  }, [orgId]);

  if (loading || !plan) {
    return (
      <div className="flex items-center justify-center py-16">
        <div className="w-5 h-5 border-2 border-slate-200 border-t-slate-600 rounded-full animate-spin" />
      </div>
    );
  }

  const resetDate = plan.usage.aiCreditsResetAt
    ? new Date(plan.usage.aiCreditsResetAt).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" })
    : "next billing cycle";

  const currentPlanName = PLANS[plan.effectivePlan]?.name ?? plan.effectivePlan;

  // Every metric the card renders — kept as data so the loop is
  // just one pattern instead of N copy-pasted blocks.
  const u = plan.usage as unknown as Record<string, number>;
  const metrics = [
    { icon: Layers,  label: "Brands",               used: plan.usage.brandsUsed,        limit: plan.limits.maxBrands,            color: "bg-amber-500" },
    { icon: Users,   label: "Team seats",           used: members?.total ?? 0,          limit: plan.limits.seats,                 color: "bg-sky-500" },
    { icon: Sparkles,label: "AI credits this period", used: plan.usage.aiCreditsUsed,   limit: plan.limits.aiCredits,             color: "bg-brand-500" },
    { icon: Search,  label: "Rank tracking keywords",used: u.rankKeywordsUsed ?? 0,     limit: plan.limits.rankKeywords,          color: "bg-violet-500" },
    { icon: FileText,label: "Content briefs (period)", used: u.contentBriefsUsed ?? 0,  limit: plan.limits.contentBriefs,         color: "bg-emerald-500" },
    { icon: Database,label: "SERP & keyword lookups", used: u.serpLookupsUsed ?? 0,      limit: plan.limits.dataForSeoLookups,     color: "bg-indigo-500" },
    { icon: Globe,   label: "Site Tag events (period)", used: u.siteTagEventsUsed ?? 0, limit: plan.limits.siteTagEvents,         color: "bg-teal-500" },
    { icon: Mail,    label: "Email schedules",       used: u.emailSchedulesUsed ?? 0,    limit: plan.limits.emailSchedules,        color: "bg-rose-500" },
  ];

  const anyNearLimit = metrics.some((m) =>
    m.limit !== "unlimited" && typeof m.limit === "number" && m.limit > 0 && m.used / m.limit >= 0.8,
  );

  return (
    <div className="space-y-6">
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100 flex items-center gap-2">
          <BarChart3 className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">
            Usage — {currentPlanName}
            {plan.effectivePlan !== plan.plan && (
              <span className="ml-2 text-[10px] font-bold uppercase tracking-wider text-amber-600 bg-amber-50 px-1.5 py-0.5 rounded">
                Trial → {PLANS[plan.effectivePlan]?.name}
              </span>
            )}
          </h2>
          <span className="ml-auto text-xs text-slate-400">AI credits reset {resetDate}</span>
        </div>
        <div className="px-6 py-5 grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5">
          {metrics.map((m) => (
            <UsageBar key={m.label} icon={m.icon} label={m.label} used={m.used} limit={m.limit} color={m.color} />
          ))}
        </div>
      </div>

      {/* Upgrade prompt — fires when any metric is ≥80% of its cap */}
      {anyNearLimit && (
        <div className="flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 px-5 py-4">
          <AlertTriangle className="w-4 h-4 text-amber-600 mt-0.5 shrink-0" />
          <div className="flex-1">
            <p className="text-sm font-semibold text-amber-900">Approaching usage limits</p>
            <p className="text-xs text-amber-700 mt-0.5">
              You&apos;re within 20% of one or more plan caps. Upgrade for more capacity or add a one-off pack from Billing.
            </p>
            <div className="flex items-center gap-3 mt-2">
              <button
                onClick={() => openUpgrade({ kind: "manual" })}
                className="inline-flex items-center gap-1 text-xs font-semibold text-brand-600 hover:underline"
              >
                Upgrade plan →
              </button>
              <Link
                href="/pricing#add-ons"
                className="inline-flex items-center gap-1 text-xs font-semibold text-slate-600 hover:underline"
              >
                See add-ons →
              </Link>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function UsageBar({ icon: Icon, label, used, limit, color }: {
  icon: typeof Sparkles;
  label: string;
  used: number;
  limit: number | "unlimited";
  color: string;
}) {
  if (limit === "unlimited") {
    return (
      <div>
        <div className="flex items-center justify-between mb-1.5">
          <div className="flex items-center gap-1.5"><Icon className="w-3.5 h-3.5 text-slate-500" /><span className="text-xs font-semibold text-slate-700">{label}</span></div>
          <span className="inline-flex items-center gap-1 text-xs font-bold text-emerald-600">
            {used.toLocaleString()} <InfinityIcon className="w-3 h-3" />
          </span>
        </div>
        <div className="h-2 rounded-full bg-gradient-to-r from-emerald-200 via-emerald-400 to-emerald-200" />
      </div>
    );
  }
  // Avoid divide-by-zero on plans with limit: 0 (growth emailSchedules).
  const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : (used > 0 ? 100 : 0);
  const band = pct >= 80 ? "danger" : pct >= 60 ? "warn" : "ok";
  const bandClasses = band === "danger" ? "bg-red-500" : band === "warn" ? "bg-amber-500" : color;
  const textClasses = band === "danger" ? "text-red-600" : band === "warn" ? "text-amber-600" : "text-slate-600";

  return (
    <div>
      <div className="flex items-center justify-between mb-1.5">
        <div className="flex items-center gap-1.5"><Icon className="w-3.5 h-3.5 text-slate-500" /><span className="text-xs font-semibold text-slate-700">{label}</span></div>
        <span className={`text-xs font-bold tabular-nums ${textClasses}`}>
          {used.toLocaleString()} / {limit.toLocaleString()}
        </span>
      </div>
      <div className="h-2 rounded-full bg-slate-100 overflow-hidden">
        <div className={`h-full rounded-full transition-all ${bandClasses}`} style={{ width: `${pct}%` }} />
      </div>
    </div>
  );
}
