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

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

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

  const sp = await searchParams;
  const justSucceeded = sp?.success === "true" || sp?.success === "1";

  const credit = await prisma.credit.findUnique({
    where: { user_id: Number(session.user.id) },
    select: { credits: true },
  });

  const transactions = await prisma.transaction.findMany({
    where: { user_id: Number(session.user.id) },
    orderBy: { created_at: "desc" },
    take: 50,
  });

  return (
    <div className="max-w-3xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-3xl font-bold text-text">Credits</h1>
        <Link
          href="/credits/buy"
          className="bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-lg font-semibold transition-colors"
        >
          Buy Credits
        </Link>
      </div>

      {justSucceeded && (
        <StripeSuccessBanner initialBalance={credit?.credits ?? 0} />
      )}

      <div className="bg-surface rounded-lg p-6 mb-6">
        <p className="text-text-muted text-sm">Current Balance</p>
        <p className="text-4xl font-bold text-primary">{credit?.credits ?? 0}</p>
        <p className="text-text-muted text-sm mt-1">credits</p>
      </div>

      {/* How Credits Work */}
      <div className="bg-surface rounded-lg p-6 mb-6">
        <h2 className="text-lg font-semibold text-text mb-3">How Credits Work</h2>
        <div className="text-sm text-text-muted space-y-2">
          <p>
            Credits are the universal currency on AdultWorld. One credit is approximately &euro;0.20, and they power everything you do on the platform &mdash;
            from messaging escorts to tipping, boosting profiles, and accessing premium pay-per-view content.
          </p>
          <p>
            <strong className="text-text">Buying credits:</strong> We offer six convenient packages ranging from 100 to 2,000 credits.
            Larger packages offer better value per credit. Head to the{" "}
            <Link href="/credits/buy" className="text-gold hover:underline">Buy Credits</Link> page to top up your balance.
          </p>
          <p>
            <strong className="text-text">Spending credits:</strong> Use credits to send messages and SMS chats, join LiveCam sessions, boost your profile visibility,
            tip your favourite escorts, and unlock premium PPV photos and videos.
          </p>
          <p>
            <strong className="text-text">Earning credits:</strong> Escorts and creators can earn credits through referrals, receiving tips from clients,
            and selling premium content. Credits earned can be converted back to cash via the payout system in your dashboard.
          </p>
        </div>
      </div>

      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold text-text mb-4">Transaction History</h2>

        {transactions.length === 0 ? (
          <p className="text-text-muted text-center py-4">No transactions yet.</p>
        ) : (
          <div className="space-y-2">
            {transactions.map((tx) => (
              <div key={tx.id} className="flex items-center justify-between py-3 border-b border-surface-light last:border-0">
                <div>
                  <p className="text-text text-sm">{tx.type}</p>
                  <p className="text-text-muted text-xs">
                    {tx.created_at?.toLocaleDateString(undefined, {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </p>
                </div>
                <span className={`font-semibold text-sm ${Number(tx.amount) > 0 ? "text-green-400" : "text-red-400"}`}>
                  {Number(tx.amount) > 0 ? "+" : ""}{Number(tx.amount)}
                </span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
