import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import prisma from "@/lib/prisma";
import Link from "next/link";
import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "Credit History | AdultWorld",
  description: "View your AW credit transaction history, balance, and spending details.",
  robots: { index: false, follow: false },
};

type Props = {
  searchParams: Promise<{ type?: string; page?: string }>;
};

const TYPE_BADGE: Record<string, { label: string; className: string }> = {
  PURCHASE: { label: "Purchase", className: "bg-blue-500/15 text-blue-400 border-blue-500/30" },
  SUBSCRIPTION: { label: "Subscription", className: "bg-purple-500/15 text-purple-400 border-purple-500/30" },
  TIP: { label: "Tip", className: "bg-pink-500/15 text-pink-400 border-pink-500/30" },
  WITHDRAWAL: { label: "Withdrawal", className: "bg-orange-500/15 text-orange-400 border-orange-500/30" },
};

const FILTER_TABS = [
  { value: "all", label: "All" },
  { value: "PURCHASE", label: "Purchases" },
  { value: "SUBSCRIPTION", label: "Subscriptions" },
  { value: "TIP", label: "Tips" },
  { value: "WITHDRAWAL", label: "Withdrawals" },
];

export default async function CreditHistoryPage({ searchParams }: Props) {
  const session = await auth();
  if (!session?.user?.id) redirect("/login?callbackUrl=/credits/history");

  const { type, page } = await searchParams;
  const currentPage = Math.max(1, parseInt(page || "1", 10));
  const perPage = 20;
  const userId = parseInt(session.user.id);

  // Fetch credit balance
  const credit = await prisma.credit.findUnique({
    where: { user_id: userId },
  });
  const balance = credit?.credits ?? 0;

  // Build transaction query
  const where: Record<string, unknown> = { user_id: userId };
  if (type && type !== "all") {
    where.type = type;
  }

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

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

  // Build running balance (approximate - starts from current and works backward)
  // For a proper running balance we compute from the current balance
  let runningBalance = balance;
  // Adjust for transactions on pages before this one
  if (currentPage > 1) {
    const priorTransactions = await prisma.transaction.findMany({
      where,
      orderBy: { created_at: "desc" },
      take: (currentPage - 1) * perPage,
      select: { amount: true, type: true, user_id: true, receiver_id: true },
    });
    for (const t of priorTransactions) {
      const amt = Number(t.amount);
      // C.12: use the sign of `amount` directly. Earlier this branched on
      // (PURCHASE && receiver_id IS NULL) only, treating every other inbound
      // credit (received tips, paid messages, subscription earnings) as a
      // spend — backward pass added them when it should subtract, so the
      // displayed running balance was wrong for escorts who receive money.
      if (amt > 0) {
        // Credit IN (top-up, tip received, paid-message earnings) — go back
        // by subtracting the amount that was added.
        runningBalance -= amt;
      } else {
        // Credit OUT (debits stored as negative numbers) — go back by adding
        // back the absolute amount that was subtracted.
        runningBalance += Math.abs(amt);
      }
    }
  }

  function getDescription(t: typeof transactions[number]): string {
    if (t.transactionable_type) {
      const typeLabel = t.transactionable_type.replace(/App\\Models\\/, "").replace(/([A-Z])/g, " $1").trim();
      return `${typeLabel} #${t.transactionable_id}`;
    }
    if (t.type === "TIP" && t.receiver) return `Tip to ${t.receiver.username}`;
    if (t.type === "PURCHASE") return "Credit Purchase";
    if (t.type === "SUBSCRIPTION") return "Subscription Payment";
    if (t.type === "WITHDRAWAL") return "Withdrawal";
    return t.type;
  }

  return (
    <div className="max-w-5xl mx-auto px-4 py-8">
      {/* Balance Header */}
      <div className="bg-surface rounded-2xl border border-surface-light p-8 mb-8">
        <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
          <div className="text-center sm:text-left">
            <p className="text-text-muted text-sm font-medium mb-1">Current Balance</p>
            <div className="flex items-baseline gap-2">
              <span className="text-5xl font-extrabold text-gold">{balance.toLocaleString()}</span>
              <span className="text-text-muted text-lg">AW Credits</span>
            </div>
          </div>
          <Link
            href="/credits/buy"
            className="bg-gradient-to-r from-gold to-gold-light text-black font-semibold px-8 py-3 rounded-xl transition-all duration-300 hover:shadow-[0_0_20px_rgba(212,175,55,0.3)] text-sm"
          >
            Buy Credits
          </Link>
        </div>
      </div>

      {/* Filter Tabs */}
      <div className="flex flex-wrap gap-2 mb-6">
        {FILTER_TABS.map((tab) => {
          const isActive = (!type && tab.value === "all") || type === tab.value;
          return (
            <Link
              key={tab.value}
              href={`/credits/history${tab.value !== "all" ? `?type=${tab.value}` : ""}`}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                isActive
                  ? "bg-gold text-black"
                  : "bg-surface-light text-text-muted hover:text-white hover:bg-surface-light/80"
              }`}
            >
              {tab.label}
            </Link>
          );
        })}
      </div>

      {/* Transaction Table */}
      {transactions.length === 0 ? (
        <div className="bg-surface rounded-2xl border border-surface-light p-12 text-center">
          <div className="text-text-muted text-lg mb-2">No transactions found</div>
          <p className="text-text-muted text-sm">
            {type && type !== "all"
              ? "No transactions match this filter."
              : "Your credit history will appear here after your first transaction."}
          </p>
        </div>
      ) : (
        <div className="bg-surface rounded-2xl border border-surface-light overflow-hidden">
          {/* Desktop Table */}
          <div className="hidden md:block overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-surface-light">
                  <th className="text-left text-xs font-medium text-text-muted uppercase tracking-wider px-6 py-4">Date</th>
                  <th className="text-left text-xs font-medium text-text-muted uppercase tracking-wider px-6 py-4">Type</th>
                  <th className="text-left text-xs font-medium text-text-muted uppercase tracking-wider px-6 py-4">Description</th>
                  <th className="text-right text-xs font-medium text-text-muted uppercase tracking-wider px-6 py-4">Amount</th>
                  <th className="text-right text-xs font-medium text-text-muted uppercase tracking-wider px-6 py-4">Balance</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-surface-light">
                {transactions.map((t, i) => {
                  const amt = Number(t.amount);
                  const isIncoming = t.type === "PURCHASE" && t.receiver_id === null;
                  const badge = TYPE_BADGE[t.type] || { label: t.type, className: "bg-surface-light text-text-muted border-surface-light" };

                  // Compute this row's running balance
                  let rowBalance = runningBalance;
                  for (let j = 0; j < i; j++) {
                    const prev = transactions[j];
                    const prevAmt = Number(prev.amount);
                    if (prev.type === "PURCHASE" && prev.receiver_id === null) {
                      rowBalance -= prevAmt;
                    } else {
                      rowBalance += prevAmt;
                    }
                  }

                  return (
                    <tr key={t.id} className="hover:bg-surface-light/30 transition-colors">
                      <td className="px-6 py-4 text-sm text-text-muted whitespace-nowrap">
                        {new Date(t.created_at).toLocaleDateString(undefined, {
                          day: "2-digit",
                          month: "short",
                          year: "numeric",
                        })}
                      </td>
                      <td className="px-6 py-4">
                        <span className={`inline-block text-xs font-medium px-2.5 py-1 rounded-full border ${badge.className}`}>
                          {badge.label}
                        </span>
                      </td>
                      <td className="px-6 py-4 text-sm text-white">
                        {getDescription(t)}
                      </td>
                      <td className={`px-6 py-4 text-sm font-semibold text-right whitespace-nowrap ${isIncoming ? "text-green-400" : "text-red-400"}`}>
                        {isIncoming ? "+" : "-"}{amt.toLocaleString()} credits
                      </td>
                      <td className="px-6 py-4 text-sm text-gold font-medium text-right whitespace-nowrap">
                        {rowBalance.toLocaleString()}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Mobile Cards */}
          <div className="md:hidden divide-y divide-surface-light">
            {transactions.map((t, i) => {
              const amt = Number(t.amount);
              const isIncoming = t.type === "PURCHASE" && t.receiver_id === null;
              const badge = TYPE_BADGE[t.type] || { label: t.type, className: "bg-surface-light text-text-muted border-surface-light" };

              let rowBalance = runningBalance;
              for (let j = 0; j < i; j++) {
                const prev = transactions[j];
                const prevAmt = Number(prev.amount);
                if (prev.type === "PURCHASE" && prev.receiver_id === null) {
                  rowBalance -= prevAmt;
                } else {
                  rowBalance += prevAmt;
                }
              }

              return (
                <div key={t.id} className="p-4 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className={`text-xs font-medium px-2.5 py-1 rounded-full border ${badge.className}`}>
                      {badge.label}
                    </span>
                    <span className="text-xs text-text-muted">
                      {new Date(t.created_at).toLocaleDateString(undefined, {
                        day: "2-digit",
                        month: "short",
                        year: "numeric",
                      })}
                    </span>
                  </div>
                  <p className="text-sm text-white">{getDescription(t)}</p>
                  <div className="flex items-center justify-between">
                    <span className={`text-sm font-semibold ${isIncoming ? "text-green-400" : "text-red-400"}`}>
                      {isIncoming ? "+" : "-"}{amt.toLocaleString()} credits
                    </span>
                    <span className="text-sm text-gold font-medium">
                      Bal: {rowBalance.toLocaleString()}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2 mt-8">
          {currentPage > 1 && (
            <Link
              href={`/credits/history?${type && type !== "all" ? `type=${type}&` : ""}page=${currentPage - 1}`}
              className="px-4 py-2 rounded-lg bg-surface-light text-text-muted hover:text-white 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 (currentPage <= 4) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 3) {
              pageNum = totalPages - 6 + i;
            } else {
              pageNum = currentPage - 3 + i;
            }
            return (
              <Link
                key={pageNum}
                href={`/credits/history?${type && type !== "all" ? `type=${type}&` : ""}page=${pageNum}`}
                className={`w-10 h-10 flex items-center justify-center rounded-lg text-sm font-medium transition-colors ${
                  pageNum === currentPage
                    ? "bg-gold text-black"
                    : "bg-surface-light text-text-muted hover:text-white"
                }`}
              >
                {pageNum}
              </Link>
            );
          })}
          {currentPage < totalPages && (
            <Link
              href={`/credits/history?${type && type !== "all" ? `type=${type}&` : ""}page=${currentPage + 1}`}
              className="px-4 py-2 rounded-lg bg-surface-light text-text-muted hover:text-white transition-colors text-sm"
            >
              Next
            </Link>
          )}
        </div>
      )}

      {/* Total count */}
      <p className="text-center text-xs text-text-muted mt-4">
        Showing {Math.min((currentPage - 1) * perPage + 1, totalCount)}-{Math.min(currentPage * perPage, totalCount)} of {totalCount} transactions
      </p>
    </div>
  );
}
