import React, { useState } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent } from '@/components/ui/card';
import { 
  ArrowRightLeft, 
  Settings2, 
  ShieldCheck, 
  AlertCircle,
  Plus,
  ArrowUpCircle,
  ArrowDownCircle,
  Search,
  Loader2
} from 'lucide-react';
import { DashboardKPICard } from '@/components/shared/DashboardKPICard/DashboardKPICard';
import ExcelTable from '../components/ExcelTable';
import { useWorkspaceConciliacao } from '../hooks/useWorkspaceConciliacao';
import { CategorizarTransacaoModal } from '../components/CategorizarTransacaoModal';
import { CriarRegraModal } from '../components/CriarRegraModal';
import { toast } from 'sonner';

export const ReconciliationView = () => {
  const {
    state: {
      activeTab,
      pendentes,
      cruzamentos,
      kpis,
      isLoading,
      filtroCaixinha,
      filtroMes,
      filtroAno,
      searchTerm,
      isCategorizarModalOpen,
      isCriarRegraModalOpen,
      selectedTransaction,
      isSubmitting,
      categories,
      caixinhas
    },
    actions: {
      setActiveTab,
      setFiltroCaixinha,
      setFiltroMes,
      setFiltroAno,
      setSearchTerm,
      loadPendentes,
      loadCruzamentos,
      handleOpenCategorizarModal,
      handleOpenCriarRegraModal,
      handleCloseCategorizarModal,
      handleCloseCriarRegraModal,
      handleSwitchToCriarRegra,
      handleSubmitCategorizar,
      handleSubmitCriarRegra
    }
  } = useWorkspaceConciliacao();

  /**
   * Função para processar a conciliação automática
   * Baseado na lógica antiga: processarReconciliacao
   * A conciliação será feita pelo backend através da rota /categorias/transacoes/pendentes
   * Por enquanto, apenas recarrega os dados. Em produção, isso chamaria uma rota específica de conciliação se existir
   */
  const handleConciliar = async () => {
    if (isLoading) return;
    
    try {
      toast.loading('Processando conciliação...', { id: 'conciliar' });
      
      // A conciliação automática será processada pelo backend
      // Por enquanto, apenas recarrega os dados após um delay simulado
      // Em produção, isso chamaria uma rota específica de conciliação se existir
      
      // Recarrega pendentes e cruzamentos após conciliação
      await Promise.all([
        loadPendentes(),
        loadCruzamentos()
      ]);
      
      toast.success('Conciliação processada com sucesso!', { id: 'conciliar' });
    } catch (error) {
      console.error('Erro ao conciliar:', error);
      toast.error('Erro ao processar conciliação', { id: 'conciliar' });
    }
  };

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

  const kpisData = [
    { label: 'Saldo Bancário', value: formatCurrency(kpis.saldoBancario), color: 'workspace', icon: ArrowUpCircle },
    { label: 'A Conciliar hoje', value: formatCurrency(kpis.valorPendentes), color: 'workspace', icon: AlertCircle },
    { label: 'Pendências Críticas', value: kpis.pendenciasCriticas.toString(), color: 'red', icon: ShieldCheck },
    { label: 'Total Pendentes', value: kpis.totalPendentes.toString(), color: 'workspace', icon: Settings2 },
  ];

  return (
    <div className="workspace-theme space-y-6">
      <div className="flex justify-end mb-2">
          <button 
            onClick={handleConciliar}
            disabled={isLoading}
            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] disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <ArrowRightLeft size={18} />
            {isLoading ? 'CONCILIANDO...' : 'CONCILIAR AGORA'}
          </button>
      </div>

      {/* KPI Section */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpisData.map((kpi, i) => (
          <DashboardKPICard 
            key={i}
            label={kpi.label}
            value={kpi.value}
            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 value={activeTab} 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="pendencias" 
                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">
                  <AlertCircle size={16} />
                  Pendências
                </div>
              </TabsTrigger>
              <TabsTrigger 
                value="cruzamento" 
                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">
                  <ArrowRightLeft size={16} />
                  Cruzamento
                </div>
              </TabsTrigger>
              <TabsTrigger 
                value="config" 
                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">
                  <Settings2 size={16} />
                  Configurações
                </div>
              </TabsTrigger>
            </TabsList>

            <div className="flex items-center gap-2 bg-white dark:bg-[#252525] px-4 py-2 rounded-full border border-slate-200 dark:border-white/10 shadow-sm">
               <Search size={14} className="text-slate-400" />
               <input 
                 type="text" 
                 placeholder="Buscar transação..." 
                 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-500"
               />
            </div>
          </div>

          <CardContent className="p-0">
            <TabsContent value="pendencias" 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: 'data', header: 'Data', width: '120px' },
                        { field: 'descricao', header: 'Descrição da Transação', width: '350px' },
                        { 
                          field: 'valor', 
                          header: 'Valor', 
                          width: '150px',
                          render: (row) => {
                            const value = row.valor || 0;
                            const formatted = new Intl.NumberFormat('pt-BR', {
                              style: 'currency',
                              currency: 'BRL'
                            }).format(value);
                            const isDebito = row.tipo === 'DEBITO' || row.tipo === 'D';
                            return (
                              <span className={`font-mono font-bold ${isDebito ? 'text-rose-500 dark:text-rose-400' : 'text-green-600 dark:text-green-400'}`}>
                                {formatted}
                              </span>
                            );
                          }
                        },
                        { field: 'tipo', header: 'Tipo', width: '120px' },
                        { 
                          field: 'acoes', 
                          header: 'Ações', 
                          width: '150px',
                          render: (row) => (
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                handleOpenCategorizarModal(row);
                              }}
                              className="text-xs font-bold uppercase tracking-wider text-[#26b1c7] hover:text-[#1f9fb3] transition-colors px-3 py-1.5 rounded-lg hover:bg-[#26b1c7]/10"
                            >
                              Categorizar
                            </button>
                          )
                        },
                      ]}
                      data={pendentes}
                    />
                  )}
               </div>
            </TabsContent>
            
            <TabsContent value="cruzamento" className="m-0 min-h-[400px]">
               <div className="p-6 space-y-4">
                  {/* Filtros */}
                  <div className="flex flex-wrap gap-4 items-center">
                    <div className="flex items-center gap-2">
                      <label className="text-xs font-bold text-slate-600 dark:text-stone-300 uppercase tracking-wider">Caixinha:</label>
                      <input
                        type="number"
                        value={filtroCaixinha || ''}
                        onChange={(e) => setFiltroCaixinha(e.target.value ? parseInt(e.target.value) : null)}
                        placeholder="ID"
                        className="w-20 px-2 py-1 text-xs bg-white dark:bg-[#252525] border border-slate-200 dark:border-white/10 rounded-lg"
                      />
                    </div>
                    <div className="flex items-center gap-2">
                      <label className="text-xs font-bold text-slate-600 dark:text-stone-300 uppercase tracking-wider">Mês:</label>
                      <input
                        type="number"
                        min="1"
                        max="12"
                        value={filtroMes}
                        onChange={(e) => setFiltroMes(parseInt(e.target.value))}
                        className="w-20 px-2 py-1 text-xs bg-white dark:bg-[#252525] border border-slate-200 dark:border-white/10 rounded-lg"
                      />
                    </div>
                    <div className="flex items-center gap-2">
                      <label className="text-xs font-bold text-slate-600 dark:text-stone-300 uppercase tracking-wider">Ano:</label>
                      <input
                        type="number"
                        min="2020"
                        max="2030"
                        value={filtroAno}
                        onChange={(e) => setFiltroAno(parseInt(e.target.value))}
                        className="w-24 px-2 py-1 text-xs bg-white dark:bg-[#252525] border border-slate-200 dark:border-white/10 rounded-lg"
                      />
                    </div>
                  </div>

                  {/* Tabela de Cruzamentos */}
                  {isLoading ? (
                    <div className="flex items-center justify-center min-h-[400px]">
                      <Loader2 className="w-8 h-8 animate-spin text-[#26b1c7]" />
                    </div>
                  ) : cruzamentos.length > 0 ? (
                    <ExcelTable 
                      columns={[
                        { field: 'id', header: 'ID', width: '80px' },
                        { field: 'data', header: 'Data', width: '120px' },
                        { field: 'descricao', header: 'Descrição', width: '350px' },
                        { field: 'valor', header: 'Valor', width: '150px', type: 'currency' },
                        { field: 'caixinha', header: 'Caixinha', width: '100px' },
                      ]}
                      data={cruzamentos}
                    />
                  ) : (
                    <div className="p-12 text-center">
                      <div className="w-16 h-16 bg-slate-50 dark:bg-white/5 rounded-full flex items-center justify-center mx-auto mb-4 border border-slate-100 dark:border-white/5">
                        <ArrowRightLeft size={32} className="text-[var(--workspace-sec-3-light)]" />
                      </div>
                      <h3 className="text-lg font-bold uppercase tracking-tight text-slate-700 dark:text-stone-200">Cruzamento Digital</h3>
                      <p className="text-slate-400 text-sm max-w-md mx-auto mt-2">
                        Nenhum cruzamento encontrado para os filtros selecionados.
                      </p>
                    </div>
                  )}
               </div>
            </TabsContent>

            <TabsContent value="config" className="m-0 min-h-[400px]">
               <div className="grid grid-cols-1 md:grid-cols-3 gap-4 p-6">
                  {['Categorias', 'Regras de Importação', 'Mapeamento de Caixas'].map(item => (
                    <Card key={item} className="p-6 bg-slate-50 dark:bg-white/5 border-none hover:bg-white dark:hover:bg-white/10 transition-all cursor-pointer group rounded-2xl border border-transparent hover:border-slate-200 dark:hover:border-white/10">
                       <h4 className="font-bold text-slate-700 dark:text-stone-200 mb-2">{item}</h4>
                       <p className="text-[10px] text-slate-400 uppercase tracking-widest">Gerenciar Parâmetros</p>
                    </Card>
                  ))}
               </div>
            </TabsContent>
          </CardContent>
        </Tabs>
      </Card>

      {/* Modais */}
      <CategorizarTransacaoModal
        isOpen={isCategorizarModalOpen}
        onClose={handleCloseCategorizarModal}
        transaction={selectedTransaction}
        categories={categories}
        caixinhas={caixinhas}
        onSubmit={handleSubmitCategorizar}
        onSwitchToCriarRegra={handleSwitchToCriarRegra}
        isLoading={isSubmitting}
      />

      <CriarRegraModal
        isOpen={isCriarRegraModalOpen}
        onClose={handleCloseCriarRegraModal}
        transaction={selectedTransaction}
        formData={selectedTransaction?.formData || null}
        categories={categories}
        caixinhas={caixinhas}
        onSubmit={handleSubmitCriarRegra}
        isLoading={isSubmitting}
      />
    </div>
  );
};
