import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import SeoHead from "@/components/SeoHead";
import { Button } from "@/components/ui/button";
import { ArrowRight, Clock, Tag, Loader2 } from "lucide-react";
import { Link } from "@inertiajs/react";
import { useQuery } from "@tanstack/react-query";
import courseDumper from "@/assets/course-dumper.jpg";
import courseNrswa from "@/assets/course-nrswa.jpg";

const fallbackImages = [courseDumper, courseNrswa];

interface ELearningCourse {
  id: string;
  slug: string;
  title: string;
  description: string | null;
  image_url: string | null;
  duration_minutes: number | null;
  price_cents: number;
  videotile_course_id: number | null;
}

const ELearningPage = () => {
  // DB-backed catalog: pulls every active "E-Learning" course. The
  // marketplace endpoint scopes by category, so we filter VT-linked rows
  // client-side to avoid surfacing any half-imported courses without a
  // videotile_course_id (which couldn't be launched).
  const { data: courses, isLoading } = useQuery<ELearningCourse[]>({
    queryKey: ["public-elearning-courses"],
    queryFn: async () => {
      const res = await fetch("/api/marketplace/courses?category=E-Learning");
      if (!res.ok) return [];
      const list = await res.json();
      return Array.isArray(list)
        ? list.filter((c: ELearningCourse) => Boolean(c.videotile_course_id))
        : [];
    },
  });

  return (
    <div className="min-h-screen bg-background">
      <SeoHead />
      <Navbar />
      <div className="pt-24 pb-24">
        <div className="container mx-auto px-4 mb-12">
          <h1 className="text-4xl md:text-5xl font-bold text-foreground mb-3">E-Learning Courses</h1>
          <p className="text-muted-foreground max-w-2xl">
            Flexible online courses you can complete at your own pace. Ideal for health
            and safety compliance training with instant certification.
          </p>
        </div>

        <div className="container mx-auto px-4 mb-10">
          <div className="text-sm text-muted-foreground">
            {isLoading
              ? "Loading courses…"
              : `Showing ${courses?.length ?? 0} course${(courses?.length ?? 0) === 1 ? "" : "s"}`}
          </div>
        </div>

        <div className="container mx-auto px-4">
          {isLoading ? (
            <div className="flex justify-center py-16">
              <Loader2 className="w-6 h-6 animate-spin text-primary" />
            </div>
          ) : !courses || courses.length === 0 ? (
            <div className="text-center py-16 text-muted-foreground">
              No e-learning courses are available right now. Please check back soon.
            </div>
          ) : (
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {courses.map((course, idx) => {
                const image = course.image_url || fallbackImages[idx % fallbackImages.length];
                const duration = course.duration_minutes
                  ? `${course.duration_minutes} min`
                  : "—";
                const price = `£${(course.price_cents / 100).toFixed(2)}`;
                return (
                  <div
                    key={course.id}
                    className="bg-card rounded-xl overflow-hidden border border-border hover:border-primary/30 transition-all group"
                  >
                    <div className="relative h-44 overflow-hidden">
                      <img
                        src={image}
                        alt={`${course.title} online e-learning course`}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                      />
                      <div className="absolute top-3 left-3">
                        <span className="bg-primary/90 text-primary-foreground text-xs font-medium px-3 py-1 rounded-full">
                          E-Learning
                        </span>
                      </div>
                    </div>
                    <div className="p-5">
                      <h2 className="text-base font-bold text-foreground mb-2 line-clamp-2">{course.title}</h2>
                      <p className="text-sm text-muted-foreground mb-4 line-clamp-2">
                        {course.description || ""}
                      </p>
                      <div className="flex items-center gap-4 mb-4 text-sm text-muted-foreground">
                        <span className="flex items-center gap-1">
                          <Clock className="w-3.5 h-3.5" /> {duration}
                        </span>
                        <span className="flex items-center gap-1">
                          <Tag className="w-3.5 h-3.5" /> {price}
                        </span>
                      </div>
                      <Link href={`/course/${course.slug}`}>
                        <Button variant="outline" size="sm" className="w-full">
                          View Details <ArrowRight className="w-4 h-4 ml-1" />
                        </Button>
                      </Link>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default ELearningPage;
