"use client";

import { useEffect, useState } from "react";

interface RevenueData {
  proFamilies: number;
  freeFamilies: number;
  mrr: number;
  history: { month: string; revenue: number }[];
}

const PRO_PRICE = 9.99;

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

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

  const fetchRevenue = async () => {
    try {
      const res = await fetch("/api/admin/stats", { credentials: "include" });
      const stats = await res.json();
      setData({
        proFamilies: stats.overview?.proFamilies || 0,
        freeFamilies: stats.overview?.freeFamilies || 0,
        mrr: stats.overview?.mrr || 0,
        history: generateMonthlyHistory(stats.overview?.proFamilies || 0),
      });
    } catch (err) {
      console.error("Failed to fetch revenue:", err);
    }
    setLoading(false);
  };

  const generateMonthlyHistory = (proCount: number): { month: string; revenue: number }[] => {
    const months: { month: string; revenue: number }[] = [];
    for (let i = 11; i >= 0; i--) {
      const date = new Date();
      date.setMonth(date.getMonth() - i);
      months.push({
        month: date.toLocaleDateString("en-US", { month: "short", year: "2-digit" }),
        revenue: proCount > 0 ? proCount * PRO_PRICE : 0,
      });
    }
    return months;
  };

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

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Revenue</h1>
        <p className="text-gray-400">Subscription revenue analytics</p>
        <p className="text-sm text-rose-400">Pro: ${PRO_PRICE}/month per family</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">${data.mrr.toFixed(2)}</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">${(data.mrr * 12).toFixed(2)}</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">Pro 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 Chart */}
      <div className="bg-gray-800 p-6 rounded-xl">
        <h3 className="text-lg font-semibold mb-4">Monthly Revenue</h3>
        <div className="h-48 flex items-end gap-1">
          {data.history.map((h, i) => (
            <div key={i} className="flex-1 flex flex-col items-center gap-1">
              <div
                className="w-full bg-emerald-500 rounded-t"
                style={{
                  height: data.mrr > 0 ? `${(h.revenue / (data.mrr * 1.2)) * 100}%` : "0%",
                  minHeight: h.revenue > 0 ? "4px" : "0"
                }}
              />
              <div className="text-[8px] text-gray-500">{h.month}</div>
            </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">Pro</span>
              <span className="font-bold">${(data.proFamilies * PRO_PRICE).toFixed(2)}/mo</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-400">Free</span>
              <span className="font-bold">$0.00/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>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span>If 10% convert</span>
              <span className="font-bold text-amber-400">
                ${((data.freeFamilies * 0.1) * PRO_PRICE).toFixed(2)}/mo
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span>If 25% convert</span>
              <span className="font-bold text-amber-400">
                ${((data.freeFamilies * 0.25) * PRO_PRICE).toFixed(2)}/mo
              </span>
            </div>
            <div className="flex justify-between items-center">
              <span>If 50% convert</span>
              <span className="font-bold text-emerald-400">
                ${((data.freeFamilies * 0.5) * PRO_PRICE).toFixed(2)}/mo
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}