'use client';
import Link from 'next/link';
import { Card, CardContent } from '@/components/ui/card';
import Image from 'next/image';
import { useCollection, useFirestore, useMemoFirebase } from '@/firebase';
import { collection } from 'firebase/firestore';
import type { Category } from '@/lib/types';
import { Skeleton } from '@/components/ui/skeleton';

export default function CategoriesPage() {
  const firestore = useFirestore();
  const categoriesQuery = useMemoFirebase(() => firestore ? collection(firestore, 'categories') : null, [firestore]);
  const { data: categories, isLoading } = useCollection<Category>(categoriesQuery);

  return (
    <div className="container mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
      <header className="mb-8 text-center md:text-left">
        <h1 className="text-3xl font-bold font-headline text-primary md:text-4xl">Browse Categories</h1>
        <p className="mt-2 text-muted-foreground">Find the perfect service by choosing a category.</p>
      </header>

      <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
        {isLoading ? (
            [...Array(4)].map((_, i) => <Skeleton key={i} className="h-48 w-full rounded-lg" />)
        ) : (
            (categories || []).map((category) => (
              <Link href={`/categories/${category.name.toLowerCase()}`} key={category.id} className="group">
                <Card className="relative h-48 overflow-hidden rounded-lg transition-transform duration-300 ease-in-out group-hover:scale-105 group-hover:shadow-xl">
                  <Image
                    src={category.imageUrl}
                    alt={category.name}
                    fill
                    className="object-cover transition-transform duration-300 group-hover:scale-110"
                  />
                  <div className="absolute inset-0 bg-black/50" />
                  <CardContent className="relative flex h-full items-center justify-center p-6 text-center">
                    <h3 className="text-2xl font-bold text-white">{category.name}</h3>
                  </CardContent>
                </Card>
              </Link>
            ))
        )}
      </div>
    </div>
  );
}
