import prisma from "@/lib/prisma";

export const metadata = {
  title: "Revenue | Admin",
};

async function safeQuery<T>(query: string, fallback: T): Promise<T> {
  try {
    const result = await prisma.$queryRawUnsafe(query);
    return result as T;
  } catch {
    return fallback;
  }
}

export default async function AdminRevenuePage() {
  // Total revenue (all credit purchases in EUR)
  const [totalRevenueRows] = await safeQuery<{ total: number }[]>(
    `SELECT COALESCE(SUM(amount), 0)::float as total FROM credit_purchases WHERE status = 'completed'`,
    [{ total: 0 }]
  );

  // Revenue this month
  const [thisMonthRows] = await safeQuery<{ total: number }[]>(
    `SELECT COALESCE(SUM(amount), 0)::float as total FROM credit_purchases
     WHERE status = 'completed' AND created_at >= date_trunc('month', CURRENT_DATE)`,
    [{ total: 0 }]
  );

  // Revenue last month
  const [lastMonthRows] = await safeQuery<{ total: number }[]>(
    `SELECT COALESCE(SUM(amount), 0)::float as total FROM credit_purchases
     WHERE status = 'completed'
       AND created_at >= date_trunc('month', CURRENT_DATE - interval '1 month')
       AND created_at < date_trunc('month', CURRENT_DATE)`,
    [{ total: 0 }]
  );

  // Total credits in circulation
  const [creditsCirculation] = await safeQuery<{ total: number }[]>(
    `SELECT COALESCE(SUM(credits), 0)::float as total FROM users WHERE credits > 0`,
    [{ total: 0 }]
  );

  // Total credits used (spent)
  const [creditsUsed] = await safeQuery<{ total: number }[]>(
    `SELECT COALESCE(SUM(ABS(amount)), 0)::float as total FROM credit_transactions WHERE amount < 0`,
    [{ total: 0 }]
  );

  // Active paying users
  const [payingUsers] = await safeQuery<{ count: number }[]>(
    `SELECT COUNT(DISTINCT user_id)::int as count FROM credit_purchases WHERE status = 'completed'`,
    [{ count: 0 }]
  );

  const totalRevenue = totalRevenueRows?.total ?? 0;
  const thisMonth = thisMonthRows?.total ?? 0;
  const lastMonth = lastMonthRows?.total ?? 0;
  const percentChange = lastMonth > 0 ? ((thisMonth - lastMonth) / lastMonth * 100) : 0;
  const payingCount = payingUsers?.count ?? 0;
  const revenuePerUser = payingCount > 0 ? totalRevenue / payingCount : 0;

  const stats = [
    {
      label: "Total Revenue",
      value: `€${totalRevenue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
      icon: (
        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      ),
      color: "text-gold",
    },
    {
      label: "This Month",
      value: `€${thisMonth.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
      sub: percentChange !== 0 ? (
        <span className={percentChange > 0 ? "text-green-400" : "text-red-400"}>
          {percentChange > 0 ? "+" : ""}{percentChange.toFixed(1)}% vs last month
        </span>
      ) : null,
      icon: (
        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
        </svg>
      ),
      color: "text-green-400",
    },
    {
      label: "Last Month",
      value: `€${lastMonth.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
      icon: (
        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
        </svg>
      ),
      color: "text-blue-400",
    },
    {
      label: "Credits in Circulation",
      value: creditsCirculation?.total?.toLocaleString() ?? "0",
      icon: (
        <svg className="w-6 h-6 text-gold" viewBox="0 0 24 24" fill="currentColor">
          <circle cx="12" cy="12" r="10" opacity="0.2" />
          <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="1.5" fill="none" />
          <text x="12" y="16" textAnchor="middle" fontSize="11" fontWeight="bold" fill="currentColor">C</text>
        </svg>
      ),
      color: "text-gold",
    },
    {
      label: "Credits Used (Spent)",
      value: (creditsUsed?.total ?? 0).toLocaleString(),
      icon: (
        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
        </svg>
      ),
      color: "text-purple-400",
    },
    {
      label: "Paying Users",
      value: payingCount.toLocaleString(),
      icon: (
        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
      ),
      color: "text-cyan-400",
    },
    {
      label: "Revenue per User",
      value: `€${revenuePerUser.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
      icon: (
        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
        </svg>
      ),
      color: "text-amber-400",
    },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Platform Revenue</h1>
        <p className="text-text-muted mt-1">Financial overview and credit metrics.</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div
            key={stat.label}
            className="bg-surface rounded-xl border border-surface-light p-5 space-y-3"
          >
            <div className="flex items-center justify-between">
              <span className="text-text-muted text-sm">{stat.label}</span>
              <span className={stat.color}>{stat.icon}</span>
            </div>
            <p className="text-2xl font-bold text-white">{stat.value}</p>
            {stat.sub && <p className="text-sm">{stat.sub}</p>}
          </div>
        ))}
      </div>
    </div>
  );
}
