import { Link } from "@inertiajs/react";
import { useQuery } from "@tanstack/react-query";
import { useTenant } from "@/contexts/TenantContext";
import { useTenantHref } from "@/hooks/useTenantLink";
import { Badge } from "@/components/ui/badge";

interface Course {
  id: string;
  title: string;
  slug: string;
  description: string | null;
  price_cents: number;
  days: number;
  image_url: string | null;
  category: string;
}

const LocktelFeaturedCourses = ({ featuredOnly = false }: { featuredOnly?: boolean }) => {
  const { branding } = useTenant();
  const tenantHref = useTenantHref();

  const { data: courses = [] } = useQuery<Course[]>({
    queryKey: ["locktel-courses", branding?.company_id, featuredOnly],
    queryFn: async () => {
      if (!branding) return [];
      const params = new URLSearchParams({ company_id: branding.company_id });
      if (featuredOnly) params.set("featured_only", "1");
      try {
        const res = await fetch(`/api/locktel/courses?${params.toString()}`);
        if (!res.ok) return [];
        const data = await res.json();
        return Array.isArray(data) ? data : [];
      } catch {
        return [];
      }
    },
    enabled: !!branding,
  });

  if (courses.length === 0) return null;

  return (
    <section className="container mx-auto px-4 py-16">
      <h2 className="text-3xl font-bold text-foreground mb-2 text-center">
        {featuredOnly ? "Featured Courses" : "Our Courses"}
      </h2>
      <p className="text-muted-foreground text-center mb-10">
        Industry-accredited training delivered by experienced professionals
      </p>
      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
        {courses.map(course => (
          <Link
            key={course.id}
            href={tenantHref(`/course/${course.slug}`)}
            className="bg-card border border-border rounded-xl overflow-hidden hover:border-primary/50 transition-all hover:shadow-lg group"
          >
            {course.image_url && (
              <img src={course.image_url} alt={course.title} className="w-full h-48 object-cover" />
            )}
            <div className="p-5">
              <Badge variant="secondary" className="mb-2 text-xs">{course.category}</Badge>
              <h3 className="font-semibold text-card-foreground group-hover:text-primary transition-colors mb-2">
                {course.title}
              </h3>
              {course.description && (
                <p className="text-sm text-card-foreground/70 mb-3 line-clamp-2">{course.description}</p>
              )}
              <div className="flex items-center justify-between text-sm text-card-foreground/70">
                <span>{course.days} day{course.days !== 1 ? "s" : ""}</span>
                <span className="font-semibold text-primary">£{(course.price_cents / 100).toFixed(2)}</span>
              </div>
            </div>
          </Link>
        ))}
      </div>
    </section>
  );
};

export default LocktelFeaturedCourses;
