import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { 
  Loader2, 
  ChevronRight, 
  ChevronDown, 
  User, 
  Tag, 
  Receipt,
  ArrowUpRight,
  ArrowDownRight,
  Wallet
} from 'lucide-react';
import { extratoService } from '@/services/extratoService';
import { formatCurrency, formatDate } from '../utils/dateUtils';
import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

const CaixinhaDetailsModal = ({ isOpen, onClose, caixinhaId, caixinhaName, mes, ano }) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);
  const [expandedCategories, setExpandedCategories] = useState({});
  const [expandedBeneficiaries, setExpandedBeneficiaries] = useState({});

  useEffect(() => {
    if (isOpen && caixinhaId) {
      loadDetails();
    } else {
      setData(null);
      setExpandedCategories({});
      setExpandedBeneficiaries({});
    }
  }, [isOpen, caixinhaId, mes, ano]);

  const loadDetails = async () => {
    try {
      setLoading(true);
      const result = await extratoService.getCaixinhaDetalhada({
        caixinha: caixinhaId,
        mes,
        ano
      });
      setData(result);
    } catch (error) {
      console.error('Erro ao carregar detalhes da caixinha:', error);
    } finally {
      setLoading(false);
    }
  };

  const toggleCategory = (catName) => {
    setExpandedCategories(prev => ({
      ...prev,
      [catName]: !prev[catName]
    }));
  };

  const toggleBeneficiary = (benefKey) => {
    setExpandedBeneficiaries(prev => ({
      ...prev,
      [benefKey]: !prev[benefKey]
    }));
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-5xl h-[90vh] flex flex-col p-0 bg-white dark:bg-slate-900 border-none overflow-hidden sm:rounded-2xl">
        <DialogHeader className="p-6 bg-slate-50 dark:bg-slate-800/50 border-b border-slate-200 dark:border-slate-800 shrink-0">
          <div className="flex items-center justify-between">
            <div>
              <DialogTitle className="text-2xl font-bold text-slate-900 dark:text-white flex items-center gap-3">
                <div className="p-2 bg-emerald-500/10 rounded-xl">
                  <Wallet className="w-6 h-6 text-emerald-600 dark:text-emerald-400" />
                </div>
                {caixinhaName || data?.caixinha || 'Detalhes da Caixinha'}
              </DialogTitle>
              <DialogDescription className="text-slate-500 dark:text-slate-400 mt-1 font-medium">
                Detalhamento por Categoria e Beneficiário • {mes}/{ano}
              </DialogDescription>
            </div>
            
            {data && (
              <div className="flex items-center gap-6">
                <div className="text-right">
                  <p className="text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-1">Total Movimentado</p>
                  <p className="text-xl font-bold text-emerald-600 dark:text-emerald-400 font-mono">
                    {formatCurrency(data.valor_total || 0)}
                  </p>
                </div>
                <div className="text-right">
                  <p className="text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-1">Lançamentos</p>
                  <Badge variant="secondary" className="bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-200 font-bold">
                    {data.total_transacoes || (data.categorias || []).reduce((acc, cat) => acc + (cat.total_transacoes || 0), 0)}
                  </Badge>
                </div>
              </div>
            )}
          </div>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto p-6 scrollbar-thin scrollbar-thumb-slate-200 dark:scrollbar-thumb-slate-800">
          {loading ? (
            <div className="flex flex-col items-center justify-center h-full gap-4 text-slate-500">
              <Loader2 className="w-10 h-10 animate-spin text-emerald-500" />
              <p className="text-sm font-semibold animate-pulse">Carregando detalhes...</p>
            </div>
          ) : !data || !data.categorias || data.categorias.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full gap-3 text-slate-400">
               <Receipt className="w-12 h-12 opacity-20" />
               <p className="text-lg font-medium">Nenhuma movimentação encontrada</p>
            </div>
          ) : (
            <div className="space-y-4">
              {(data?.categorias || []).map((cat, idx) => (
                <div key={idx} className="border border-slate-200 dark:border-slate-800 rounded-xl overflow-hidden bg-white dark:bg-slate-900 shadow-sm transition-all duration-300">
                  <button
                    onClick={() => toggleCategory(cat.categoria)}
                    className="w-full flex items-center justify-between p-4 hover:bg-slate-50 dark:hover:bg-slate-800/30 transition-colors group"
                  >
                    <div className="flex items-center gap-4">
                      <div className={cn(
                        "p-2 rounded-lg transition-colors group-hover:bg-cyan-500/10",
                        expandedCategories[cat.categoria] ? "bg-cyan-500/10" : "bg-slate-100 dark:bg-slate-800"
                      )}>
                        <Tag className={cn(
                          "w-4 h-4 transition-colors",
                          expandedCategories[cat.categoria] ? "text-cyan-600 dark:text-cyan-400" : "text-slate-500"
                        )} />
                      </div>
                      <div className="text-left">
                        <span className="text-sm font-bold text-slate-900 dark:text-white uppercase tracking-tight">
                          {cat.categoria || "Sem Categoria"}
                        </span>
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-[10px] text-slate-400 font-medium">
                            {cat.total_transacoes || (cat.transacoes?.length || 0)} lançamentos
                          </span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-6">
                      <div className="text-right">
                        <p className="text-sm font-bold text-slate-900 dark:text-white font-mono">
                          {formatCurrency(cat.valor_total)}
                        </p>
                      </div>
                      {expandedCategories[cat.categoria] ? <ChevronDown className="w-4 h-4 text-slate-400" /> : <ChevronRight className="w-4 h-4 text-slate-400" />}
                    </div>
                  </button>

                  {expandedCategories[cat.categoria] && (
                    <div className="border-t border-slate-100 dark:border-slate-800 bg-slate-50/30 dark:bg-slate-900/50 p-4 space-y-3">
                      {/* Suporte para novas estruturas (subgrupos OU flat transacoes) OU estrutura antiga (beneficiarios) */}
                      {cat.subgrupos && cat.subgrupos.length > 0 ? (
                        cat.subgrupos.map((sub, sIdx) => {
                          const subKey = `${cat.categoria}-${sub.nome_agrupamento}`;
                          return (
                            <div key={sIdx} className="bg-white dark:bg-slate-800/50 rounded-lg border border-slate-100 dark:border-slate-700 overflow-hidden shadow-sm">
                              <button
                                onClick={() => toggleBeneficiary(subKey)}
                                className="w-full flex items-center justify-between p-3 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"
                              >
                                <div className="flex items-center gap-3">
                                  <User className="w-4 h-4 text-slate-400" />
                                  <span className="text-xs font-semibold text-slate-700 dark:text-slate-300">
                                    {sub.nome_agrupamento || 'Não informado'}
                                  </span>
                                  <Badge variant="outline" className="text-[9px] font-bold border-slate-200 text-slate-500 h-4">
                                    {sub.total_transacoes || (sub.transacoes?.length || 0)}
                                  </Badge>
                                </div>
                                <div className="flex items-center gap-4">
                                  <span className="text-xs font-bold text-slate-600 dark:text-slate-400 font-mono">
                                    {formatCurrency(sub.valor_total || 0)}
                                  </span>
                                  {expandedBeneficiaries[subKey] ? <ChevronDown className="w-3 h-3 text-slate-400" /> : <ChevronRight className="w-3 h-3 text-slate-400" />}
                                </div>
                              </button>

                              {expandedBeneficiaries[subKey] && (
                                <div className="p-2 bg-slate-50/50 dark:bg-slate-900/30">
                                  <Table>
                                    <TableHeader>
                                      <TableRow className="hover:bg-transparent border-slate-200 dark:border-slate-800">
                                        <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase">Data</TableHead>
                                        <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase">Descrição</TableHead>
                                        <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase">Tipo</TableHead>
                                        <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase text-right">Valor</TableHead>
                                      </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                      {(sub.transacoes || []).map((t, tIdx) => (
                                        <TableRow key={tIdx} className="hover:bg-white dark:hover:bg-slate-800 border-slate-100 dark:border-slate-800/50">
                                          <TableCell className="text-[11px] py-2 text-slate-500 font-medium whitespace-nowrap">
                                            {t.dataEntrada || t.data || ''}
                                          </TableCell>
                                          <TableCell className="text-[11px] py-2 text-slate-700 dark:text-slate-300 font-medium max-w-[200px] truncate">
                                            {t.descricao}
                                          </TableCell>
                                          <TableCell className="text-[11px] py-2">
                                            <div className="flex items-center gap-1">
                                              {t.tipoOperacao === 'C' ? 
                                                <ArrowUpRight className="w-3 h-3 text-emerald-500" /> : 
                                                <ArrowDownRight className="w-3 h-3 text-rose-500" />
                                              }
                                              <span className={cn(
                                                "font-bold",
                                                t.tipoOperacao === 'C' ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
                                              )}>
                                                {t.tipoOperacao === 'C' ? 'Entrada' : 'Saída'}
                                              </span>
                                            </div>
                                          </TableCell>
                                          <TableCell className={cn(
                                            "text-[11px] py-2 text-right font-bold font-mono",
                                            t.tipoOperacao === 'C' ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
                                          )}>
                                            {formatCurrency(t.valor)}
                                          </TableCell>
                                        </TableRow>
                                      ))}
                                    </TableBody>
                                  </Table>
                                </div>
                              )}
                            </div>
                          );
                        })
                      ) : cat.transacoes && cat.transacoes.length > 0 ? (
                        <div className="p-2 bg-white dark:bg-slate-800/50 rounded-lg border border-slate-100 dark:border-slate-700 overflow-hidden shadow-sm">
                          <Table>
                            <TableHeader>
                              <TableRow className="hover:bg-transparent border-slate-200 dark:border-slate-800">
                                <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase">Data</TableHead>
                                <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase">Descrição</TableHead>
                                <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase">Tipo</TableHead>
                                <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase text-right">Valor</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {cat.transacoes.map((t, tIdx) => (
                                <TableRow key={tIdx} className="hover:bg-white dark:hover:bg-slate-800 border-slate-100 dark:border-slate-800/50">
                                  <TableCell className="text-[11px] py-2 text-slate-500 font-medium whitespace-nowrap">
                                    {t.dataEntrada || t.data || ''}
                                  </TableCell>
                                  <TableCell className="text-[11px] py-2 text-slate-700 dark:text-slate-300 font-medium max-w-[200px] truncate">
                                    {t.descricao}
                                  </TableCell>
                                  <TableCell className="text-[11px] py-2">
                                    <div className="flex items-center gap-1">
                                      {t.tipoOperacao === 'C' ? 
                                        <ArrowUpRight className="w-3 h-3 text-emerald-500" /> : 
                                        <ArrowDownRight className="w-3 h-3 text-rose-500" />
                                      }
                                      <span className={cn(
                                        "font-bold",
                                        t.tipoOperacao === 'C' ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
                                      )}>
                                        {t.tipoOperacao === 'C' ? 'Entrada' : 'Saída'}
                                      </span>
                                    </div>
                                  </TableCell>
                                  <TableCell className={cn(
                                    "text-[11px] py-2 text-right font-bold font-mono",
                                    t.tipoOperacao === 'C' ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
                                  )}>
                                    {formatCurrency(t.valor)}
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      ) : (cat.beneficiarios || []).map((benef, bIdx) => {
                        const benefKey = `${cat.categoria}-${benef.beneficiario}`;
                        return (
                          <div key={bIdx} className="bg-white dark:bg-slate-800/50 rounded-lg border border-slate-100 dark:border-slate-700 overflow-hidden shadow-sm">
                            <button
                              onClick={() => toggleBeneficiary(benefKey)}
                              className="w-full flex items-center justify-between p-3 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"
                            >
                              <div className="flex items-center gap-3">
                                <User className="w-4 h-4 text-slate-400" />
                                <span className="text-xs font-semibold text-slate-700 dark:text-slate-300">
                                  {benef.beneficiario || 'Não informado'}
                                </span>
                                <Badge variant="outline" className="text-[9px] font-bold border-slate-200 text-slate-500 h-4">
                                  {benef.total_transacoes}
                                </Badge>
                              </div>
                              <div className="flex items-center gap-4">
                                <span className="text-xs font-bold text-slate-600 dark:text-slate-400 font-mono">
                                  {formatCurrency(benef.valor_total)}
                                </span>
                                {expandedBeneficiaries[benefKey] ? <ChevronDown className="w-3 h-3 text-slate-400" /> : <ChevronRight className="w-3 h-3 text-slate-400" />}
                              </div>
                            </button>

                            {expandedBeneficiaries[benefKey] && (
                              <div className="p-2 bg-slate-50/50 dark:bg-slate-900/30">
                                <Table>
                                  <TableHeader>
                                    <TableRow className="hover:bg-transparent border-slate-200 dark:border-slate-800">
                                      <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase">Data</TableHead>
                                      <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase">Descrição</TableHead>
                                      <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase">Tipo</TableHead>
                                      <TableHead className="text-[10px] h-8 font-bold text-slate-500 uppercase text-right">Valor</TableHead>
                                    </TableRow>
                                  </TableHeader>
                                  <TableBody>
                                    {(benef.transacoes || []).map((t, tIdx) => (
                                      <TableRow key={tIdx} className="hover:bg-white dark:hover:bg-slate-800 border-slate-100 dark:border-slate-800/50">
                                        <TableCell className="text-[11px] py-2 text-slate-500 font-medium whitespace-nowrap">
                                          {t.dataEntrada || t.data || ''}
                                        </TableCell>
                                        <TableCell className="text-[11px] py-2 text-slate-700 dark:text-slate-300 font-medium max-w-[200px] truncate">
                                          {t.descricao}
                                        </TableCell>
                                        <TableCell className="text-[11px] py-2">
                                          <div className="flex items-center gap-1">
                                            {t.tipoOperacao === 'C' ? 
                                              <ArrowUpRight className="w-3 h-3 text-emerald-500" /> : 
                                              <ArrowDownRight className="w-3 h-3 text-rose-500" />
                                            }
                                            <span className={cn(
                                              "font-bold",
                                              t.tipoOperacao === 'C' ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
                                            )}>
                                              {t.tipoOperacao === 'C' ? 'Entrada' : 'Saída'}
                                            </span>
                                          </div>
                                        </TableCell>
                                        <TableCell className={cn(
                                          "text-[11px] py-2 text-right font-bold font-mono",
                                          t.tipoOperacao === 'C' ? "text-emerald-600 dark:text-emerald-400" : "text-rose-600 dark:text-rose-400"
                                        )}>
                                          {formatCurrency(t.valor)}
                                        </TableCell>
                                      </TableRow>
                                    ))}
                                  </TableBody>
                                </Table>
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default CaixinhaDetailsModal;
