'use client';
import { useState } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { useAuth } from '@/hooks/useAuth';
import { useApi } from '@/hooks/useApi';
import { categoriesService } from '@/services/categories.service';
import { Card, CardBody } from '@/components/ui/Card';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';
import { PageHeader } from '@/components/layout/PageHeader';
import { LoadingState, EmptyState } from '@/components/ui/States';
import { slugify } from '@/utils/slugify';

export default function CategoriasPage() {
  const { storeId } = useAuth();
  const [name, setName] = useState('');
  const { data, loading, refetch } = useApi(
    () => (storeId ? categoriesService.list(storeId) : Promise.resolve([])),
    [storeId],
  );

  async function add() {
    if (!name || !storeId) return;
    await categoriesService.create({
      id: `cat_${Date.now()}`, storeId, name, slug: slugify(name), active: true, productCount: 0,
    });
    setName('');
    refetch();
  }
  async function remove(id: string) {
    await categoriesService.remove(id);
    refetch();
  }

  return (
    <>
      <PageHeader title="Categorias" subtitle="Organize seus produtos" />
      <div className="grid gap-4 lg:grid-cols-3">
        <Card className="lg:col-span-1">
          <CardBody className="space-y-3">
            <Input label="Nova categoria" value={name} onChange={(e) => setName(e.target.value)} placeholder="Ex: Áudio" />
            <Button className="w-full" onClick={add} disabled={!name}><Plus className="h-4 w-4" /> Adicionar</Button>
          </CardBody>
        </Card>
        <Card className="lg:col-span-2">
          {loading ? <LoadingState /> : (data ?? []).length === 0 ? (
            <EmptyState title="Nenhuma categoria" description="Crie categorias para organizar o catálogo." />
          ) : (
            <CardBody className="space-y-2">
              {(data ?? []).map((c) => (
                <div key={c.id} className="flex items-center justify-between rounded-lg border border-ink-100 px-4 py-3">
                  <div>
                    <p className="font-medium text-ink-900">{c.name}</p>
                    <p className="text-xs text-ink-400">/{c.slug} · {c.productCount ?? 0} produtos</p>
                  </div>
                  <div className="flex items-center gap-3">
                    <Badge tone={c.active ? 'green' : 'gray'}>{c.active ? 'Ativa' : 'Inativa'}</Badge>
                    <button onClick={() => remove(c.id)} className="text-ink-400 hover:text-red-600" aria-label="Remover">
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              ))}
            </CardBody>
          )}
        </Card>
      </div>
    </>
  );
}
