import { createFileRoute, Link } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { useEffect } from "react";
import { getStudentDashboard } from "@/lib/dashboard.functions";
import { DashboardLayout } from "@/components/DashboardLayout";
import { BookOpen, TrendingUp, PlayCircle } from "lucide-react";
import { trackEvent } from "@/lib/pixels";

const q = queryOptions({ queryKey: ["dashboard"], queryFn: () => getStudentDashboard() });

export const Route = createFileRoute("/_authenticated/dashboard")({
  loader: ({ context }) => context.queryClient.ensureQueryData(q),
  component: DashboardPage,
  errorComponent: ({ error }) => <div className="p-8 text-center text-destructive">{error.message}</div>,
});

function DashboardPage() {
  const { data } = useSuspenseQuery(q);
  const { profile, enrollments, progressByCourse, isAdmin } = data;

  // Fire Purchase event once per enrollment when the student first sees their approved access.
  useEffect(() => {
    if (typeof window === "undefined") return;
    for (const e of enrollments as any[]) {
      const key = `purchase_tracked_${e.course_id}`;
      if (!localStorage.getItem(key)) {
        const c = e.courses ?? {};
        const value = Number(c.discount_price ?? c.price ?? 0);
        trackEvent("Purchase", { content_name: c.title, value, currency: "BDT", content_type: "course" });
        localStorage.setItem(key, "1");
      }
    }
  }, [enrollments]);

  return (
    <DashboardLayout isAdmin={isAdmin}>
      <div className="mb-8">
        <h1 className="font-display text-3xl font-bold">Welcome back{profile?.full_name ? `, ${profile.full_name.split(" ")[0]}` : ""} 👋</h1>
        <p className="mt-1 text-muted-foreground">Pick up where you left off.</p>
      </div>

      {enrollments.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-border bg-card p-10 text-center">
          <BookOpen className="mx-auto h-10 w-10 text-muted-foreground" />
          <h2 className="mt-3 font-semibold">No active courses yet</h2>
          <p className="mt-1 text-sm text-muted-foreground">Enroll in Binary Options Mastery to start learning.</p>
          <Link to="/buy" className="mt-5 inline-block rounded-lg bg-gradient-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground shadow-glow">
            Enroll Now
          </Link>
        </div>
      ) : (
        <div className="grid gap-5 md:grid-cols-2">
          {enrollments.map((e: any) => {
            const c = e.courses;
            const p = progressByCourse[e.course_id] ?? { completed: 0, total: 0, lastLessonId: null };
            const pct = p.total > 0 ? Math.round((p.completed / p.total) * 100) : 0;
            return (
              <div key={e.id} className="overflow-hidden rounded-2xl border border-border bg-card shadow-card">
                {c.thumbnail_url && <img src={c.thumbnail_url} alt={c.title} className="aspect-video w-full object-cover" loading="lazy" />}
                <div className="p-5">
                  <h3 className="font-display text-lg font-semibold">{c.title}</h3>
                  <div className="mt-3 flex items-center justify-between text-xs text-muted-foreground">
                    <span className="inline-flex items-center gap-1"><TrendingUp className="h-3 w-3" /> {pct}% complete</span>
                    <span>{p.completed} / {p.total} lessons</span>
                  </div>
                  <div className="mt-2 h-2 overflow-hidden rounded-full bg-muted">
                    <div className="h-full bg-gradient-primary transition-all" style={{ width: `${pct}%` }} />
                  </div>
                  <Link to="/learn" className="mt-5 inline-flex w-full items-center justify-center gap-2 rounded-lg bg-gradient-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground shadow-glow">
                    <PlayCircle className="h-4 w-4" /> {p.completed > 0 ? "Continue Learning" : "Start Course"}
                  </Link>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </DashboardLayout>
  );
}
