'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_compra_combustivel() {
  const supabase = createClientComponentClient();
  const [entries, setEntries] = useState<any[]>([]);
  const [filtro, setFiltro] = useState('');

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

  async function fetchEntries() {
    let q = supabase.from('fuel_tank_entries').select('*');
    if (filtro) {
      q = q.ilike('fornecedor_id', `%${filtro}%`);
    }
    const { data } = await q.order('data_compra', { ascending: false });
    setEntries(data || []);
  }

  async function handleDelete(id: string) {
    if (!confirm('Deseja excluir esta compra?')) return;
    await supabase.from('fuel_tank_entries').delete().eq('id', id);
    fetchEntries();
  }

  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">Compras de Combustível</h1>
        <Link href="/abastecimentos/compra_combustivel">
          <Button>+ Nova Compra</Button>
        </Link>
      </div>

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

      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Data</TableHead>
            <TableHead>Fornecedor</TableHead>
            <TableHead>Litros</TableHead>
            <TableHead>Preço/L</TableHead>
            <TableHead>Total (R$)</TableHead>
            <TableHead className="text-right">Ações</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {entries.map((e) => (
            <TableRow key={e.id}>
              <TableCell>{e.data_compra}</TableCell>
              <TableCell>{e.fornecedor_id}</TableCell>
              <TableCell>{e.litros_entregues}</TableCell>
              <TableCell>{e.preco_litro.toFixed(2)}</TableCell>
              <TableCell>{e.valor_total.toFixed(2)}</TableCell>
              <TableCell className="text-right space-x-1">
                <Link href={`/abastecimentos/edicao_compra_combustivel?id=${e.id}`}>
                  <Button size="icon" variant="outline">✎</Button>
                </Link>
                <Button size="icon" variant="destructive" onClick={() => handleDelete(e.id)}>
                  🗑️
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}
