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

const TenantHomePage = () => {
  const { branding, companyName } = useTenant();
  const tenantHref = useTenantHref();

  const { data: courses = [] } = useQuery<any[]>({
    queryKey: ["tenant-home-courses", branding?.company_id],
    queryFn: async () => {
      try {
        // The endpoint resolves the tenant from the host; company_id is passed
        // as a belt-and-braces hint for dev/preview (?tenant=) usage.
        const qs = branding?.company_id ? `?company_id=${encodeURIComponent(branding.company_id)}` : "";
        const res = await fetch(`/api/marketplace/tenant-courses${qs}`);
        if (!res.ok) return [];
        const data = await res.json();
        return Array.isArray(data) ? data : [];
      } catch {
        return [];
      }
    },
  });

  return (
    <TenantLayout>
      <SeoHead />
      {/* Hero */}
      {branding?.hero_video_url ? (
        <section className="pt-16 relative">
          {branding.hero_video_url.includes("youtube.com") || branding.hero_video_url.includes("youtu.be") || branding.hero_video_url.includes("vimeo.com") ? (
            <iframe
              src={branding.hero_video_url}
              className="w-full object-cover h-[300px] sm:h-[450px] md:h-[550px] lg:h-[750px]"
              allow="autoplay; fullscreen"
              title={companyName || "Hero video"}
            />
          ) : (
            <video
              src={branding.hero_video_url}
              className="w-full object-cover h-[300px] sm:h-[450px] md:h-[550px] lg:h-[750px]"
              autoPlay
              muted
              loop
              playsInline
            />
          )}
          {companyName && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none">
              <h1 className="text-4xl md:text-6xl font-bold text-white drop-shadow-lg text-center px-4">{companyName}</h1>
            </div>
          )}
        </section>
      ) : branding?.hero_image_url ? (
        <section className="pt-16 relative">
          <img src={branding.hero_image_url} alt={companyName || ""} className="w-full object-cover h-[300px] sm:h-[450px] md:h-[550px] lg:h-[750px]" />
          {companyName && (
            <div className="absolute inset-0 flex items-center justify-center bg-black/30">
              <h1 className="text-4xl md:text-6xl font-bold text-white drop-shadow-lg text-center px-4">{companyName}</h1>
            </div>
          )}
        </section>
      ) : (
        <section className="pt-24 pb-16 bg-secondary/30">
          <div className="container mx-auto text-center py-24 md:py-32 px-4">
            <h1 className="text-4xl md:text-5xl font-bold text-foreground">
              {companyName || "Training Courses"}
            </h1>
            {branding?.tagline && (
              <p className="mt-4 text-lg text-muted-foreground max-w-2xl mx-auto">{branding.tagline}</p>
            )}
          </div>
        </section>
      )}

      {/* Courses grid */}
      <section className="container mx-auto px-4 pb-20 pt-12">
        <h2 className="text-2xl font-bold text-foreground mb-8">Our Courses</h2>
        {courses.length === 0 ? (
          <p className="text-muted-foreground">No courses available at the moment.</p>
        ) : (
          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
            {courses.map((course: any) => (
              <Link
                key={course.id}
                href={tenantHref(`/course/${course.slug}`)}
                className="bg-card border border-border rounded-xl overflow-hidden hover:border-primary/50 transition-colors 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>
                  <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>
    </TenantLayout>
  );
};

export default TenantHomePage;
