import { createFileRoute } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery, useQueryClient } from "@tanstack/react-query";
import { useState, useMemo } from "react";
import { useServerFn } from "@tanstack/react-start";
import { listStudents, setStudentSuspension } from "@/lib/admin.functions";
import { toast } from "sonner";
import { Search } from "lucide-react";

const q = queryOptions({ queryKey: ["admin-students"], queryFn: () => listStudents() });

export const Route = createFileRoute("/_authenticated/admin/students")({
  loader: ({ context }) => context.queryClient.ensureQueryData(q),
  component: AdminStudents,
});

function AdminStudents() {
  const { data } = useSuspenseQuery(q);
  const qc = useQueryClient();
  const suspendFn = useServerFn(setStudentSuspension);
  const [search, setSearch] = useState("");

  const filtered = useMemo(() => {
    const s = search.trim().toLowerCase();
    if (!s) return data.students;
    return data.students.filter((p: any) =>
      (p.full_name ?? "").toLowerCase().includes(s) ||
      (p.email ?? "").toLowerCase().includes(s) ||
      (p.phone ?? "").toLowerCase().includes(s));
  }, [search, data.students]);

  const toggle = async (id: string, suspended: boolean) => {
    try {
      await suspendFn({ data: { userId: id, suspended } });
      toast.success(suspended ? "Access suspended" : "Access restored");
      qc.invalidateQueries({ queryKey: ["admin-students"] });
    } catch (e: any) { toast.error(e.message); }
  };

  return (
    <div>
      <h1 className="mb-6 font-display text-3xl font-bold">Students</h1>
      <div className="mb-4 flex items-center gap-2 rounded-lg border border-border bg-card px-3">
        <Search className="h-4 w-4 text-muted-foreground" />
        <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search by name, email, phone…"
          className="w-full bg-transparent py-2.5 text-sm outline-none" />
      </div>

      <div className="overflow-x-auto rounded-2xl border border-border bg-card">
        <table className="w-full text-sm">
          <thead className="bg-muted/40 text-xs uppercase tracking-wider text-muted-foreground">
            <tr><th className="px-4 py-3 text-left">Joined</th><th className="px-4 py-3 text-left">Name</th><th className="px-4 py-3 text-left">Email / Phone</th><th className="px-4 py-3 text-right">Enrolled</th><th className="px-4 py-3 text-left">Status</th><th className="px-4 py-3 text-right">Actions</th></tr>
          </thead>
          <tbody className="divide-y divide-border">
            {filtered.map((p: any) => (
              <tr key={p.id}>
                <td className="px-4 py-3 text-muted-foreground">{new Date(p.created_at).toLocaleDateString()}</td>
                <td className="px-4 py-3 font-medium">{p.full_name || "—"}</td>
                <td className="px-4 py-3">
                  <div className="text-xs">{p.email}</div>
                  <div className="text-xs text-muted-foreground">{p.phone}</div>
                </td>
                <td className="px-4 py-3 text-right">{p.enrolledCount}</td>
                <td className="px-4 py-3">
                  {p.suspended ? <span className="rounded-full bg-destructive/15 px-2 py-0.5 text-xs font-semibold text-destructive">Suspended</span> : <span className="rounded-full bg-success/15 px-2 py-0.5 text-xs font-semibold text-success">Active</span>}
                </td>
                <td className="px-4 py-3 text-right">
                  <button onClick={() => toggle(p.id, !p.suspended)} className="rounded-md border border-border bg-card px-3 py-1.5 text-xs font-semibold hover:bg-muted">
                    {p.suspended ? "Restore" : "Suspend"}
                  </button>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && <tr><td colSpan={6} className="px-4 py-10 text-center text-sm text-muted-foreground">No students found.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}
