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

interface FeaturedPackage {
  id: number;
  name: string;
  type: string;
  price: number;
  duration_days: number;
  active: boolean;
  created_at: Date;
}

interface FeaturedPurchase {
  id: number;
  user_id: number;
  username: string | null;
  package_id: number;
  package_name: string | null;
  starts_at: Date;
  expires_at: Date;
  active: boolean;
}

export default async function AdminBoostsPage() {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  let packages: FeaturedPackage[] = [];
  let purchases: FeaturedPurchase[] = [];

  try {
    packages = await prisma.$queryRawUnsafe(
      `SELECT * FROM featured_packages ORDER BY created_at DESC`
    );
  } catch (e) {
    console.error("Failed to load featured packages:", e);
  }

  try {
    purchases = await prisma.$queryRawUnsafe(
      `SELECT fp.*, u.username, pkg.name as package_name
       FROM featured_purchases fp
       LEFT JOIN users u ON fp.user_id = u.id
       LEFT JOIN featured_packages pkg ON fp.package_id = pkg.id
       WHERE fp.active = true AND fp.expires_at > NOW()
       ORDER BY fp.expires_at ASC LIMIT 100`
    );
  } catch (e) {
    console.error("Failed to load featured purchases:", e);
  }

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

      {/* Packages Table */}
      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">Featured Packages</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">Name</th>
                <th className="pb-3 font-medium">Type</th>
                <th className="pb-3 font-medium">Price (Credits)</th>
                <th className="pb-3 font-medium">Duration</th>
                <th className="pb-3 font-medium">Active</th>
                <th className="pb-3 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {packages.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-4 text-center text-text-muted">
                    No packages configured.
                  </td>
                </tr>
              ) : (
                packages.map((pkg) => (
                  <tr
                    key={pkg.id}
                    className="border-b border-surface-light last:border-0"
                  >
                    <td className="py-3 font-medium">{pkg.name}</td>
                    <td className="py-3">
                      <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400">
                        {pkg.type}
                      </span>
                    </td>
                    <td className="py-3">{pkg.price}</td>
                    <td className="py-3 text-text-muted">
                      {pkg.duration_days}d
                    </td>
                    <td className="py-3">
                      {pkg.active ? (
                        <span className="text-green-400">Active</span>
                      ) : (
                        <span className="text-red-400">Inactive</span>
                      )}
                    </td>
                    <td className="py-3">
                      <BoostActions
                        packageId={pkg.id}
                        isActive={pkg.active}
                      />
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Active Purchases Table */}
      <div className="bg-surface rounded-lg p-6">
        <h2 className="text-lg font-semibold mb-4">Active Featured Purchases</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">User</th>
                <th className="pb-3 font-medium">Package</th>
                <th className="pb-3 font-medium">Starts</th>
                <th className="pb-3 font-medium">Expires</th>
                <th className="pb-3 font-medium">Active</th>
              </tr>
            </thead>
            <tbody>
              {purchases.length === 0 ? (
                <tr>
                  <td colSpan={5} className="py-4 text-center text-text-muted">
                    No active purchases.
                  </td>
                </tr>
              ) : (
                purchases.map((purchase) => (
                  <tr
                    key={purchase.id}
                    className="border-b border-surface-light last:border-0"
                  >
                    <td className="py-3">
                      <a
                        href={`/admin/users/${purchase.user_id}`}
                        className="text-primary hover:underline"
                      >
                        {purchase.username || `User #${purchase.user_id}`}
                      </a>
                    </td>
                    <td className="py-3">{purchase.package_name || "-"}</td>
                    <td className="py-3 text-text-muted text-sm">
                      {new Date(purchase.starts_at).toLocaleString()}
                    </td>
                    <td className="py-3 text-text-muted text-sm">
                      {new Date(purchase.expires_at).toLocaleString()}
                    </td>
                    <td className="py-3">
                      {purchase.active ? (
                        <span className="text-green-400">Active</span>
                      ) : (
                        <span className="text-red-400">Inactive</span>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
