import Link from "next/link";
import { createClient } from "@/lib/supabase/server";
import { Card, CardContent } from "@/components/ui/card";
import { KeyRound, ChevronRight } from "lucide-react";

export default async function RechercheAssisteePage() {
  const supabase = createClient();
  const { data: products } = await supabase
    .from("products")
    .select("fabricant")
    .eq("actif", true);

  const brandsMap = new Map<string, number>();
  for (const p of products ?? []) {
    brandsMap.set(p.fabricant, (brandsMap.get(p.fabricant) ?? 0) + 1);
  }
  const brands = Array.from(brandsMap.entries())
    .map(([name, count]) => ({ name, count }))
    .sort((a, b) => a.name.localeCompare(b.name));

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-2xl font-bold">Recherche assistée</h1>
        <p className="text-sm text-muted-foreground">
          Étape 1 sur 2 — Sélectionnez la marque
        </p>
      </div>

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
        {brands.map((b) => (
          <Link key={b.name} href={`/catalogue?fabricant=${encodeURIComponent(b.name)}`}>
            <Card className="h-full transition-shadow hover:shadow-md">
              <CardContent className="flex items-center justify-between p-4">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-md bg-primary/10 text-primary">
                    <KeyRound className="h-5 w-5" />
                  </div>
                  <div>
                    <div className="font-semibold">{b.name}</div>
                    <div className="text-xs text-muted-foreground">
                      {b.count} modèle{b.count > 1 ? "s" : ""}
                    </div>
                  </div>
                </div>
                <ChevronRight className="h-4 w-4 text-muted-foreground" />
              </CardContent>
            </Card>
          </Link>
        ))}
      </div>
    </div>
  );
}
