"use client";

/**
 * Settings → Billing
 * ──────────────────
 * Reads the authoritative plan context from PlanProvider (same source
 * /admin + /pricing read from) so the numbers here match every other
 * entitlement surface. Until Stripe ships, payment management is a
 * "contact us" placeholder; the tab still shows real plan name, price,
 * cycle, renewal date, and trial countdown so users can verify what
 * they're on.
 */

import Link from "next/link";
import { CreditCard, ExternalLink, AlertTriangle, Clock, CheckCircle2 } from "lucide-react";
import { usePlan } from "@/context/plan-context";
import { PLANS, formatPlanPrice } from "@/lib/plan-config";

function formatDate(iso: string | null | undefined): string | null {
  if (!iso) return null;
  try {
    return new Date(iso).toLocaleDateString(undefined, { month: "long", day: "numeric", year: "numeric" });
  } catch { return iso; }
}

function daysUntil(iso: string | null | undefined): number | null {
  if (!iso) return null;
  try {
    const ms = new Date(iso).getTime() - Date.now();
    return Math.max(0, Math.ceil(ms / 86_400_000));
  } catch { return null; }
}

export default function BillingTab() {
  const { plan, loading } = usePlan();

  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 planData = PLANS[plan.effectivePlan];
  const isTrial = plan.plan === "trial";
  const cycleLabel = plan.billingCycle === "annual" ? "Annual (billed yearly)" : "Monthly";
  const priceLabel = planData.monthlyPrice == null ? "Custom" : formatPlanPrice(planData, plan.billingCycle);
  const nextBilling = formatDate(plan.planExpiresAt);
  const trialDaysLeft = isTrial ? daysUntil(plan.planExpiresAt) : null;

  return (
    <div className="space-y-6">
      {/* Trial countdown — only rendered during the trial so it
          doesn't add clutter once the user is on a real plan. */}
      {isTrial && (
        <div className="flex items-start gap-3 rounded-xl border border-brand-200 bg-brand-50/40 px-5 py-4">
          <Clock className="w-4 h-4 text-brand-600 mt-0.5 shrink-0" />
          <div className="flex-1">
            <p className="text-sm font-semibold text-brand-900">
              Trial — {trialDaysLeft ?? "—"} day{trialDaysLeft === 1 ? "" : "s"} remaining
            </p>
            <p className="text-xs text-brand-800/80 mt-0.5">
              You&apos;re currently getting full <span className="font-semibold">{PLANS[plan.effectivePlan]?.name}</span> access.
              After the trial ends your workspace drops to Growth features — pick a plan below to keep full access.
            </p>
            <Link
              href="/pricing"
              className="inline-flex items-center gap-1 text-xs font-semibold text-brand-700 mt-2 hover:underline"
            >
              Choose a plan →
            </Link>
          </div>
        </div>
      )}

      {/* Current plan card */}
      <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">
          <CreditCard className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Subscription</h2>
          <span className="ml-auto text-[10px] font-bold uppercase tracking-wider text-slate-500 bg-slate-100 rounded-full px-2.5 py-0.5">
            Stripe integration coming soon
          </span>
        </div>
        <div className="px-6 py-5">
          <div className="flex items-center gap-3 mb-4">
            <span className="text-lg font-bold text-slate-900">{planData.name}</span>
            <span className="inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider text-brand-700 bg-brand-50 border border-brand-200 rounded-full px-2.5 py-0.5">
              <CheckCircle2 className="w-2.5 h-2.5" /> Current Plan
            </span>
            {plan.effectivePlan !== plan.plan && (
              <span className="text-[10px] font-bold uppercase tracking-wider text-amber-700 bg-amber-50 border border-amber-200 rounded-full px-2.5 py-0.5">
                Trial → {PLANS[plan.effectivePlan]?.name}
              </span>
            )}
          </div>

          <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 mb-5">
            <div>
              <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Price</p>
              <p className="text-sm font-bold text-slate-900">
                {priceLabel}
                {plan.billingCycle === "annual" && planData.annualMonthlyPrice != null && (
                  <span className="ml-1 text-[10px] text-emerald-600 font-semibold">
                    save ${planData.annualSavings?.toLocaleString()}/yr
                  </span>
                )}
              </p>
            </div>
            <div>
              <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Billing Cycle</p>
              <p className="text-sm font-bold text-slate-900">{cycleLabel}</p>
            </div>
            <div>
              <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">
                {isTrial ? "Trial Ends" : "Next Renewal"}
              </p>
              <p className="text-sm font-bold text-slate-900">{nextBilling ?? "—"}</p>
            </div>
          </div>

          <div className="flex items-center gap-2 flex-wrap">
            <Link
              href="/pricing"
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-brand-600 text-white text-xs font-semibold hover:bg-brand-700"
            >
              Change Plan
            </Link>
            <a
              href="mailto:billing@meseo.io?subject=Billing%20question"
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg border border-slate-200 text-xs font-semibold text-slate-700 hover:bg-slate-50"
            >
              <ExternalLink className="w-3 h-3" /> Manage Billing
            </a>
            <p className="text-[11px] text-slate-400 ml-1">
              Stripe self-serve portal arrives soon — until then billing@meseo.io picks up change requests.
            </p>
          </div>
        </div>
      </div>

      {/* Invoice history placeholder */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-100"><h2 className="font-bold text-slate-800 text-sm">Invoice History</h2></div>
        <div className="px-6 py-8 text-center">
          <p className="text-sm text-slate-500 mb-2">Invoice history and payment management via Stripe.</p>
          <span className="text-[10px] font-bold uppercase tracking-widest text-slate-400 bg-slate-100 rounded-full px-2.5 py-0.5">Stripe Integration Coming Soon</span>
        </div>
      </div>

      {/* Danger zone */}
      <div className="bg-white rounded-xl border border-red-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-red-100 bg-red-50/40 flex items-center gap-2">
          <AlertTriangle className="w-4 h-4 text-red-500" />
          <h2 className="font-bold text-slate-800 text-sm">Danger Zone</h2>
        </div>
        <div className="px-6 py-5 space-y-3">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-semibold text-slate-800">Cancel Subscription</p>
              <p className="text-xs text-slate-500">Your access continues until the end of your billing period.</p>
            </div>
            <a
              href="mailto:billing@meseo.io?subject=Cancel%20subscription"
              className="px-4 py-2 rounded-lg border border-red-200 text-xs font-semibold text-red-600 hover:bg-red-50"
            >
              Cancel
            </a>
          </div>
          <div className="flex items-center justify-between pt-3 border-t border-red-100">
            <div>
              <p className="text-sm font-semibold text-slate-800">Delete Organization</p>
              <p className="text-xs text-slate-500">Permanently remove all data. This cannot be undone.</p>
            </div>
            <a
              href="mailto:billing@meseo.io?subject=Delete%20organization"
              className="px-4 py-2 rounded-lg bg-red-600 text-xs font-semibold text-white hover:bg-red-700"
            >
              Delete
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}
