'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 { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';

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

  const [form, setForm] = useState({
    id_patrimonio: '',
    tipo: '',
    descricao: '',
    fornecedor_id: '',
    valor_custo: '',
    data_manutencao: '',
    data_pagamento: '',
    observacoes: '',
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function load() {
      const { data } = await supabase
        .from('manutencoes')
        .select('*')
        .eq('id', id)
        .single();
      if (data) {
        setForm({
          id_patrimonio: data.id_patrimonio,
          tipo: data.tipo,
          descricao: data.descricao,
          fornecedor_id: data.fornecedor_id || '',
          valor_custo: data.valor_custo.toString(),
          data_manutencao: data.data_manutencao,
          data_pagamento: data.data_pagamento || '',
          observacoes: data.observacoes || '',
        });
      }
      setLoading(false);
    }
    load();
  }, [id, supabase]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    await supabase
      .from('manutencoes')
      .update({
        ...form,
        valor_custo: parseFloat(form.valor_custo),
      })
      .eq('id', id);
    router.push('/manutencoes/listagem_manutencoes');
  };

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

  return (
    <div className="p-6 max-w-3xl mx-auto">
      <Card className="shadow-lg">
        <CardContent className="space-y-4 p-6">
          <h1 className="text-2xl font-bold">Editar Manutenção</h1>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <Label>ID Patrimônio</Label>
              <Input name="id_patrimonio" value={form.id_patrimonio} onChange={handleChange} required />
            </div>
            <div>
              <Label>Tipo</Label>
              <Input name="tipo" value={form.tipo} onChange={handleChange} required />
            </div>
            <div>
              <Label>Descrição</Label>
              <Textarea name="descricao" value={form.descricao} onChange={handleChange} />
            </div>
            <div>
              <Label>Fornecedor (ID)</Label>
              <Input name="fornecedor_id" value={form.fornecedor_id} onChange={handleChange} />
            </div>
            <div>
              <Label>Valor Custo (R$)</Label>
              <Input
                name="valor_custo"
                type="number"
                step="0.01"
                value={form.valor_custo}
                onChange={handleChange}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Data Manutenção</Label>
                <Input name="data_manutencao" type="date" value={form.data_manutencao} onChange={handleChange} />
              </div>
              <div>
                <Label>Data Pagamento</Label>
                <Input name="data_pagamento" type="date" value={form.data_pagamento} onChange={handleChange} />
              </div>
            </div>
            <div>
              <Label>Observações</Label>
              <Textarea name="observacoes" value={form.observacoes} onChange={handleChange} />
            </div>
            <Button type="submit" className="w-full bg-green-600 text-white">Salvar Alterações</Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
