'use client';

import { useState, useEffect } from 'react';
import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import dayjs from 'dayjs';

import {
  Table, TableHeader, TableBody, TableRow, TableHead, TableCell
} from '@/components/ui/table';
import { Select } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

type Despesa = {
  id: string;
  categoria: { nome: string };
  fornecedor: { nome: string } | null;
  valor: number;
  data_servico: string;
  status: string;
};

const categorias = [
  'manutenção','combustível','seguro','salários','fornecedor','taxas','outros'
];

export default function ConsultaDespesas() {
  const supabase = createClientComponentClient();
  const [despesas, setDespesas] = useState<Despesa[]>([]);
  const [filtroCat, setFiltroCat] = useState('');
  const [from, setFrom] = useState(dayjs().startOf('month').format('YYYY-MM-DD'));
  const [to, setTo] = useState(dayjs().format('YYYY-MM-DD'));

  useEffect(() => { fetchDespesas(); }, [filtroCat, from, to]);

  async function fetchDespesas() {
    let query = supabase
      .from('expenses')
      .select('id, valor, data_servico, status, categoria:expense_categories(nome), fornecedor:suppliers(nome)')
      .gte('data_servico', from)
      .lte('data_servico', to);

    if (filtroCat) query = query.eq('categoria_id', filtroCat);

    const { data } = await query.order('data_servico', { ascending: false });
    setDespesas(data || []);
  }

  return (
    <div className="p-6 max-w-5xl mx-auto space-y-6">
      <h1 className="text-3xl font-bold">Consulta de Despesas</h1>

      {/* filtros */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Select value={filtroCat} onValueChange={setFiltroCat}>
          <Select.Trigger><Select.Value placeholder="Todas Categorias" /></Select.Trigger>
          <Select.Content>
            <Select.Item value="">Todas</Select.Item>
            {categorias.map((cat) => (
              <Select.Item key={cat} value={cat}>{cat}</Select.Item>
            ))}
          </Select.Content>
        </Select>

        <Input type="date" value={from} onChange={e => setFrom(e.target.value)} />
        <Input type="date" value={to} onChange={e => setTo(e.target.value)} />
        <Button onClick={fetchDespesas}>Filtrar</Button>
      </div>

      {/* tabela */}
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Categoria</TableHead>
            <TableHead>Fornecedor</TableHead>
            <TableHead>Valor</TableHead>
            <TableHead>Data Serviço</TableHead>
            <TableHead>Status</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {despesas.map((d) => (
            <TableRow key={d.id}>
              <TableCell>{d.categoria.nome}</TableCell>
              <TableCell>{d.fornecedor?.nome || '—'}</TableCell>
              <TableCell>R$ {d.valor.toFixed(2)}</TableCell>
              <TableCell>{dayjs(d.data_servico).format('DD/MM/YYYY')}</TableCell>
              <TableCell>{d.status}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}
