'use client';

import { useState, useEffect } from 'react';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import Link from 'next/link';

export default function ListagemSeguro() {
  const supabase = createClientComponentClient();
  const [seguros, setSeguros] = useState<any[]>([]);
  const [filtro, setFiltro] = useState('');

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

  async function fetchSeguros() {
    let query = supabase.from('insurance_policies').select('*');
    if (filtro) {
      query = query.ilike('seguradora', `%${filtro}%`);
    }
    const { data } = await query;
    setSeguros(data || []);
  }

  async function handleDelete(id: string) {
    if (!confirm('Confirma exclusão desta apólice?')) return;
    await supabase.from('insurance_policies').delete().eq('id', id);
    fetchSeguros();
  }

  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">Apólices de Seguro</h1>
        <Link href="/seguros/cadastro_seguro">
          <Button>+ Nova Apólice</Button>
        </Link>
      </div>

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

      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Seguradora</TableHead>
            <TableHead>Tipo</TableHead>
            <TableHead>Valor Total</TableHead>
            <TableHead>Status</TableHead>
            <TableHead className="text-right">Ações</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {seguros.map((s) => (
            <TableRow key={s.id}>
              <TableCell>{s.seguradora}</TableCell>
              <TableCell>{s.tipo}</TableCell>
              <TableCell>R$ {s.valor_total?.toFixed(2)}</TableCell>
              <TableCell>{s.status}</TableCell>
              <TableCell className="text-right space-x-2">
                <Link href={`/seguros/visualizacao_seguro?id=${s.id}`}>
                  <Button size="icon" variant="outline">Ver</Button>
                </Link>
                <Link href={`/seguros/edicao_seguro?id=${s.id}`}>
                  <Button size="icon" variant="secondary">✎</Button>
                </Link>
                <Button size="icon" variant="destructive" onClick={() => handleDelete(s.id)}>
                  🗑️
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}
