import React, { useState, useMemo } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent } from '@/components/ui/card';
import { Users, FileText, Briefcase, Plus, Search, TrendingUp, Loader2, Calendar, Download, Mail, Edit, Ban } from 'lucide-react';
import ExcelTable from '../components/ExcelTable';
import { DashboardKPICard } from '@/components/shared/DashboardKPICard/DashboardKPICard';
import { StatusBadge } from '../components/StatusBadge';
import { useWorkspaceReceitas } from '../hooks/useWorkspaceReceitas';
import { getBackendStatus } from '../utils/backendStatus';
import { workspaceReceitasService } from '@/services/workspaceReceitasService';
import { toast } from 'sonner';

/**
 * Formata nome de status para exibição
 * @param {string} nome
 * @returns {string}
 */
const formatarNome = (nome) => {
  if (!nome) return '';
  return nome
    .replace(/[-_]/g, ' ')
    .trim()
    .toLowerCase()
    .replace(/^\w/, l => l.toUpperCase());
};

export const IncomesView = () => {
  const {
    state: {
      activeTab,
      boletos,
      clientes,
      servicos,
      activeData,
      kpis: kpisData,
      isLoading,
      searchTerm,
      filterMonth,
      selectedStatus,
      statusGroups,
      totalByStatus
    },
    actions: {
      setActiveTab,
      setSearchTerm,
      setFilterMonth,
      setSelectedStatus
    }
  } = useWorkspaceReceitas();

  const status = getBackendStatus('entradas');

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

  const kpis = [
    { label: 'A Receber', value: formatCurrency(kpisData.aReceber || 0), trend: '+12%', color: 'workspace', icon: FileText },
    { label: 'Em Atraso', value: formatCurrency(kpisData.emAtraso || 0), trend: '-5%', color: 'red', icon: TrendingUp },
    { label: 'Recebido', value: formatCurrency(kpisData.recebido || 0), trend: '+8%', color: 'workspace', icon: Users },
    { label: 'Total Faturado', value: formatCurrency(kpisData.totalFaturado || 0), trend: '+15%', color: 'workspace', icon: Briefcase },
  ];

  // Cards de status baseados na lógica antiga
  const statusCards = useMemo(() => {
    if (!statusGroups || !totalByStatus) return [];

    const cards = [];
    
    // Adiciona cards de status de boletos
    for (const [status, data] of Object.entries(totalByStatus)) {
      if (status === 'PIX') continue; // PIX será tratado separadamente
      
      cards.push({
        id: status,
        name: formatarNome(status),
        quantidade: data.quantidade || 0,
        total: data.total || 0,
        origemRecebimento: data.origemRecebimento || 'BOLETO',
        status
      });
    }

    // Adiciona card de PIX se houver
    const pixGroup = statusGroups['PIX'];
    if (pixGroup && pixGroup.quantidade > 0) {
      cards.push({
        id: 'PIX',
        name: 'PIX Recebido',
        quantidade: pixGroup.quantidade,
        total: pixGroup.total,
        origemRecebimento: 'PIX',
        status: 'RECEBIDO'
      });
    }

    return cards;
  }, [statusGroups, totalByStatus]);

  // Ações de boleto
  const handleDownloadPDF = async (codigoSolicitacao) => {
    try {
      const blob = await workspaceReceitasService.downloadBoletoPDF(codigoSolicitacao);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `Boleto_${codigoSolicitacao}.pdf`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
      toast.success('Boleto baixado com sucesso');
    } catch (err) {
      console.error('Erro ao baixar boleto:', err);
      toast.error('Erro ao baixar boleto');
    }
  };

  const handleEnviarEmail = async (codigoSolicitacao, pagadorNome) => {
    try {
      // Busca empresa pelo nome do pagador
      const empresas = await workspaceReceitasService.fetchClientes();
      const empresa = empresas.find(e => e.nome === pagadorNome);
      
      if (!empresa) {
        toast.error('Empresa não encontrada');
        return;
      }

      await workspaceReceitasService.enviarBoletoEmail({
        codigo_solicitacao: codigoSolicitacao,
        idempresa: empresa.id
      });
      
      toast.success('Email enviado com sucesso');
    } catch (err) {
      console.error('Erro ao enviar email:', err);
      toast.error('Erro ao enviar email');
    }
  };

  // Colunas da tabela de boletos
  const boletosColumns = useMemo(() => [
    { field: 'codigoSolicitacao', header: 'Código Solicitação', width: '200px' },
    { field: 'cliente', header: 'Pagador', width: '250px' },
    { field: 'dataEmissao', header: 'Emitido', width: '120px' },
    { field: 'dataVencimento', header: 'Vencimento', width: '120px' },
    { field: 'origemRecebimento', header: 'Recebimento', width: '120px' },
    { field: 'situacao', header: 'Status', width: '120px' },
    { field: 'tipoCobranca', header: 'Tipo de Cobrança', width: '150px' },
    { field: 'valorNominal', header: 'Valor Nominal', width: '150px', type: 'currency' },
    { field: 'valorTotalRecebido', header: 'Total Recebido', width: '150px', type: 'currency' },
  ], []);

  // Dados formatados para a tabela
  const boletosFormatted = useMemo(() => {
    return boletos.map(b => ({
      ...b,
      situacao: b.status || b.situacao,
      dataVencimento: b.vencimento || b.dataVencimento,
      valorNominal: b.valor || b.valorNominal,
      origemRecebimento: b.origemRecebimento || 'BOLETO',
      codigoSolicitacao: b.codigoSolicitacao || b.id || ''
    }));
  }, [boletos]);

  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-3">
           <input
             type="month"
             value={filterMonth}
             onChange={(e) => setFilterMonth(e.target.value)}
             className="px-4 py-2 bg-white dark:bg-[#252525] border border-slate-200 dark:border-white/10 rounded-xl text-xs focus:ring-2 focus:ring-[#26b1c7] focus:outline-none"
           />
           <button className="flex items-center gap-2 bg-[#26b1c7] text-white px-6 py-2.5 rounded-full font-bold text-xs shadow-xl shadow-[#26b1c7]/20 hover:scale-105 active:scale-95 transition-all uppercase tracking-[0.2em]">
              <Plus size={18} />
              NOVA RECEITA
           </button>
         </div>
      </div>

      {/* KPIs da Feature */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpis.map((kpi, i) => (
          <DashboardKPICard 
            key={i}
            label={kpi.label}
            value={kpi.value}
            trend={kpi.trend}
            color={kpi.color}
            icon={kpi.icon}
          />
        ))}
      </div>

      <Card className="border-none shadow-sm bg-white dark:bg-[#1b1b1b] rounded-[32px] overflow-hidden border border-slate-100 dark:border-white/5">
        <Tabs defaultValue="boletos" className="w-full" onValueChange={setActiveTab}>
          <div className="px-6 pt-4 border-b border-slate-100 dark:border-[#2a2a2a] flex justify-between items-center bg-slate-50/50 dark:bg-[#1e1e1e]/50">
            <TabsList className="bg-transparent gap-8 h-12">
              <TabsTrigger 
                value="boletos" 
                className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-[var(--workspace-sec-3-light)] rounded-none px-0 font-bold text-xs uppercase tracking-[0.2em] text-slate-400 data-[state=active]:text-[var(--workspace-sec-3-light)] transition-all"
              >
                <div className="flex items-center gap-2">
                  <FileText size={16} />
                  Boletos
                </div>
              </TabsTrigger>
              <TabsTrigger 
                value="clientes" 
                className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-[var(--workspace-sec-3-light)] rounded-none px-0 font-bold text-xs uppercase tracking-[0.2em] text-slate-400 data-[state=active]:text-[var(--workspace-sec-3-light)] transition-all"
              >
                <div className="flex items-center gap-2">
                  <Users size={16} />
                  Clientes
                </div>
              </TabsTrigger>
              <TabsTrigger 
                value="servicos" 
                className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-[var(--workspace-sec-3-light)] rounded-none px-0 font-bold text-xs uppercase tracking-[0.2em] text-slate-400 data-[state=active]:text-[var(--workspace-sec-3-light)] transition-all"
              >
                <div className="flex items-center gap-2">
                  <Briefcase size={16} />
                  Serviços
                </div>
              </TabsTrigger>
            </TabsList>

            <div className="flex items-center gap-2 bg-white dark:bg-[#252525] px-3 py-1.5 rounded-xl border border-slate-200 dark:border-white/10 shadow-sm focus-within:ring-2 focus-within:ring-[var(--workspace-sec-3-light)] transition-all">
              <Search size={14} className="text-slate-400" />
              <input 
                type="text" 
                placeholder="Pesquisar registro..." 
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="bg-transparent border-none text-xs focus:ring-0 w-48 text-slate-600 dark:text-stone-300 placeholder:text-slate-400"
              />
            </div>
          </div>

          <CardContent className="p-0">
            <TabsContent value="boletos" className="m-0 min-h-[400px]">
               <div className="p-6 space-y-4">
                  {/* Cards de Status */}
                  {!isLoading && statusCards.length > 0 && (
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                      {statusCards.map((card) => (
                        <button
                          key={card.id}
                          onClick={() => setSelectedStatus(selectedStatus === card.status ? null : card.status)}
                          className={`p-4 rounded-2xl border-2 transition-all text-left ${
                            selectedStatus === card.status
                              ? 'border-[#26b1c7] bg-[#26b1c7]/10 dark:bg-[#26b1c7]/20'
                              : 'border-slate-200 dark:border-white/10 bg-white dark:bg-[#252525] hover:border-[#26b1c7]/50'
                          }`}
                        >
                          <div className="font-bold text-xs uppercase tracking-[0.2em] text-slate-400 mb-2">
                            {card.name}
                          </div>
                          <div className="text-2xl font-bold text-[#26b1c7] mb-1">
                            {formatCurrency(card.total)}
                          </div>
                          <div className="text-xs text-slate-500">
                            {card.quantidade} {card.quantidade === 1 ? 'item' : 'itens'}
                          </div>
                        </button>
                      ))}
                    </div>
                  )}

                  {/* Tabela de Boletos */}
                  {isLoading ? (
                    <div className="flex items-center justify-center min-h-[400px]">
                      <Loader2 className="w-8 h-8 animate-spin text-[#26b1c7]" />
                    </div>
                  ) : boletosFormatted.length > 0 ? (
                    <div className="space-y-4">
                      <ExcelTable 
                        columns={boletosColumns}
                        data={boletosFormatted}
                      />
                      {/* Ações para boletos com código */}
                      {boletosFormatted.some(b => b.codigoSolicitacao) && (
                        <div className="flex items-center gap-2 p-4 bg-slate-50 dark:bg-[#1e1e1e] rounded-xl border border-slate-200 dark:border-white/10">
                          <span className="text-xs font-medium text-slate-600 dark:text-slate-400">Ações disponíveis:</span>
                          <button
                            onClick={() => {
                              const boletoComCodigo = boletosFormatted.find(b => b.codigoSolicitacao);
                              if (boletoComCodigo) {
                                handleDownloadPDF(boletoComCodigo.codigoSolicitacao);
                              }
                            }}
                            className="flex items-center gap-2 px-3 py-1.5 bg-[#26b1c7] text-white rounded-lg text-xs font-medium hover:bg-[#26b1c7]/90 transition-colors"
                          >
                            <Download size={14} />
                            Baixar PDF
                          </button>
                          <button
                            onClick={() => {
                              const boletoComCodigo = boletosFormatted.find(b => b.codigoSolicitacao);
                              if (boletoComCodigo) {
                                handleEnviarEmail(boletoComCodigo.codigoSolicitacao, boletoComCodigo.cliente);
                              }
                            }}
                            className="flex items-center gap-2 px-3 py-1.5 bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-200 rounded-lg text-xs font-medium hover:bg-slate-300 dark:hover:bg-slate-600 transition-colors"
                          >
                            <Mail size={14} />
                            Enviar Email
                          </button>
                        </div>
                      )}
                    </div>
                  ) : (
                    <div className="flex flex-col items-center justify-center min-h-[400px] text-slate-400">
                      <FileText size={48} className="mb-4 opacity-50" />
                      <p className="text-sm font-medium">Nenhum boleto encontrado</p>
                      <p className="text-xs text-slate-500 mt-1">Tente alterar o filtro de mês</p>
                    </div>
                  )}
               </div>
            </TabsContent>
            
            <TabsContent value="clientes" className="m-0 min-h-[400px]">
               <div className="p-4">
                  {isLoading ? (
                    <div className="flex items-center justify-center min-h-[400px]">
                      <Loader2 className="w-8 h-8 animate-spin text-[#26b1c7]" />
                    </div>
                  ) : (
                    <ExcelTable 
                      columns={[
                        { field: 'id', header: 'ID', width: '80px' },
                        { field: 'nome', header: 'Nome Fantasia', width: '300px' },
                        { field: 'cnpj', header: 'CNPJ', width: '180px' },
                        { field: 'status', header: 'Status Contrato', width: '150px' },
                        { field: 'total_faturado', header: 'Faturamento Total', width: '180px', type: 'currency' },
                      ]}
                      data={clientes}
                    />
                  )}
               </div>
            </TabsContent>

            <TabsContent value="servicos" className="m-0 min-h-[400px]">
               <div className="p-4">
                  {isLoading ? (
                    <div className="flex items-center justify-center min-h-[400px]">
                      <Loader2 className="w-8 h-8 animate-spin text-[#26b1c7]" />
                    </div>
                  ) : (
                    <ExcelTable 
                      columns={[
                        { field: 'id', header: 'ID', width: '80px' },
                        { field: 'descricao', header: 'Descrição do Serviço', width: '400px' },
                        { field: 'categoria', header: 'Categoria', width: '200px' },
                        { field: 'preco_base', header: 'Preço Base', width: '150px', type: 'currency' },
                      ]}
                      data={servicos}
                    />
                  )}
               </div>
            </TabsContent>
          </CardContent>
        </Tabs>
      </Card>
    </div>
  );
};
