import { createFileRoute, Link } from "@tanstack/react-router";
import { Header } from "@/components/Header";
import { Footer } from "@/components/Footer";
import { Check, Sparkles } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { formatPrice } from "@/lib/format";

export const Route = createFileRoute("/prestations")({
  head: () => ({
    meta: [
      { title: "Prestations — ORIS" },
      { name: "description", content: "Catalogue complet : sites web, applications mobiles, bots, automatisation, maintenance, templates." },
    ],
  }),
  component: Prestations,
});

function Prestations() {
  const { data, isLoading } = useQuery({
    queryKey: ["catalog"],
    queryFn: async () => {
      const [cats, svc] = await Promise.all([
        supabase.from("service_categories").select("*").order("sort_order"),
        supabase.from("services").select("*").eq("published", true).order("sort_order"),
      ]);
      if (cats.error) throw cats.error;
      if (svc.error) throw svc.error;
      return { categories: cats.data, services: svc.data };
    },
  });

  return (
    <>
      <Header />
      <main className="mx-auto max-w-7xl px-6 py-20">
        <div className="text-center max-w-3xl mx-auto">
          <span className="text-xs tracking-[0.2em] text-primary uppercase">Prestations</span>
          <h1 className="mt-3 font-display text-4xl md:text-6xl font-bold text-gradient">
            Catalogue complet
          </h1>
          <p className="mt-5 text-muted-foreground">
            Des solutions claires et transparentes. Chaque projet démarre par un échange gratuit pour cadrer vos besoins.
          </p>
        </div>

        {isLoading && <p className="text-center mt-16 text-muted-foreground">Chargement…</p>}

        {data?.categories.map((cat) => {
          const services = data.services.filter((s) => s.category_id === cat.id);
          if (!services.length) return null;
          return (
            <section key={cat.id} className="mt-20">
              <div className="flex items-end justify-between gap-6 mb-8 border-b border-border pb-4">
                <div>
                  <h2 className="font-display text-3xl font-bold">{cat.name}</h2>
                  {cat.description && <p className="text-sm text-muted-foreground mt-1">{cat.description}</p>}
                </div>
                <span className="text-xs text-muted-foreground">{services.length} prestation{services.length > 1 ? "s" : ""}</span>
              </div>
              <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                {services.map((s) => (
                  <article key={s.id} className={`relative rounded-2xl border p-7 backdrop-blur transition-colors ${s.featured ? "border-primary bg-card shadow-glow" : "border-border bg-card/40 hover:border-primary/40"}`}>
                    {s.featured && (
                      <span className="absolute -top-3 left-6 inline-flex items-center gap-1 rounded-full bg-gold text-background text-xs px-3 py-1 font-semibold">
                        <Sparkles className="size-3" /> Best-seller
                      </span>
                    )}
                    <h3 className="font-display text-xl font-bold">{s.name}</h3>
                    {s.tagline && <p className="text-xs text-primary mt-1">{s.tagline}</p>}
                    <div className="mt-4 flex items-baseline gap-1">
                      <span className="font-display text-3xl font-bold">{formatPrice(s.price_cents, s.price_suffix)}</span>
                    </div>
                    {s.description && <p className="mt-3 text-sm text-muted-foreground">{s.description}</p>}
                    {s.features.length > 0 && (
                      <ul className="mt-5 space-y-2">
                        {s.features.map((f: string) => (
                          <li key={f} className="flex items-start gap-2 text-sm">
                            <Check className="size-4 text-primary mt-0.5 shrink-0" />
                            <span>{f}</span>
                          </li>
                        ))}
                      </ul>
                    )}
                    {s.ideal_for.length > 0 && (
                      <div className="mt-5 pt-4 border-t border-border">
                        <div className="text-[10px] uppercase tracking-wider text-muted-foreground mb-2">Idéal pour</div>
                        <div className="flex flex-wrap gap-1.5">
                          {s.ideal_for.map((i: string) => (
                            <span key={i} className="text-xs px-2 py-0.5 rounded-full bg-secondary text-secondary-foreground">{i}</span>
                          ))}
                        </div>
                      </div>
                    )}
                    <Link to="/contact" className="mt-6 block text-center rounded-full bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground">
                      Demander un devis
                    </Link>
                  </article>
                ))}
              </div>
            </section>
          );
        })}
      </main>
      <Footer />
    </>
  );
}
