'use client';
import { useState } from 'react';
import { useParams } from 'next/navigation';
import { Search } from 'lucide-react';
import { useApi } from '@/hooks/useApi';
import { storeService } from '@/services/store.service';
import { productsService } from '@/services/products.service';
import { categoriesService } from '@/services/categories.service';
import { themeService } from '@/services/theme.service';
import { ProductCard } from '@/components/product/ProductCard';
import { LoadingState, EmptyState } from '@/components/ui/States';
import { cn } from '@/utils/cn';

export default function StorefrontPage() {
  const params = useParams();
  const slug = params.slug as string;
  const [q, setQ] = useState('');
  const [cat, setCat] = useState('todos');

  const { data: store } = useApi(() => storeService.getBySlug(slug), [slug]);
  const { data: theme } = useApi(
    () => (store ? themeService.get(store.id) : Promise.resolve(null)),
    [store?.id],
  );
  const { data: products, loading } = useApi(
    () => (store ? productsService.list(store.id) : Promise.resolve([])),
    [store?.id],
  );
  const { data: categories } = useApi(
    () => (store ? categoriesService.list(store.id) : Promise.resolve([])),
    [store?.id],
  );

  if (loading || !store) return <LoadingState />;

  const active = (products ?? []).filter((p) => p.status === 'ativo');
  const featured = active.filter((p) => p.featured);
  const filtered = active.filter(
    (p) =>
      (cat === 'todos' || p.categoryId === cat) &&
      p.name.toLowerCase().includes(q.toLowerCase()),
  );

  return (
    <div className="py-6">
      {/* Banner */}
      <div className="overflow-hidden rounded-2xl text-white" style={{ background: 'var(--store-primary)' }}>
        <div className="relative px-6 py-10 sm:px-10 sm:py-14">
          {store.bannerUrl && (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={store.bannerUrl} alt="" className="absolute inset-0 h-full w-full object-cover opacity-25" />
          )}
          <div className="relative">
            <h1 className="font-display text-3xl font-bold sm:text-4xl">{store.name}</h1>
            <p className="mt-2 max-w-lg text-white/90">{store.description}</p>
          </div>
        </div>
      </div>

      {/* Busca */}
      <div className="mt-6">
        <div className="relative max-w-md">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-ink-400" />
          <input
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Buscar produtos..."
            className="h-11 w-full rounded-lg border border-ink-200 pl-9 pr-3 text-sm focus:outline-none focus:ring-2"
            style={{ ['--tw-ring-color' as string]: 'var(--store-primary)' }}
          />
        </div>
      </div>

      {/* Categorias */}
      {theme?.showCategories && (categories ?? []).length > 0 && (
        <div className="mt-4 flex flex-wrap gap-2">
          {[{ id: 'todos', name: 'Tudo' }, ...(categories ?? [])].map((c) => {
            const isActive = cat === c.id;
            return (
              <button
                key={c.id}
                onClick={() => setCat(c.id)}
                className={cn('rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors', !isActive && 'bg-ink-100 text-ink-600 hover:bg-ink-200')}
                style={isActive ? { background: 'var(--store-primary)', color: '#fff' } : undefined}
              >
                {c.name}
              </button>
            );
          })}
        </div>
      )}

      {/* Destaques */}
      {theme?.showFeatured && featured.length > 0 && cat === 'todos' && !q && (
        <section className="mt-8">
          <h2 className="mb-3 font-display text-lg font-semibold text-ink-900">Destaques</h2>
          <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
            {featured.map((p) => <ProductCard key={p.id} product={p} />)}
          </div>
        </section>
      )}

      {/* Todos os produtos */}
      <section className="mt-8">
        <h2 className="mb-3 font-display text-lg font-semibold text-ink-900">Produtos</h2>
        {filtered.length === 0 ? (
          <EmptyState title="Nenhum produto encontrado" description="Tente outra busca ou categoria." />
        ) : (
          <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
            {filtered.map((p) => <ProductCard key={p.id} product={p} />)}
          </div>
        )}
      </section>
    </div>
  );
}
