import React from 'react';
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogDescription,
  DialogFooter 
} from '@/components/ui/dialog';
import { 
  Tabs, 
  TabsContent, 
  TabsList, 
  TabsTrigger 
} from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  AlertCircle,
  ExternalLink,
  Edit,
  CreditCard,
  Hash,
  Info,
  Banknote,
  Percent,
  History,
  ArrowRightLeft,
  Settings,
  CheckCircle2,
  ArrowUpRight,
  ArrowDownRight,
  Calendar,
  User,
  FileText,
  Tag
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { formatDate, formatDateTime, formatCurrency } from '../utils/dateUtils';

/**
 * Modal de detalhamento de transação
 * Exibe todos os detalhes de uma transação do extrato
 */
/**
 * Modal de detalhamento de transação
 * Exibe todos os detalhes de uma transação do extrato
 */
export function TransactionDetailModal({ 
  transaction, 
  open, 
  onOpenChange, 
  onEditTransaction, 
  onViewInExtrato,
  categorias = [],
  caixas = []
}) {
  if (!transaction) return null;

  const isCredit = transaction.tipoOperacao === 'C';
  const isConciliado = transaction.categoria && transaction.categoria != 0;

  // Helper para buscar nome da categoria
  function getCategoriaNome() {
    if (transaction.categoriaNome) return transaction.categoriaNome;
    if (!transaction.categoria || transaction.categoria == 0) return 'Não conciliado';
    
    const cat = categorias.find(c => String(c.id) === String(transaction.categoria) || String(c.idcategoria) === String(transaction.categoria));
    return cat ? (cat.name || cat.nome || cat.categoria) : 'Categoria ' + transaction.categoria;
  };

  // Helper para buscar nome da caixinha
  const getCaixinhaNome = () => {
    if (!transaction.caixinha || transaction.caixinha == 0) return null;
    
    const caixa = caixas.find(c => String(c.id) === String(transaction.caixinha) || String(c.idcaixinhas_financeiro) === String(transaction.caixinha));
    return caixa ? (caixa.name || caixa.nome || caixa.caixinha) : transaction.caixinha;
  };

  const categoriaNome = getCategoriaNome();
  const caixinhaNome = getCaixinhaNome();


  const InfoField = ({ label, value, icon: Icon, className = "" }) => (
    <div className={cn("space-y-1.5", className)}>
      <span className="text-[10px] text-slate-500 dark:text-slate-400 font-black uppercase tracking-widest flex items-center gap-1.5">
        {Icon && <Icon size={12} className="text-slate-400" />}
        {label}
      </span>
      <p className="text-sm font-semibold text-slate-900 dark:text-white truncate">
        {value === null || value === undefined || value === "" || value === 0 ? (
          <span className="text-slate-300 dark:text-slate-700 italic font-normal text-xs">Não informado</span>
        ) : (
          typeof value === 'number' && label.toLowerCase().includes('valor') || ['juros', 'multa', 'abatimento', 'imposto', 'desconto'].some(k => label.toLowerCase().includes(k))
            ? formatCurrency(value)
            : value
        )}
      </p>
    </div>
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="bg-white dark:bg-[#0b1120] border-slate-200 dark:border-slate-800 max-w-2xl p-0 overflow-hidden z-[9999]">
        {/* Header Superior - Destaque */}
        <div className={cn(
          "p-6 border-b border-slate-100 dark:border-slate-800",
          isCredit ? "bg-emerald-500/5" : "bg-rose-500/5"
        )}>
          <div className="flex items-center justify-between gap-6">
            <div className="flex items-center gap-4">
              <div className={cn(
                "w-14 h-14 rounded-2xl flex items-center justify-center shadow-sm",
                isCredit ? "bg-emerald-500/10 text-emerald-600 dark:bg-emerald-500/20" : "bg-rose-500/10 text-rose-600 dark:bg-rose-500/20"
              )}>
                {isCredit ? <ArrowUpRight size={28} /> : <ArrowDownRight size={28} />}
              </div>
              <div className="space-y-1">
                <DialogDescription className="sr-only">
                  Detalhamento da transação bancária
                </DialogDescription>
                <DialogTitle className="text-xl font-bold text-slate-900 dark:text-white line-clamp-1">
                  {transaction.titulo || transaction.descricao || 'Transação sem título'}
                </DialogTitle>
                <div className="flex items-center gap-2">
                  <Badge variant="outline" className="text-[9px] font-black tracking-tighter uppercase border-slate-200 dark:border-slate-800">
                    {transaction.tipoTransacao || 'Geral'}
                  </Badge>
                  <Badge className={cn(
                    "text-[9px] font-black tracking-tighter uppercase",
                    isConciliado ? "bg-emerald-500/10 text-emerald-600 border-emerald-500/20" : "bg-amber-500/10 text-amber-600 border-amber-500/20"
                  )}>
                    {isConciliado ? 'Conciliado' : 'Pendente'}
                  </Badge>
                </div>
              </div>
            </div>
            <div className="text-right">
              <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1">Valor Total</p>
              <div className={cn(
                "text-2xl font-black tabular-nums",
                isCredit ? "text-emerald-600" : "text-rose-600"
              )}>
                {isCredit ? '+' : '-'}{formatCurrency(transaction.valorTotal || transaction.valor)}
              </div>
            </div>
          </div>
        </div>

        <Tabs defaultValue="geral" className="w-full">
          <div className="px-6 border-b border-slate-100 dark:border-slate-800 bg-slate-50/50 dark:bg-slate-900/50">
            <TabsList className="h-12 bg-transparent gap-6 p-0 w-full justify-start overflow-x-auto no-scrollbar">
              <TabsTrigger value="geral" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 border-b-2 border-transparent data-[state=active]:border-blue-600 rounded-none h-full px-1 text-[10px] font-black uppercase tracking-widest transition-all">
                Geral
              </TabsTrigger>
              <TabsTrigger value="financeiro" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 border-b-2 border-transparent data-[state=active]:border-blue-600 rounded-none h-full px-1 text-[10px] font-black uppercase tracking-widest transition-all">
                Financeiro
              </TabsTrigger>
              <TabsTrigger value="participantes" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 border-b-2 border-transparent data-[state=active]:border-blue-600 rounded-none h-full px-1 text-[10px] font-black uppercase tracking-widest transition-all">
                Participantes
              </TabsTrigger>
              <TabsTrigger value="tecnico" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 border-b-2 border-transparent data-[state=active]:border-blue-600 rounded-none h-full px-1 text-[10px] font-black uppercase tracking-widest transition-all">
                Técnico
              </TabsTrigger>
              <TabsTrigger value="conciliacao" className="data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 border-b-2 border-transparent data-[state=active]:border-blue-600 rounded-none h-full px-1 text-[10px] font-black uppercase tracking-widest transition-all">
                Conciliação
              </TabsTrigger>
            </TabsList>
          </div>

          <div className="p-6 h-[350px] overflow-y-auto custom-scrollbar">
            <TabsContent value="geral" className="mt-0 outline-none space-y-6">
              <div className="grid grid-cols-2 gap-y-6 gap-x-12">
                <InfoField label="Título" value={transaction.titulo} icon={Info} className="col-span-2" />
                <InfoField label="Data de Entrada" value={formatDateTime(transaction.dataEntrada || transaction.dataTransacao || transaction.data)} icon={Calendar} />
                <InfoField label="Tipo Transação" value={transaction.tipoTransacao} icon={Tag} />
                <InfoField label="Valor Lançado" value={transaction.valor || transaction.valorTotal} icon={Banknote} />
                <InfoField label="Operação" value={transaction.tipoOperacao === 'D' ? 'Débito' : 'Crédito'} icon={ArrowRightLeft} />
                <div className="col-span-2 space-y-2">
                  <span className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Descrição Completa</span>
                  <div className="p-3 bg-slate-50 dark:bg-slate-900 border border-slate-100 dark:border-slate-800 rounded-lg text-xs leading-relaxed text-slate-600 dark:text-slate-400">
                    {transaction.descricao || 'Sem descrição detalhada disponível.'}
                  </div>
                </div>
              </div>
            </TabsContent>

            <TabsContent value="financeiro" className="mt-0 outline-none space-y-6">
              <div className="grid grid-cols-2 gap-y-6 gap-x-12">
                <InfoField label="Valor Base/Original" value={transaction.valor} icon={Banknote} />
                <InfoField label="Acréscimos (Adicionado)" value={transaction.adicionado} icon={ArrowUpRight} />
                <InfoField label="Juros" value={transaction.juros} icon={Percent} />
                <InfoField label="Multa" value={transaction.multa} icon={Percent} />
                <InfoField label="Abatimento" value={transaction.abatimento} icon={ArrowDownRight} />
                <InfoField label="Imposto Retido" value={transaction.imposto} icon={FileText} />
                <InfoField label="Desconto 01" value={transaction.desconto1} icon={Tag} />
                <InfoField label="Desconto 02" value={transaction.desconto2} icon={Tag} />
                <InfoField label="Desconto 03" value={transaction.desconto3} icon={Tag} />
                <InfoField label="Valor Final Liquido" value={transaction.valorTotal || transaction.valor} icon={Banknote} className="col-span-2 pt-4 border-t border-slate-100 dark:border-slate-800" />
              </div>
            </TabsContent>

            <TabsContent value="participantes" className="mt-0 outline-none space-y-6">
              <div className="grid grid-cols-2 gap-y-6 gap-x-12">
                <InfoField label="Principal Envolvido" value={transaction.beneficiario_pagador} icon={User} className="col-span-2" />
                <InfoField label="Nome do Pagador" value={transaction.nomePagador} icon={User} />
                <InfoField label="CPF/CNPJ Pagador" value={transaction.cpfCnpjPagador} icon={FileText} />
                <InfoField label="Nome do Recebedor" value={transaction.nomeRecebedor} icon={User} />
                <InfoField label="CPF/CNPJ Recebedor" value={transaction.cpfCnpjRecebedor} icon={FileText} />
                <InfoField label="Estabelecimento" value={transaction.estabelecimento} icon={CreditCard} className="col-span-2" />
                <InfoField label="Agência" value={transaction.agencia} icon={Hash} />
                <InfoField label="Conta Bancária" value={transaction.contaBancaria} icon={CreditCard} />
                <InfoField label="Chave PIX" value={transaction.chavePix} icon={Tag} className="col-span-2" />
              </div>
            </TabsContent>

            <TabsContent value="tecnico" className="mt-0 outline-none space-y-6">
              <div className="grid grid-cols-1 gap-y-6">
                <InfoField label="ID no Extrato (Interno)" value={transaction.idextrato} icon={Hash} />
                <InfoField label="ID da Transação (Banco)" value={transaction.idTransacao} icon={ExternalLink} />
                <InfoField label="EndToEnd ID (PIX)" value={transaction.endToEndId} icon={ExternalLink} />
                <InfoField label="Código de Barras" value={transaction.codigoBarras} icon={Hash} />
                <InfoField label="Linha Digitável" value={transaction.linhaDigitavel} icon={FileText} />
                <div className="grid grid-cols-2 gap-12">
                  <InfoField label="Nosso Número" value={transaction.nossoNumero} icon={Hash} />
                  <InfoField label="Seu Número" value={transaction.seuNumero} icon={Hash} />
                </div>
                <InfoField label="Origem da Movimentação" value={transaction.origemMovimentacao} icon={History} />
              </div>
            </TabsContent>

            <TabsContent value="conciliacao" className="mt-0 outline-none space-y-6">
              <div className="grid grid-cols-2 gap-y-6 gap-x-12">
                <InfoField label="Status Atual" value={isConciliado ? 'CONCILIADO' : 'PENDENTE'} icon={CheckCircle2} className="col-span-2" />
                <InfoField label="Categoria" value={categoriaNome} icon={Tag} />
                <InfoField label="Caixinha / Destino" value={caixinhaNome} icon={Banknote} />
                <InfoField label="Tag da Transação" value={transaction.tag} icon={Tag} className="col-span-2" />
                <InfoField label="Regra Aplicada" value={transaction.regra ? 'ID #' + transaction.regra : null} icon={Settings} className="col-span-2" />
                <InfoField label="Data de Emissão" value={transaction.dataEmissao} icon={Calendar} />
                <InfoField label="Data de Vencimento" value={transaction.dataVencimento} icon={Calendar} />
                <InfoField label="Data Limite" value={transaction.dataLimite} icon={Calendar} />
              </div>
            </TabsContent>
          </div>
        </Tabs>

        <DialogFooter className="p-6 bg-slate-50/50 dark:bg-slate-900/50 border-t border-slate-100 dark:border-slate-800">
          <div className="flex w-full items-center justify-between">
            <Button
              variant="ghost"
              onClick={() => onOpenChange(false)}
              className="text-[10px] font-black uppercase tracking-widest text-slate-400 hover:text-slate-900 dark:hover:text-white"
            >
              Fechar Detalhes
            </Button>
            
            {onEditTransaction && (
              <Button
                className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl h-11 px-6 shadow-lg shadow-blue-500/20 transition-all font-black text-[10px] uppercase tracking-widest"
                onClick={() => {
                  onEditTransaction(transaction);
                  onOpenChange(false);
                }}
              >
                <Edit size={16} className="mr-2" />
                Editar Transação
              </Button>
            )}
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
