'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';

export default function Edicao_abastecimento_combustivel() {
  const supabase = createClientComponentClient();
  const router = useRouter();
  const params = useSearchParams();
  const id = params.get('id')!;

  const [form, setForm] = useState<any>({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function load() {
      const { data } = await supabase
        .from('vehicle_refuels')
        .select('*')
        .eq('id', id)
        .single();
      setForm(data || {});
      setLoading(false);
    }
    load();
  }, [id]);

  const handleChange = (e: any) =>
    setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }));

  const handleSubmit = async (e: any) => {
    e.preventDefault();
    await supabase.from('vehicle_refuels').update({
      id_veiculo: form.id_veiculo,
      tipo: form.tipo,
      data_abastecimento: form.data_abastecimento,
      quilometragem_anterior: form.quilometragem_anterior,
      quilometragem_atual: form.quilometragem_atual,
      litros: form.litros,
      preco_litro: form.preco_litro,
      observacoes: form.observacoes,
    }).eq('id', id);
    router.push('/abastecimentos/Listagem_abastecimento_combustivel');
  };

  if (loading) return <div className="p-6 text-center">Carregando...</div>;

  return (
    <div className="p-6 max-w-2xl mx-auto">
      <Card>
        <CardContent className="space-y-4">
          <h1 className="text-2xl font-bold">Editar Abastecimento</h1>
          <form onSubmit={handleSubmit} className="space-y-4">
            {/* mesmos campos de cadastro, com value vindo de form */}
            {/* ... */}
            <Button type="submit" className="w-full bg-green-600 text-white">
              Atualizar Abastecimento
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
