import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import { PayoutActions } from "./PayoutActions";

interface PayoutRow {
  id: number;
  user_id: number;
  username: string | null;
  amount: number;
  method: string;
  status: string;
  admin_notes: string | null;
  created_at: Date;
  processed_at: Date | null;
}

interface StatRow {
  count: bigint;
  total: number | null;
}

export default async function AdminPayoutsPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string }>;
}) {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  const { status: filterStatus } = await searchParams;

  let pendingStats: StatRow[] = [{ count: BigInt(0), total: 0 }];
  let processedStats: StatRow[] = [{ count: BigInt(0), total: 0 }];
  let payouts: PayoutRow[] = [];

  try {
    pendingStats = await prisma.$queryRawUnsafe(
      `SELECT COUNT(*)::bigint as count, COALESCE(SUM(amount), 0) as total FROM payout_requests WHERE status = 'pending'`
    );
  } catch (e) {
    console.error("Failed to load pending payout stats:", e);
  }

  try {
    processedStats = await prisma.$queryRawUnsafe(
      `SELECT COUNT(*)::bigint as count, COALESCE(SUM(amount), 0) as total FROM payout_requests WHERE status = 'completed' AND processed_at >= date_trunc('month', CURRENT_DATE)`
    );
  } catch (e) {
    console.error("Failed to load processed payout stats:", e);
  }

  try {
    let query = `SELECT pr.*, u.username FROM payout_requests pr LEFT JOIN users u ON pr.user_id = u.id`;
    const params: string[] = [];

    if (filterStatus && filterStatus !== "all") {
      query += ` WHERE pr.status = $1`;
      params.push(filterStatus);
    }

    query += ` ORDER BY pr.created_at DESC LIMIT 200`;

    payouts = params.length
      ? await prisma.$queryRawUnsafe(query, ...params)
      : await prisma.$queryRawUnsafe(query);
  } catch (e) {
    console.error("Failed to load payouts:", e);
  }

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

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

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="bg-surface rounded-lg p-6">
          <p className="text-text-muted text-sm">Pending Payouts</p>
          <p className="text-2xl font-bold mt-1">
            {Number(pendingStats[0]?.count ?? 0)}
          </p>
          <p className="text-yellow-400 text-sm mt-1">
            Total: ${Number(pendingStats[0]?.total ?? 0).toFixed(2)}
          </p>
        </div>
        <div className="bg-surface rounded-lg p-6">
          <p className="text-text-muted text-sm">Processed This Month</p>
          <p className="text-2xl font-bold mt-1">
            {Number(processedStats[0]?.count ?? 0)}
          </p>
          <p className="text-green-400 text-sm mt-1">
            Total: ${Number(processedStats[0]?.total ?? 0).toFixed(2)}
          </p>
        </div>
      </div>

      {/* Filter */}
      <div className="flex gap-2">
        {["all", "pending", "processing", "completed", "rejected"].map((s) => (
          <a
            key={s}
            href={`/admin/payouts?status=${s}`}
            className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
              (filterStatus || "all") === s
                ? "bg-primary text-white"
                : "bg-surface-light text-text-muted hover:text-white"
            }`}
          >
            {s.charAt(0).toUpperCase() + s.slice(1)}
          </a>
        ))}
      </div>

      {/* Table */}
      <div className="bg-surface rounded-lg overflow-x-auto">
        <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">ID</th>
              <th className="p-4 font-medium">User</th>
              <th className="p-4 font-medium">Amount</th>
              <th className="p-4 font-medium">Method</th>
              <th className="p-4 font-medium">Status</th>
              <th className="p-4 font-medium">Date</th>
              <th className="p-4 font-medium">Notes</th>
              <th className="p-4 font-medium">Actions</th>
            </tr>
          </thead>
          <tbody>
            {payouts.length === 0 ? (
              <tr>
                <td colSpan={8} className="p-4 text-center text-text-muted">
                  No payout requests found.
                </td>
              </tr>
            ) : (
              payouts.map((payout) => (
                <tr
                  key={payout.id}
                  className="border-b border-surface-light last:border-0"
                >
                  <td className="p-4 text-text-muted">#{payout.id}</td>
                  <td className="p-4">
                    <a
                      href={`/admin/users/${payout.user_id}`}
                      className="text-primary hover:underline"
                    >
                      {payout.username || `User #${payout.user_id}`}
                    </a>
                  </td>
                  <td className="p-4 font-medium">
                    ${Number(payout.amount).toFixed(2)}
                  </td>
                  <td className="p-4 text-text-muted">{payout.method}</td>
                  <td className="p-4">
                    <span
                      className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                        statusColors[payout.status] || "bg-surface-light"
                      }`}
                    >
                      {payout.status}
                    </span>
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {new Date(payout.created_at).toLocaleDateString()}
                  </td>
                  <td className="p-4 text-text-muted text-sm max-w-[200px] truncate">
                    {payout.admin_notes || "-"}
                  </td>
                  <td className="p-4">
                    <PayoutActions
                      payoutId={payout.id}
                      currentStatus={payout.status}
                    />
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
