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

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

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

  async function handleDelete(id: string) {
    if (!confirm('Deseja excluir este abastecimento?')) return;
    await supabase.from('vehicle_refuels').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">Abastecimentos de Veículos</h1>
        <Link href="/abastecimentos/abastecimento_caminhoes_combustivel">
          <Button>+ Novo Abastecimento</Button>
        </Link>
      </div>

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

      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Data</TableHead>
            <TableHead>Veículo ID</TableHead>
            <TableHead>Km Anterior</TableHead>
            <TableHead>Km Atual</TableHead>
            <TableHead>Litros</TableHead>
            <TableHead>Consumo L/100km</TableHead>
            <TableHead className="text-right">Ações</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {rows.map((r) => (
            <TableRow key={r.id}>
              <TableCell>{r.data_abastecimento}</TableCell>
              <TableCell>{r.id_veiculo}</TableCell>
              <TableCell>{r.km_anterior}</TableCell>
              <TableCell>{r.km_atual}</TableCell>
              <TableCell>{r.litros}</TableCell>
              <TableCell>{r.consumo_medio?.toFixed(2) || '—'}</TableCell>
              <TableCell className="text-right space-x-1">
                <Link href={`/abastecimentos/edicao_abastecimento_combustivel?id=${r.id}`}>
                  <Button size="icon" variant="outline">✎</Button>
                </Link>
                <Button size="icon" variant="destructive" onClick={() => handleDelete(r.id)}>
                  🗑️
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}
