'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import {
  Table, TableHeader, TableBody, TableRow, TableHead, TableCell
} from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

export default function Listagem_fornecedores() {
  const supabase = createClientComponentClient();
  const [rows, setRows] = useState<any[]>([]);
  const [filtro, setFiltro] = useState('');

  useEffect(() => {
    fetchRows();
  }, [filtro]);

  async function fetchRows() {
    let q = supabase.from('suppliers').select('*');
    if (filtro) {
      q = q.ilike('nome', `%${filtro}%`);
    }
    const { data } = await q.order('nome', { ascending: true });
    setRows(data || []);
  }

  async function handleDelete(id: string) {
    if (!confirm('Deseja excluir este fornecedor?')) return;
    await supabase.from('suppliers').delete().eq('id', id);
    fetchRows();
  }

  return (
    <div className="p-6 max-w-6xl mx-auto">
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-2xl font-bold">Fornecedores</h1>
        <Link href="/fornecedores/cadastro_fornecedor">
          <Button>+ Novo Fornecedor</Button>
        </Link>
      </div>

      <div className="mb-4">
        <Input
          placeholder="Filtrar por nome..."
          value={filtro}
          onChange={(e) => setFiltro(e.target.value)}
        />
      </div>

      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Nome</TableHead>
            <TableHead>CNPJ/CPF</TableHead>
            <TableHead>Telefone</TableHead>
            <TableHead>Email</TableHead>
            <TableHead className="text-right">Ações</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {rows.map(f => (
            <TableRow key={f.id}>
              <TableCell>{f.nome}</TableCell>
              <TableCell>{f.cnpj_cpf}</TableCell>
              <TableCell>{f.telefone}</TableCell>
              <TableCell>{f.email}</TableCell>
              <TableCell className="text-right space-x-1">
                <Link href={`/fornecedores/edicao_fornecedor?id=${f.id}`}>
                  <Button size="icon" variant="outline">✎</Button>
                </Link>
                <Button size="icon" variant="destructive" onClick={() => handleDelete(f.id)}>
                  🗑️
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}
