// pages/financeiro/despesas.tsx
'use client';

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

import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';

export default function DespesasDashboardPage() {
  const supabase = createClientComponentClient();
  const [totais, setTotais] = useState({
    todas: 0,
    pendentes: 0,
    pagas: 0,
    protestos: 0,
    mes: 0,
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchTotais();
  }, []);

  async function fetchTotais() {
    setLoading(true);
    const hoje = dayjs().format('YYYY-MM-DD');
    const mesInicio = dayjs().startOf('month').format('YYYY-MM-DD');

    // total geral
    const { count: todas } = await supabase
      .from('despesas')
      .select('id', { count: 'exact', head: true });

    // pendentes
    const { count: pendentes } = await supabase
      .from('despesas')
      .select('id', { count: 'exact', head: true })
      .eq('status', 'pendente');

    // pagas
    const { count: pagas } = await supabase
      .from('despesas')
      .select('id', { count: 'exact', head: true })
      .eq('status', 'pago');

    // protestos (a protestar + protestado)
    const { count: protestos } = await supabase
      .from('despesas')
      .select('id', { count: 'exact', head: true })
      .or('status.eq.protestar,status.eq.protestado');

    // despesas no mês atual
    const { count: mes } = await supabase
      .from('despesas')
      .select('id', { count: 'exact', head: true })
      .gte('data_servico', mesInicio)
      .lte('data_servico', hoje);

    setTotais({
      todas: todas || 0,
      pendentes: pendentes || 0,
      pagas: pagas || 0,
      protestos: protestos || 0,
      mes: mes || 0,
    });
    setLoading(false);
  }

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

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

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        <Card>
          <CardHeader>
            <CardTitle>Total de Despesas</CardTitle>
          </CardHeader>
          <CardContent>
            <h2 className="text-4xl font-semibold">{totais.todas}</h2>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Em Aberto</CardTitle>
          </CardHeader>
          <CardContent className="flex items-center space-x-2">
            <h2 className="text-4xl font-semibold">{totais.pendentes}</h2>
            <Badge variant="destructive">Pendente</Badge>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Pagas</CardTitle>
          </CardHeader>
          <CardContent className="flex items-center space-x-2">
            <h2 className="text-4xl font-semibold">{totais.pagas}</h2>
            <Badge variant="success">Pago</Badge>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Protestos</CardTitle>
          </CardHeader>
          <CardContent>
            <h2 className="text-4xl font-semibold">{totais.protestos}</h2>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Este Mês</CardTitle>
          </CardHeader>
          <CardContent>
            <h2 className="text-4xl font-semibold">{totais.mes}</h2>
          </CardContent>
        </Card>
      </div>

      <div className="flex flex-wrap gap-4">
        <Link href="/financeiro/cadastro_de_despesa">
          <Button variant="default">+ Nova Despesa</Button>
        </Link>
        <Link href="/financeiro/consulta_despesas">
          <Button variant="outline">Consultar Despesas</Button>
        </Link>
        <Link href="/financeiro/consulta_nao_recebidos">
          <Button variant="outline">Não Recebidas</Button>
        </Link>
        <Link href="/financeiro/consulta_protestos">
          <Button variant="outline">Protestos</Button>
        </Link>
      </div>
    </div>
  );
}
