"use client";

import { useEffect, useState } from "react";

interface RevenueData {
  proFamilies: number;
  freeFamilies: number;
  mrr: number; // rupees
}

const inr = (rupees: number) =>
  "₹" + (Number(rupees) || 0).toLocaleString("en-IN", { maximumFractionDigits: 0 });

export default function AdminRevenue() {
  const [data, setData] = useState<RevenueData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/admin/stats", { credentials: "include" })
      .then((r) => r.json())
      .then((stats) => {
        setData({
          proFamilies: stats.overview?.proFamilies || 0,
          freeFamilies: stats.overview?.freeFamilies || 0,
          mrr: stats.overview?.mrr || 0,
        });
      })
      .catch((err) => console.error("Failed to fetch revenue:", err))
      .finally(() => setLoading(false));
  }, []);

  if (loading || !data) {
    return <div className="p-6 text-white">Loading...</div>;
  }

  // ARPU across paying families only (avoids a misleading blended number).
  const arpu = data.proFamilies > 0 ? data.mrr / data.proFamilies : 0;

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Revenue</h1>
        <p className="text-gray-400">Real subscription revenue, in ₹ (from active Razorpay subscriptions)</p>
        <p className="text-xs text-gray-500 mt-1">
          For per-subscription detail, see the <a href="/admin/subscriptions" className="text-rose-400 underline">Subscriptions</a> page.
        </p>
      </div>

      {/* Key Metrics */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-gray-800 p-6 rounded-xl">
          <div className="text-3xl font-bold text-emerald-400">{inr(data.mrr)}</div>
          <div className="text-gray-400 text-sm">Monthly Recurring Revenue</div>
        </div>
        <div className="bg-gray-800 p-6 rounded-xl">
          <div className="text-3xl font-bold text-rose-400">{inr(data.mrr * 12)}</div>
          <div className="text-gray-400 text-sm">Annual Run Rate</div>
        </div>
        <div className="bg-gray-800 p-6 rounded-xl">
          <div className="text-3xl font-bold text-rose-400">{data.proFamilies}</div>
          <div className="text-gray-400 text-sm">Paying Families</div>
        </div>
        <div className="bg-gray-800 p-6 rounded-xl">
          <div className="text-3xl font-bold text-gray-400">{data.freeFamilies}</div>
          <div className="text-gray-400 text-sm">Free Families</div>
        </div>
      </div>

      {/* Revenue Breakdown */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="bg-gray-800 p-6 rounded-xl">
          <h3 className="text-lg font-semibold mb-4">Revenue by Tier</h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-emerald-400">Premium</span>
              <span className="font-bold">{inr(data.mrr)}/mo</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-400">Free</span>
              <span className="font-bold">₹0/mo</span>
            </div>
            <div className="flex justify-between items-center border-t border-gray-700 pt-3">
              <span className="text-gray-400">ARPU (paying)</span>
              <span className="font-bold text-gray-300">{inr(arpu)}/mo</span>
            </div>
          </div>
        </div>

        <div className="bg-gray-800 p-6 rounded-xl">
          <h3 className="text-lg font-semibold mb-4">Growth Potential</h3>
          <p className="text-xs text-gray-500 mb-3">If free families convert at premium price</p>
          <div className="space-y-3">
            {[0.1, 0.25, 0.5].map((rate) => (
              <div key={rate} className="flex justify-between items-center">
                <span>If {rate * 100}% convert</span>
                <span className={`font-bold ${rate >= 0.5 ? "text-emerald-400" : "text-amber-400"}`}>
                  {inr(data.freeFamilies * rate * arpu)}/mo
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
