'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_compra_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('fuel_tank_entries')
        .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('fuel_tank_entries').update({
      data_compra: form.data_compra,
      fornecedor_id: form.fornecedor_id,
      litros_entregues: parseFloat(form.litros_entregues),
      preco_litro: parseFloat(form.preco_litro),
      observacoes: form.observacoes,
    }).eq('id', id);
    router.push('/abastecimentos/Listagem_compra_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 Compra de Combustível</h1>
          <form onSubmit={handleSubmit} className="space-y-4">
            {/* mesmos campos de cadastro, com value vindo de form */}
            {/* ... */}
            <Button type="submit" className="w-full bg-blue-600 text-white">
              Atualizar Compra
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
