import { Link, Navigate } from "react-router-dom";
import { useClientTablos } from "../hooks/useClientPortal";

export function ClientTabloListPage() {
  const { data: tablos, isLoading } = useClientTablos();

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (!tablos || tablos.length === 0) {
    return (
      <div className="text-center py-16">
        <p className="text-muted-foreground">Aucun projet disponible.</p>
      </div>
    );
  }

  if (tablos.length === 1) {
    return <Navigate to={`/tablo/${tablos[0].id}`} replace />;
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Mes projets</h1>
        <p className="text-muted-foreground mt-1">Sélectionnez un projet pour y accéder.</p>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {tablos.map((tablo) => (
          <Link
            key={tablo.id}
            to={`/tablo/${tablo.id}`}
            className="block p-5 rounded-lg border border-border bg-card hover:bg-muted/50 transition-colors space-y-2"
          >
            {tablo.color && <div className={`w-8 h-8 rounded-lg ${tablo.color}`} />}
            <h2 className="font-semibold text-foreground">{tablo.name}</h2>
          </Link>
        ))}
      </div>
    </div>
  );
}
