import prisma from "@/lib/prisma";
import RegistrationChart from "./RegistrationChart";

export default async function AdminDashboardPage() {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
  thirtyDaysAgo.setHours(0, 0, 0, 0);

  const [
    totalUsers,
    activeEscorts,
    newToday,
    pendingModeration,
    openTickets,
    totalCreditsSold,
    revenueToday,
    totalBlogViews,
    recentUsers,
    recentTickets,
    registrationRaw,
  ] = await Promise.all([
    prisma.user.count(),
    prisma.user.count({ where: { user_type: "escort", active: true } }),
    prisma.user.count({ where: { created_at: { gte: today } } }),
    prisma.photo.count({ where: { moderation_status: "pending" } }),
    prisma.ticket.count({ where: { status: "open" } }),
    prisma.credit.aggregate({ _sum: { credits: true } }),
    prisma.transaction.aggregate({
      _sum: { amount: true },
      where: { created_at: { gte: today } },
    }),
    prisma.blogPost.aggregate({ _sum: { views: true } }),
    prisma.user.findMany({
      orderBy: { created_at: "desc" },
      take: 10,
      select: {
        id: true,
        id_aw: true,
        username: true,
        email: true,
        user_type: true,
        created_at: true,
      },
    }),
    prisma.ticket.findMany({
      orderBy: { created_at: "desc" },
      take: 10,
      select: {
        id: true,
        subject: true,
        category: true,
        status: true,
        priority: true,
        created_at: true,
      },
    }),
    prisma.$queryRaw<{ day: Date; count: bigint }[]>`
      SELECT DATE(created_at) as day, COUNT(*)::bigint as count
      FROM users
      WHERE created_at >= ${thirtyDaysAgo}
      GROUP BY DATE(created_at)
      ORDER BY day ASC
    `,
  ]);

  // Build chart data for last 30 days (fill missing days with 0)
  const chartMap = new Map<string, number>();
  for (const row of registrationRaw) {
    const d = new Date(row.day).toISOString().slice(0, 10);
    chartMap.set(d, Number(row.count));
  }
  const chartData: { date: string; count: number }[] = [];
  for (let i = 29; i >= 0; i--) {
    const d = new Date();
    d.setDate(d.getDate() - i);
    const key = d.toISOString().slice(0, 10);
    chartData.push({ date: key.slice(5), count: chartMap.get(key) ?? 0 });
  }

  const stats = [
    { label: "Total Users", value: totalUsers.toLocaleString(), color: "text-blue-400" },
    { label: "Active Escorts", value: activeEscorts.toLocaleString(), color: "text-pink-400" },
    { label: "New Today", value: newToday.toLocaleString(), color: "text-green-400" },
    { label: "Pending Moderation", value: pendingModeration.toLocaleString(), color: "text-yellow-400" },
    { label: "Open Tickets", value: openTickets.toLocaleString(), color: "text-orange-400" },
    { label: "Total Credits Sold", value: (totalCreditsSold._sum.credits ?? 0).toLocaleString(), color: "text-purple-400" },
    { label: "Revenue Today", value: `$${Number(revenueToday._sum.amount ?? 0).toFixed(2)}`, color: "text-emerald-400" },
    { label: "Total Blog Views", value: (totalBlogViews._sum.views ?? 0).toLocaleString(), color: "text-cyan-400" },
  ];

  const priorityColors: Record<string, string> = {
    low: "bg-blue-500/20 text-blue-400",
    normal: "bg-green-500/20 text-green-400",
    high: "bg-orange-500/20 text-orange-400",
    urgent: "bg-red-500/20 text-red-400",
  };

  const statusColors: Record<string, string> = {
    open: "bg-yellow-500/20 text-yellow-400",
    in_progress: "bg-blue-500/20 text-blue-400",
    resolved: "bg-green-500/20 text-green-400",
    closed: "bg-gray-500/20 text-gray-400",
  };

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

      {/* Row 1: Stat Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-surface rounded-lg p-4">
            <p className="text-text-muted text-xs">{stat.label}</p>
            <p className={`text-xl font-bold mt-1 ${stat.color}`}>
              {stat.value}
            </p>
          </div>
        ))}
      </div>

      {/* Row 2: Registration Trend Chart */}
      <RegistrationChart data={chartData} />

      {/* Row 3: Recent Registrations + Recent Tickets */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Registrations */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">Recent Registrations</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">ID</th>
                  <th className="pb-3 font-medium">Username</th>
                  <th className="pb-3 font-medium">Email</th>
                  <th className="pb-3 font-medium">Type</th>
                  <th className="pb-3 font-medium">Registered</th>
                </tr>
              </thead>
              <tbody>
                {recentUsers.map((user) => (
                  <tr
                    key={user.id}
                    className="border-b border-surface-light last:border-0"
                  >
                    <td className="py-3 text-text-muted">{user.id_aw}</td>
                    <td className="py-3 font-medium">{user.username}</td>
                    <td className="py-3 text-text-muted text-sm">{user.email}</td>
                    <td className="py-3">
                      <span
                        className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                          user.user_type === "escort"
                            ? "bg-pink-500/20 text-pink-400"
                            : user.user_type === "admin"
                            ? "bg-red-500/20 text-red-400"
                            : "bg-blue-500/20 text-blue-400"
                        }`}
                      >
                        {user.user_type}
                      </span>
                    </td>
                    <td className="py-3 text-text-muted text-sm">
                      {new Date(user.created_at).toLocaleString()}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Recent Tickets */}
        <div className="bg-surface rounded-lg p-6">
          <h2 className="text-lg font-semibold mb-4">Recent Tickets</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">#</th>
                  <th className="pb-3 font-medium">Subject</th>
                  <th className="pb-3 font-medium">Status</th>
                  <th className="pb-3 font-medium">Priority</th>
                  <th className="pb-3 font-medium">Date</th>
                </tr>
              </thead>
              <tbody>
                {recentTickets.map((ticket) => (
                  <tr
                    key={ticket.id}
                    className="border-b border-surface-light last:border-0"
                  >
                    <td className="py-3 text-text-muted">{ticket.id}</td>
                    <td className="py-3 font-medium text-sm">{ticket.subject}</td>
                    <td className="py-3">
                      <span
                        className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                          statusColors[ticket.status] ?? "bg-gray-500/20 text-gray-400"
                        }`}
                      >
                        {ticket.status}
                      </span>
                    </td>
                    <td className="py-3">
                      <span
                        className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                          priorityColors[ticket.priority] ?? "bg-gray-500/20 text-gray-400"
                        }`}
                      >
                        {ticket.priority}
                      </span>
                    </td>
                    <td className="py-3 text-text-muted text-sm">
                      {new Date(ticket.created_at).toLocaleString()}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
