import { AdminAddUser } from "@/components/AdminAddUser";
import { db, unlockedCourses } from "@/lib/db";
import { courses } from "@/lib/courses";

export const metadata = { title: "Manage users" };

export default async function AdminUsersPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string }>;
}) {
  const { q = "" } = await searchParams;
  const rows = await db
    .prepare(
      `SELECT id, name, email, phone, role, status, created_at, trial_ends_at, has_access FROM users ORDER BY created_at DESC`
    )
    .all() as {
    id: string;
    name: string;
    email: string;
    phone: string | null;
    role: string;
    status: string;
    created_at: string;
    trial_ends_at: string;
    has_access: number;
  }[];
  const needle = q.trim().toLowerCase();
  const users = needle
    ? rows.filter(
        (u) =>
          u.name.toLowerCase().includes(needle) ||
          u.email.toLowerCase().includes(needle) ||
          (u.phone || "").includes(needle)
      )
    : rows;
  const ownedByUser = new Map<string, string[]>();
  await Promise.all(users.map(async (u) => ownedByUser.set(u.id, await unlockedCourses(u.id))));

  return (
    <div className="mx-auto max-w-6xl px-4 py-10">
      <h1 className="font-display text-4xl text-forest">Manage users</h1>
      <AdminAddUser />
      <form className="mt-6 flex gap-2">
        <input
          name="q"
          defaultValue={q}
          placeholder="Search name, email, phone"
          className="flex-1 rounded-full border border-forest/15 bg-white px-4 py-2 text-sm"
        />
        <button className="rounded-full bg-forest px-4 py-2 text-sm text-gold-2">Search</button>
      </form>
      <div className="mt-6 overflow-x-auto rounded-3xl border border-forest/10 bg-cream">
        <table className="w-full min-w-[720px] text-left text-sm">
          <thead className="border-b border-forest/10 text-xs uppercase tracking-widest text-forest/50">
            <tr>
              <th className="px-4 py-3">Learner</th>
              <th className="px-4 py-3">Trial</th>
              <th className="px-4 py-3">Courses</th>
              <th className="px-4 py-3">Role</th>
              <th className="px-4 py-3">Status</th>
            </tr>
          </thead>
          <tbody>
            {users.map((u) => {
              const owned = ownedByUser.get(u.id) || [];
              const trialOn = Boolean(u.has_access) && new Date(u.trial_ends_at).getTime() > Date.now();
              return (
                <tr key={u.id} className="border-t border-forest/5">
                  <td className="px-4 py-3">
                    <a href={`/admin/users/${u.id}`} className="font-medium text-forest hover:text-terra">
                      {u.name}
                    </a>
                    <p className="text-xs text-forest/60">
                      {u.email}
                      {u.phone ? ` · ${u.phone}` : ""}
                    </p>
                  </td>
                  <td className="px-4 py-3 text-xs">
                    {!u.has_access ? "Unpaid ₵50" : trialOn ? "3-day open" : "Ended"}
                    <br />
                    {new Date(u.trial_ends_at).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-3 text-xs">
                    {owned.length
                      ? owned.map((s) => courses.find((c) => c.slug === s)?.short || s).join(", ")
                      : "—"}
                  </td>
                  <td className="px-4 py-3">{u.role}</td>
                  <td className="px-4 py-3">{u.status}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
