import prisma from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import Link from "next/link";

export default async function AdminTransactionsPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const page = Math.max(1, parseInt(String(params.page ?? "1")));
  const perPage = 25;
  const typeFilter = String(params.type ?? "");

  const where: Prisma.TransactionWhereInput = {
    ...(typeFilter ? { type: typeFilter as Prisma.EnumTransactionTypeFilter["equals"] } : {}),
  };

  const [transactions, total] = await Promise.all([
    prisma.transaction.findMany({
      where,
      orderBy: { created_at: "desc" },
      skip: (page - 1) * perPage,
      take: perPage,
      include: {
        user: { select: { id: true, id_aw: true, username: true } },
      },
    }),
    prisma.transaction.count({ where }),
  ]);

  const totalPages = Math.ceil(total / perPage);

  function buildUrl(overrides: Record<string, string>) {
    const p = new URLSearchParams();
    if (typeFilter) p.set("type", typeFilter);
    p.set("page", String(page));
    Object.entries(overrides).forEach(([k, v]) => p.set(k, v));
    return `/admin/transactions?${p.toString()}`;
  }

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

      {/* Filters */}
      <div className="bg-surface rounded-lg p-4">
        <form className="flex flex-wrap gap-4 items-end">
          <div>
            <label className="block text-text-muted text-sm mb-1">Type</label>
            <select
              name="type"
              defaultValue={typeFilter}
              className="bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <option value="">All</option>
              <option value="SUBSCRIPTION">Subscription</option>
              <option value="PURCHASE">Purchase</option>
              <option value="WITHDRAWAL">Withdrawal</option>
              <option value="TIP">Tip</option>
            </select>
          </div>
          <button
            type="submit"
            className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg transition-colors"
          >
            Filter
          </button>
        </form>
      </div>

      <p className="text-text-muted text-sm">
        Showing {(page - 1) * perPage + 1}-
        {Math.min(page * perPage, total)} of {total.toLocaleString()} transactions
      </p>

      {/* Table */}
      <div className="bg-surface rounded-lg overflow-hidden">
        <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="p-4 font-medium">ID</th>
                <th className="p-4 font-medium">User</th>
                <th className="p-4 font-medium">Type</th>
                <th className="p-4 font-medium">Amount</th>
                <th className="p-4 font-medium">Status</th>
                <th className="p-4 font-medium">Date</th>
              </tr>
            </thead>
            <tbody>
              {transactions.map((tx) => (
                <tr
                  key={tx.id}
                  className="border-b border-surface-light last:border-0 hover:bg-surface-light/50"
                >
                  <td className="p-4 text-text-muted font-mono text-sm">
                    {tx.id}
                  </td>
                  <td className="p-4">
                    {tx.user ? (
                      <Link
                        href={`/admin/users/${tx.user.id_aw}`}
                        className="font-medium hover:text-primary transition-colors"
                      >
                        {tx.user.username}
                      </Link>
                    ) : (
                      <span className="text-text-muted">-</span>
                    )}
                  </td>
                  <td className="p-4">
                    <span
                      className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                        tx.type === "SUBSCRIPTION"
                          ? "bg-purple-500/20 text-purple-400"
                          : tx.type === "PURCHASE"
                          ? "bg-blue-500/20 text-blue-400"
                          : tx.type === "WITHDRAWAL"
                          ? "bg-orange-500/20 text-orange-400"
                          : tx.type === "TIP"
                          ? "bg-green-500/20 text-green-400"
                          : "bg-surface-light text-text-muted"
                      }`}
                    >
                      {tx.type}
                    </span>
                  </td>
                  <td className="p-4 font-medium">{Number(tx.amount)} credits</td>
                  <td className="p-4">
                    <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-surface-light text-text-muted">
                      {tx.transaction_date ? "completed" : "pending"}
                    </span>
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {new Date(tx.created_at).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          {page > 1 && (
            <Link
              href={buildUrl({ page: String(page - 1) })}
              className="bg-surface hover:bg-surface-light text-text-muted px-3 py-1.5 rounded transition-colors text-sm"
            >
              Previous
            </Link>
          )}
          {Array.from({ length: Math.min(totalPages, 7) }, (_, i) => {
            let pageNum: number;
            if (totalPages <= 7) {
              pageNum = i + 1;
            } else if (page <= 4) {
              pageNum = i + 1;
            } else if (page >= totalPages - 3) {
              pageNum = totalPages - 6 + i;
            } else {
              pageNum = page - 3 + i;
            }
            return (
              <Link
                key={pageNum}
                href={buildUrl({ page: String(pageNum) })}
                className={`px-3 py-1.5 rounded text-sm transition-colors ${
                  pageNum === page
                    ? "bg-primary text-white"
                    : "bg-surface hover:bg-surface-light text-text-muted"
                }`}
              >
                {pageNum}
              </Link>
            );
          })}
          {page < totalPages && (
            <Link
              href={buildUrl({ page: String(page + 1) })}
              className="bg-surface hover:bg-surface-light text-text-muted px-3 py-1.5 rounded transition-colors text-sm"
            >
              Next
            </Link>
          )}
        </div>
      )}
    </div>
  );
}
