'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 EdicaoSeguro() {
  const supabase = createClientComponentClient();
  const router = useRouter();
  const params = useSearchParams();
  const id = params.get('id')!;

  const [form, setForm] = useState({
    tipo: '',
    seguradora: '',
    cobertura: '',
    valor_total: '',
    valor_mensal: '',
    data_inicio: '',
    data_fim: '',
    status: '',
    observacoes: '',
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function load() {
      const { data, error } = await supabase
        .from('insurance_policies')
        .select('*')
        .eq('id', id)
        .single();
      if (!error && data) {
        setForm({
          tipo: data.tipo,
          seguradora: data.seguradora,
          cobertura: data.cobertura || '',
          valor_total: data.valor_total?.toString() || '',
          valor_mensal: data.valor_mensal?.toString() || '',
          data_inicio: data.data_inicio,
          data_fim: data.data_fim || '',
          status: data.status,
          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('insurance_policies')
      .update({
        ...form,
        valor_total: parseFloat(form.valor_total),
        valor_mensal: parseFloat(form.valor_mensal),
      })
      .eq('id', id);
    router.push('/seguros/listagem_seguro');
  };

  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 Apólice</h1>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <Label>Tipo</Label>
              <Input name="tipo" value={form.tipo} onChange={handleChange} required />
            </div>

            <div>
              <Label>Seguradora</Label>
              <Input name="seguradora" value={form.seguradora} onChange={handleChange} required />
            </div>

            <div>
              <Label>Cobertura</Label>
              <Textarea name="cobertura" value={form.cobertura} onChange={handleChange} />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Valor Total (R$)</Label>
                <Input
                  name="valor_total"
                  type="number"
                  step="0.01"
                  value={form.valor_total}
                  onChange={handleChange}
                />
              </div>
              <div>
                <Label>Valor Mensal (R$)</Label>
                <Input
                  name="valor_mensal"
                  type="number"
                  step="0.01"
                  value={form.valor_mensal}
                  onChange={handleChange}
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>Data Início</Label>
                <Input name="data_inicio" type="date" value={form.data_inicio} onChange={handleChange} />
              </div>
              <div>
                <Label>Data Fim</Label>
                <Input name="data_fim" type="date" value={form.data_fim} onChange={handleChange} />
              </div>
            </div>

            <div>
              <Label>Status</Label>
              <Input name="status" value={form.status} onChange={handleChange} />
            </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>
  );
}
