import prisma from "@/lib/prisma";

export default async function AdminReferralsPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string }>;
}) {
  const params = await searchParams;
  const statusFilter = params.status || "all";

  let overallStats: {
    total: bigint;
    successful: bigint;
    pending: bigint;
    pending_purchase: bigint;
    total_credits: bigint;
    total_premium_months: bigint;
  }[] = [
    {
      total: BigInt(0),
      successful: BigInt(0),
      pending: BigInt(0),
      pending_purchase: BigInt(0),
      total_credits: BigInt(0),
      total_premium_months: BigInt(0),
    },
  ];
  let topReferrers: {
    referrer_id: number;
    username: string;
    referral_count: bigint;
    successful_count: bigint;
    credits_earned: bigint;
    premium_months: bigint;
  }[] = [];
  let recentReferrals: {
    id: number;
    referrer_username: string;
    referred_username: string | null;
    referred_user_type: string | null;
    code: string;
    status: string;
    reward_credits: number;
    premium_granted: boolean;
    credits_granted: boolean;
    created_at: Date;
  }[] = [];

  // Build status filter clause for recent referrals
  const statusClause =
    statusFilter !== "all"
      ? `AND r.status = '${statusFilter.replace(/[^a-z_]/g, "")}'`
      : "";

  try {
    const results = await Promise.all([
      prisma.$queryRawUnsafe<typeof overallStats>(
        `SELECT
           COUNT(*)::bigint as total,
           COUNT(CASE WHEN status = 'completed' THEN 1 END)::bigint as successful,
           COUNT(CASE WHEN status = 'pending' THEN 1 END)::bigint as pending,
           COUNT(CASE WHEN status = 'pending_purchase' THEN 1 END)::bigint as pending_purchase,
           COALESCE(SUM(CASE WHEN status = 'completed' THEN reward_credits ELSE 0 END), 0)::bigint as total_credits,
           (COUNT(CASE WHEN status = 'completed' THEN 1 END) * 3)::bigint as total_premium_months
         FROM referrals`
      ),
      prisma.$queryRawUnsafe<typeof topReferrers>(
        `SELECT r.referrer_id, u.username,
                COUNT(*)::bigint as referral_count,
                COUNT(CASE WHEN r.status = 'completed' THEN 1 END)::bigint as successful_count,
                COALESCE(SUM(CASE WHEN r.status = 'completed' THEN r.reward_credits ELSE 0 END), 0)::bigint as credits_earned,
                (COUNT(CASE WHEN r.status = 'completed' THEN 1 END) * 3)::bigint as premium_months
         FROM referrals r
         JOIN users u ON u.id = r.referrer_id
         GROUP BY r.referrer_id, u.username
         ORDER BY successful_count DESC
         LIMIT 20`
      ),
      prisma.$queryRawUnsafe<typeof recentReferrals>(
        `SELECT r.id, ru.username as referrer_username,
                rd.username as referred_username,
                rd.user_type as referred_user_type,
                r.code, r.status, r.reward_credits,
                (r.status = 'completed' AND r.reward_credits >= 5000) as premium_granted,
                (r.status = 'completed' AND r.reward_credits > 0) as credits_granted,
                r.created_at
         FROM referrals r
         JOIN users ru ON ru.id = r.referrer_id
         LEFT JOIN users rd ON rd.id = r.referred_id
         WHERE 1=1 ${statusClause}
         ORDER BY r.created_at DESC
         LIMIT 100`
      ),
    ]);
    overallStats = results[0];
    topReferrers = results[1];
    recentReferrals = results[2];
  } catch (e) {
    console.error("Failed to load referral data:", e);
  }

  const stats = overallStats[0];
  const total = Number(stats?.total ?? 0);
  const successful = Number(stats?.successful ?? 0);
  const pending = Number(stats?.pending ?? 0);
  const pendingPurchase = Number(stats?.pending_purchase ?? 0);
  const totalCredits = Number(stats?.total_credits ?? 0);
  const totalPremiumMonths = Number(stats?.total_premium_months ?? 0);
  const rate = total > 0 ? ((successful / total) * 100).toFixed(1) : "0";

  const statusColors: Record<string, string> = {
    completed: "bg-green-500/20 text-green-400",
    pending: "bg-yellow-500/20 text-yellow-400",
    pending_purchase: "bg-blue-500/20 text-blue-400",
    expired: "bg-gray-500/20 text-gray-400",
  };

  const statusFilters = [
    { value: "all", label: "All" },
    { value: "pending", label: "Pending" },
    { value: "pending_purchase", label: "Awaiting Purchase" },
    { value: "completed", label: "Completed" },
    { value: "expired", label: "Expired" },
  ];

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Referral Overview</h1>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-7 gap-4">
        <div className="bg-surface rounded-lg p-4">
          <p className="text-text-muted text-xs">Total Referrals</p>
          <p className="text-xl font-bold mt-1 text-blue-400">{total}</p>
        </div>
        <div className="bg-surface rounded-lg p-4">
          <p className="text-text-muted text-xs">Successful</p>
          <p className="text-xl font-bold mt-1 text-green-400">{successful}</p>
        </div>
        <div className="bg-surface rounded-lg p-4">
          <p className="text-text-muted text-xs">Pending</p>
          <p className="text-xl font-bold mt-1 text-yellow-400">{pending}</p>
        </div>
        <div className="bg-surface rounded-lg p-4">
          <p className="text-text-muted text-xs">Awaiting Purchase</p>
          <p className="text-xl font-bold mt-1 text-blue-400">{pendingPurchase}</p>
        </div>
        <div className="bg-surface rounded-lg p-4">
          <p className="text-text-muted text-xs">Success Rate</p>
          <p className="text-xl font-bold mt-1 text-primary">{rate}%</p>
        </div>
        <div className="bg-surface rounded-lg p-4">
          <p className="text-text-muted text-xs">Credits Distributed</p>
          <p className="text-xl font-bold mt-1 text-purple-400">
            {totalCredits.toLocaleString()}
          </p>
        </div>
        <div className="bg-surface rounded-lg p-4">
          <p className="text-text-muted text-xs">Premium Months Given</p>
          <p className="text-xl font-bold mt-1 text-gold">
            {totalPremiumMonths.toLocaleString()}
          </p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Top Referrers */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">Top Referrers</h2>
          <div className="overflow-x-auto">
            <table className="w-full text-left">
              <thead>
                <tr className="border-b border-surface-light text-text-muted text-sm">
                  <th className="pb-3 font-medium">#</th>
                  <th className="pb-3 font-medium">User</th>
                  <th className="pb-3 font-medium">Referrals</th>
                  <th className="pb-3 font-medium">Successful</th>
                  <th className="pb-3 font-medium">Credits</th>
                  <th className="pb-3 font-medium">Premium</th>
                </tr>
              </thead>
              <tbody>
                {topReferrers.map((ref, i) => (
                  <tr
                    key={ref.referrer_id}
                    className="border-b border-surface-light last:border-0"
                  >
                    <td className="py-3 text-text-muted">{i + 1}</td>
                    <td className="py-3 font-medium text-sm">
                      {ref.username}
                    </td>
                    <td className="py-3 text-text-muted text-sm">
                      {Number(ref.referral_count)}
                    </td>
                    <td className="py-3 text-green-400 text-sm">
                      {Number(ref.successful_count)}
                    </td>
                    <td className="py-3 text-primary text-sm">
                      {Number(ref.credits_earned).toLocaleString()}
                    </td>
                    <td className="py-3 text-gold text-sm">
                      {Number(ref.premium_months)}mo
                    </td>
                  </tr>
                ))}
                {topReferrers.length === 0 && (
                  <tr>
                    <td
                      colSpan={6}
                      className="py-8 text-center text-text-muted"
                    >
                      No referrers yet.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Recent Activity */}
        <div className="bg-surface rounded-lg p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold">Recent Activity</h2>
            {/* Status filter */}
            <div className="flex items-center gap-1 flex-wrap">
              {statusFilters.map((f) => (
                <a
                  key={f.value}
                  href={`/admin/referrals${f.value !== "all" ? `?status=${f.value}` : ""}`}
                  className={`px-2.5 py-1 rounded text-xs font-medium transition-colors ${
                    statusFilter === f.value
                      ? "bg-primary text-white"
                      : "bg-surface-light text-text-muted hover:text-white"
                  }`}
                >
                  {f.label}
                </a>
              ))}
            </div>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-left">
              <thead>
                <tr className="border-b border-surface-light text-text-muted text-sm">
                  <th className="pb-3 font-medium">Referrer</th>
                  <th className="pb-3 font-medium">Referred</th>
                  <th className="pb-3 font-medium">Type</th>
                  <th className="pb-3 font-medium">Status</th>
                  <th className="pb-3 font-medium">Premium</th>
                  <th className="pb-3 font-medium">Credits</th>
                  <th className="pb-3 font-medium">Date</th>
                </tr>
              </thead>
              <tbody>
                {recentReferrals.map((ref) => (
                  <tr
                    key={ref.id}
                    className="border-b border-surface-light last:border-0"
                  >
                    <td className="py-3 text-sm">{ref.referrer_username}</td>
                    <td className="py-3 text-sm">
                      {ref.referred_username ?? (
                        <span className="text-text-muted italic">Pending</span>
                      )}
                    </td>
                    <td className="py-3 text-sm text-text-muted">
                      {ref.referred_user_type === "escort" ? (
                        <span className="text-amber-400">Provider</span>
                      ) : ref.referred_user_type === "user" ? (
                        <span className="text-blue-400">Client</span>
                      ) : (
                        <span>-</span>
                      )}
                    </td>
                    <td className="py-3">
                      <span
                        className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                          statusColors[ref.status] ||
                          "bg-gray-500/20 text-gray-400"
                        }`}
                      >
                        {ref.status === "pending_purchase"
                          ? "Awaiting Buy"
                          : ref.status}
                      </span>
                    </td>
                    <td className="py-3 text-sm">
                      {ref.premium_granted ? (
                        <span className="text-gold font-medium">Yes</span>
                      ) : (
                        <span className="text-text-muted">-</span>
                      )}
                    </td>
                    <td className="py-3 text-sm">
                      {ref.credits_granted ? (
                        <span className="text-primary font-medium">
                          {ref.reward_credits.toLocaleString()}
                        </span>
                      ) : (
                        <span className="text-text-muted">-</span>
                      )}
                    </td>
                    <td className="py-3 text-text-muted text-sm">
                      {new Date(ref.created_at).toLocaleDateString()}
                    </td>
                  </tr>
                ))}
                {recentReferrals.length === 0 && (
                  <tr>
                    <td
                      colSpan={7}
                      className="py-8 text-center text-text-muted"
                    >
                      No referral activity
                      {statusFilter !== "all" ? ` with status "${statusFilter}"` : ""}.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
