import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { Star } from "lucide-react";
import { AppShell } from "@/components/AppShell";
import { supabase } from "@/integrations/supabase/client";

export const Route = createFileRoute("/reviews")({
  head: () => ({
    meta: [
      { title: "Customer reviews | Emma Mold Inspection Services" },
      { name: "description", content: "Read verified customer reviews of our mold inspection, cleaning and fumigation work." },
      { property: "og:title", content: "Customer reviews | Emma Mold Inspection Services" },
      { property: "og:description", content: "What homeowners and businesses say about our mold services." },
    ],
  }),
  component: ReviewsPage,
});

function ReviewsPage() {
  const { data } = useQuery({
    queryKey: ["reviews", "published"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("reviews")
        .select("id,author_name,rating,comment,created_at")
        .eq("approved", true)
        .order("created_at", { ascending: false });
      if (error) throw error;
      return data;
    },
  });

  return (
    <AppShell>
      <h1 className="text-2xl font-bold">Customer reviews</h1>
      <p className="mt-1 text-sm text-muted-foreground">Every review is published only after our team verifies the job.</p>
      <div className="mt-5 space-y-3">
        {data?.length ? (
          data.map((r) => (
            <article key={r.id} className="rounded-2xl border border-border/60 bg-card p-4 shadow-card">
              <div className="flex items-center gap-1">
                {Array.from({ length: r.rating }).map((_, i) => (
                  <Star key={i} className="h-4 w-4 fill-warning text-warning" />
                ))}
              </div>
              <p className="mt-2 text-sm text-muted-foreground">{r.comment}</p>
              <p className="mt-2 text-xs font-semibold">{r.author_name}</p>
            </article>
          ))
        ) : (
          <p className="rounded-2xl bg-muted p-6 text-center text-sm text-muted-foreground">
            No published reviews yet.
          </p>
        )}
      </div>
      <Link to="/dashboard" className="mt-5 block text-center text-xs font-semibold text-primary">
        Leave your own review
      </Link>
    </AppShell>
  );
}