import React from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FineCard } from '../components/FineCard';
import { DashboardKPICard } from '@/components/shared/DashboardKPICard/DashboardKPICard';
import { StatusBadge } from '../components/StatusBadge';
import { TrendingDown, Calendar, ArrowRightLeft } from 'lucide-react';
import { useWorkspaceDespesas } from '../hooks/useWorkspaceDespesas';
import { getBackendStatus } from '../utils/backendStatus';

export const ExpensesView = () => {
  const {
    state: {
      kpis,
      fluxoCaixa,
      categorias,
      isLoading,
      filtroMes,
      filtroAno
    },
    actions: {
      setFiltroMes,
      setFiltroAno
    }
  } = useWorkspaceDespesas();

  const status = getBackendStatus('saidas');

  // Formatar valores para exibição
  const formatCurrency = (value) => {
    return new Intl.NumberFormat('pt-BR', {
      style: 'currency',
      currency: 'BRL'
    }).format(value);
  };

  // Nomes dos meses
  const meses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 
                 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];

  return (
    <div className="workspace-theme space-y-6">
      <div className="flex justify-between items-center mb-2">
          <StatusBadge status={status} />
          <div className="flex items-center gap-2 bg-white dark:bg-[#1b1b1b] px-4 py-2 rounded-full border border-slate-200 dark:border-[#333] text-xs font-bold text-slate-600 dark:text-stone-300 shadow-sm uppercase tracking-widest">
            <Calendar size={16} className="text-[#26b1c7]" />
            {meses[filtroMes - 1]?.toUpperCase()} / {filtroAno}
          </div>
      </div>

      {/* Resumo de Saídas */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
         <DashboardKPICard 
            label="Total Planejado"
            value={formatCurrency(kpis.totalPlanejado || 0)}
            color="workspace"
         />
         <DashboardKPICard 
            label="Total Executado"
            value={formatCurrency(kpis.totalExecutado || 0)}
            trend={kpis.totalPlanejado > 0 ? (kpis.diferenca > 0 ? `+${((kpis.diferenca / kpis.totalPlanejado) * 100).toFixed(1)}%` : `${((kpis.diferenca / kpis.totalPlanejado) * 100).toFixed(1)}%`) : '0%'}
            trendDirection={kpis.diferenca > 0 ? "down" : "up"}
            color={kpis.diferenca > 0 ? "red" : "workspace"}
         />
         <DashboardKPICard 
            label="Diferença"
            value={formatCurrency(kpis.diferenca || 0)}
            color={kpis.diferenca < 0 ? "red" : "workspace"}
            icon={TrendingDown}
         />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Gráfico de Comparação */}
        <Card className="border-none shadow-sm bg-white dark:bg-[#1b1b1b] rounded-[32px] overflow-hidden">
          <CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-slate-50 dark:border-[#2a2a2a]">
            <div>
              <CardTitle className="text-sm font-bold text-slate-600 dark:text-stone-300 uppercase tracking-widest">Planejado vs Executado</CardTitle>
              <p className="text-[10px] text-slate-400">Histórico de variação mensal (Financeiro)</p>
            </div>
            <ArrowRightLeft size={18} className="text-slate-300" />
          </CardHeader>
          <CardContent className="pt-6">
            <FineCard 
              title=""
              height={300}
              type="bar"
              data={fluxoCaixa.length > 0 ? fluxoCaixa : []}
              dataKey="executado"
              colors={['#003153', '#22bb6c']} 
            />
          </CardContent>
        </Card>

        {/* Gráfico de Categorias */}
        <FineCard 
           title={`Saídas por Categoria (${meses[filtroMes - 1]}/${filtroAno})`}
           data={categorias.length > 0 ? categorias : []}
           height={380}
           colors={['#003153', '#22bb6c', '#22c0a3', '#26b1c7', '#285d2a']}
        />
      </div>

      {/* Tabela de Lançamentos (Mock) */}
      <Card className="border-none shadow-sm bg-white dark:bg-[#1b1b1b] rounded-[32px] overflow-hidden">
        <div className="p-12 text-center">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-slate-50 dark:bg-white/5 rounded-full mb-4">
               <ArrowRightLeft size={32} className="text-slate-300" />
            </div>
            <h3 className="text-lg font-bold text-slate-700 dark:text-stone-200">Lançamentos Financeiros</h3>
            <p className="text-slate-400 text-sm max-w-md mx-auto mt-2">
              A integração completa com o ExcelTable permitirá visualizar cada nota fiscal, boleto e pix de saída individualmente.
            </p>
        </div>
      </Card>
    </div>
  );
};
