import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import CommissionChart from "./CommissionChart";
import { MESSAGING_PLATFORM_FEE, LIVECAM_PLATFORM_FEE } from "@/lib/constants/fees";

interface TotalRow {
  total: number | null;
}

interface MonthlyRow {
  total: number | null;
}

interface TopEscortRow {
  user_id: number;
  username: string | null;
  total_received: number;
}

interface DailyRow {
  date: string;
  total: number;
}

export default async function AdminCommissionPage() {
  const session = await auth();
  if (!session?.user || (session.user as Record<string, unknown>)?.userType !== "admin") {
    redirect("/login");
  }

  // Total platform commission (livecam 30%, messaging 15%)
  let totalCommission = 0;
  let thisMonthRevenue = 0;
  let lastMonthRevenue = 0;
  let topEscorts: TopEscortRow[] = [];
  let dailyData: { date: string; commission: number; total: number }[] = [];

  try {
    // Total commission from all transactions (cam sessions + purchases)
    const totalRows: TotalRow[] = await prisma.$queryRawUnsafe(
      `SELECT COALESCE(SUM(ABS(amount)), 0) AS total
       FROM transactions
       WHERE type IN ('TIP', 'CAM_DEBIT', 'STORE_PURCHASE', 'SUBSCRIPTION')
       AND amount < 0`
    );
    const totalVolume = Number(totalRows[0]?.total || 0);
    totalCommission = Math.floor(totalVolume * LIVECAM_PLATFORM_FEE);

    // This month revenue
    const thisMonthRows: MonthlyRow[] = await prisma.$queryRawUnsafe(
      `SELECT COALESCE(SUM(ABS(amount)), 0) AS total
       FROM transactions
       WHERE type IN ('TIP', 'CAM_DEBIT', 'STORE_PURCHASE', 'SUBSCRIPTION')
       AND amount < 0
       AND transaction_date >= date_trunc('month', CURRENT_DATE)`
    );
    thisMonthRevenue = Math.floor(Number(thisMonthRows[0]?.total || 0) * LIVECAM_PLATFORM_FEE);

    // Last month revenue
    const lastMonthRows: MonthlyRow[] = await prisma.$queryRawUnsafe(
      `SELECT COALESCE(SUM(ABS(amount)), 0) AS total
       FROM transactions
       WHERE type IN ('TIP', 'CAM_DEBIT', 'STORE_PURCHASE', 'SUBSCRIPTION')
       AND amount < 0
       AND transaction_date >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
       AND transaction_date < date_trunc('month', CURRENT_DATE)`
    );
    lastMonthRevenue = Math.floor(Number(lastMonthRows[0]?.total || 0) * LIVECAM_PLATFORM_FEE);

    // Top 10 earning escorts (by credits received)
    topEscorts = await prisma.$queryRawUnsafe<TopEscortRow[]>(
      `SELECT t.receiver_id AS user_id, u.username,
              COALESCE(SUM(t.amount), 0) AS total_received
       FROM transactions t
       JOIN users u ON u.id = t.receiver_id
       WHERE t.amount > 0
       AND t.type IN ('TIP', 'CAM_DEBIT', 'STORE_SALE', 'SUBSCRIPTION')
       GROUP BY t.receiver_id, u.username
       ORDER BY total_received DESC
       LIMIT 10`
    );

    // Daily revenue for chart (last 30 days)
    const dailyRows: DailyRow[] = await prisma.$queryRawUnsafe(
      `SELECT DATE(transaction_date)::text AS date,
              COALESCE(SUM(ABS(amount)), 0) AS total
       FROM transactions
       WHERE type IN ('TIP', 'CAM_DEBIT', 'STORE_PURCHASE', 'SUBSCRIPTION')
       AND amount < 0
       AND transaction_date >= CURRENT_DATE - INTERVAL '30 days'
       GROUP BY DATE(transaction_date)
       ORDER BY date ASC`
    );

    dailyData = dailyRows.map((row) => ({
      date: row.date.slice(5), // MM-DD format
      total: Number(row.total),
      commission: Math.floor(Number(row.total) * LIVECAM_PLATFORM_FEE),
    }));
  } catch (error) {
    console.error("Commission dashboard error:", error);
  }

  const monthChange = lastMonthRevenue > 0
    ? ((thisMonthRevenue - lastMonthRevenue) / lastMonthRevenue * 100).toFixed(1)
    : "N/A";

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold text-white">Commission Dashboard</h1>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-surface rounded-lg p-6">
          <p className="text-text-muted text-sm">Total Platform Commission</p>
          <p className="text-3xl font-bold text-gold mt-1">
            {totalCommission.toLocaleString()}
          </p>
          <p className="text-text-muted text-xs mt-1">{LIVECAM_PLATFORM_FEE * 100}% of all credit volume</p>
        </div>
        <div className="bg-surface rounded-lg p-6">
          <p className="text-text-muted text-sm">Commission This Month</p>
          <p className="text-3xl font-bold text-gold mt-1">
            {thisMonthRevenue.toLocaleString()}
          </p>
          <p className={`text-xs mt-1 ${
            monthChange !== "N/A" && parseFloat(monthChange) >= 0
              ? "text-green-400"
              : "text-red-400"
          }`}>
            {monthChange !== "N/A" ? (
              <>
                {parseFloat(monthChange) >= 0 ? "+" : ""}
                {monthChange}% vs last month
              </>
            ) : (
              "No previous month data"
            )}
          </p>
        </div>
        <div className="bg-surface rounded-lg p-6">
          <p className="text-text-muted text-sm">Commission Last Month</p>
          <p className="text-3xl font-bold text-white mt-1">
            {lastMonthRevenue.toLocaleString()}
          </p>
          <p className="text-text-muted text-xs mt-1">credits earned</p>
        </div>
      </div>

      {/* Charts */}
      <CommissionChart data={dailyData} />

      {/* Top Escorts */}
      <div className="bg-surface rounded-lg overflow-hidden">
        <div className="p-4 border-b border-surface-light">
          <h2 className="text-lg font-semibold text-white">Top 10 Earning Escorts</h2>
        </div>
        <table className="w-full text-left">
          <thead>
            <tr className="border-b border-surface-light text-text-muted text-sm">
              <th className="p-4 font-medium">Rank</th>
              <th className="p-4 font-medium">Escort</th>
              <th className="p-4 font-medium text-right">Credits Received</th>
              <th className="p-4 font-medium text-right">Platform Commission ({LIVECAM_PLATFORM_FEE * 100}%)</th>
            </tr>
          </thead>
          <tbody>
            {topEscorts.length === 0 ? (
              <tr>
                <td colSpan={4} className="p-4 text-center text-text-muted">
                  No transaction data yet.
                </td>
              </tr>
            ) : (
              topEscorts.map((escort, i) => (
                <tr
                  key={escort.user_id}
                  className="border-b border-surface-light last:border-0 hover:bg-surface-light/50"
                >
                  <td className="p-4">
                    <span className={`inline-flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${
                      i === 0
                        ? "bg-gold/20 text-gold"
                        : i === 1
                        ? "bg-gray-300/20 text-gray-300"
                        : i === 2
                        ? "bg-orange-400/20 text-orange-400"
                        : "bg-surface-light text-text-muted"
                    }`}>
                      {i + 1}
                    </span>
                  </td>
                  <td className="p-4">
                    <a
                      href={`/admin/users/${escort.user_id}`}
                      className="text-white hover:text-gold transition-colors"
                    >
                      {escort.username || `User #${escort.user_id}`}
                    </a>
                  </td>
                  <td className="p-4 text-right text-white font-medium">
                    {Number(escort.total_received).toLocaleString()}
                  </td>
                  <td className="p-4 text-right text-gold font-medium">
                    {Math.floor(Number(escort.total_received) * LIVECAM_PLATFORM_FEE).toLocaleString()}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
