import React from 'react';
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { 
  CheckCheck, 
  AlertCircle, 
  List, 
  Box, 
  Tags, 
  ArrowLeft,
  ChevronRight,
  Plus,
  Pencil,
  Trash2
} from 'lucide-react';
import useConciliacao from '../../../hooks/useConciliacao';
import Modal from '@/components/shared/Modal';
import { CategoryForm, CaixinhaForm, RuleForm, ReconciliationForm } from './Forms';

const FilterButton = ({ active, icon: Icon, label, onClick }) => (
  <button
    onClick={onClick}
    className={`
      flex items-center gap-2 px-6 py-2.5 text-[10px] font-black uppercase tracking-[0.15em] transition-all duration-300 rounded-xl
      ${active 
        ? 'bg-white text-emerald-600 shadow-lg shadow-emerald-100 ring-1 ring-emerald-100 border border-emerald-200' 
        : 'text-slate-500 hover:text-emerald-500 hover:bg-emerald-50/50'
      }
    `}
  >
    <Icon className={`w-3.5 h-3.5 ${active ? 'text-emerald-500' : ''}`} />
    {label}
  </button>
);

const ConciliacaoTables = () => {
  const { 
    activeFilter, 
    setActiveFilter, 
    viewLevel, 
    navigateBack, 
    navigateDrillDown,
    drillDownPath,
    bankTransactions,
    rules,
    categories,
    caixinhas,
    addCategory,
    addCaixinha,
    addRule,
    updateCategory,
    updateCaixinha,
    updateRule,
    deleteCategory,
    deleteCaixinha,
    deleteRule,
    getAggregatedItems 
  } = useConciliacao();

  const items = getAggregatedItems();

  const [isCategoryModalOpen, setIsCategoryModalOpen] = React.useState(false);
  const [isCaixinhaModalOpen, setIsCaixinhaModalOpen] = React.useState(false);
  const [isRuleModalOpen, setIsRuleModalOpen] = React.useState(false);
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  
  const [editingCategory, setEditingCategory] = React.useState(null);
  const [editingCaixinha, setEditingCaixinha] = React.useState(null);
  const [editingRule, setEditingRule] = React.useState(null);
  const [isReconciliationModalOpen, setIsReconciliationModalOpen] = React.useState(false);
  const [selectedTransaction, setSelectedTransaction] = React.useState(null);

  const handleOpenCategoryModal = (cat = null) => { setEditingCategory(cat); setIsCategoryModalOpen(true); };
  const handleOpenCaixinhaModal = (cax = null) => { setEditingCaixinha(cax); setIsCaixinhaModalOpen(true); };
  const handleOpenRuleModal = (rule = null) => { setEditingRule(rule); setIsRuleModalOpen(true); };
  
  const handleOpenReconciliationModal = (transaction) => {
    setSelectedTransaction(transaction);
    setIsReconciliationModalOpen(true);
  };

  const handleSwitchToRule = (prefillData) => {
    setIsReconciliationModalOpen(false);
    setEditingRule(prefillData);
    setIsRuleModalOpen(true);
  };

  const handleSubmitCategory = async (data) => {
    setIsSubmitting(true);
    const res = editingCategory ? await updateCategory(data) : await addCategory(data);
    setIsSubmitting(false);
    if (res.success) setIsCategoryModalOpen(false);
  };

  const handleSubmitCaixinha = async (data) => {
    setIsSubmitting(true);
    const res = editingCaixinha ? await updateCaixinha(data) : await addCaixinha(data);
    setIsSubmitting(false);
    if (res.success) setIsCaixinhaModalOpen(false);
  };

  const handleSubmitRule = async (data) => {
    setIsSubmitting(true);
    const res = editingRule?.id ? await updateRule(data) : await addRule(data);
    setIsSubmitting(false);
    if (res.success) setIsRuleModalOpen(false);
  };

  const handleSubmitReconciliation = async (data) => {
    setIsSubmitting(true);
    const res = await useConciliacao.getState().reconcileTransaction(data);
    setIsSubmitting(false);
    if (res.success) setIsReconciliationModalOpen(false);
  };

  const renderContent = () => {
    switch (activeFilter) {
      case 'Regras': return <RulesTable rules={rules} onEdit={handleOpenRuleModal} onDelete={deleteRule} />;
      case 'Categoria': return <CategoriesTable categories={categories} onEdit={handleOpenCategoryModal} onDelete={deleteCategory} />;
      case 'Caixinhas': return <CaixinhasTable caixinhas={caixinhas} onEdit={handleOpenCaixinhaModal} onDelete={deleteCaixinha} />;
      case 'Sem_Regra': return <PendingTable transactions={bankTransactions.filter(t => !t.isReconciled)} onReconcile={handleOpenReconciliationModal} />;
      default: return <TransactionsTable items={items} level={viewLevel} onDrillDown={navigateDrillDown} />;
    }
  };

  return (
    <div className="flex flex-col gap-6 animate-in fade-in duration-700">
      <div className="flex flex-wrap gap-2 p-1.5 bg-white/80 backdrop-blur-xl rounded-2xl border border-emerald-100 items-center shadow-lg shadow-emerald-50/50">
        <FilterButton active={activeFilter === 'Regra'} icon={CheckCheck} label="Cruzamento" onClick={() => setActiveFilter('Regra')} />
        <FilterButton active={activeFilter === 'Sem_Regra'} icon={AlertCircle} label="Pendentes" onClick={() => setActiveFilter('Sem_Regra')} />
        <div className="w-px h-6 bg-emerald-200 mx-2" />
        <div className="flex gap-1 bg-slate-50 rounded-xl border border-slate-200 p-0.5">
          <FilterButton active={activeFilter === 'Regras'} icon={List} label="Regras" onClick={() => setActiveFilter('Regras')} />
          <FilterButton active={activeFilter === 'Caixinhas'} icon={Box} label="Cofres" onClick={() => setActiveFilter('Caixinhas')} />
          <FilterButton active={activeFilter === 'Categoria'} icon={Tags} label="Categorias" onClick={() => setActiveFilter('Categoria')} />
        </div>
      </div>

      <div className="bg-white rounded-2xl border border-emerald-100 shadow-xl shadow-emerald-50/20 overflow-hidden group">
        <div className="p-4 px-6 border-b border-emerald-100 flex justify-between items-center bg-emerald-50/20">
          <div className="flex items-center gap-4">
            {viewLevel > 0 && (
                <Button variant="ghost" size="icon" onClick={navigateBack} className="rounded-xl h-8 w-8 hover:bg-emerald-50 text-emerald-600">
                    <ArrowLeft className="w-4 h-4" />
                </Button>
            )}
            <div className="flex flex-col">
                <h5 className="font-black text-slate-700 text-xs uppercase tracking-widest leading-none">
                    {viewLevel === 0 ? "Detalhamento de Fluxo" : "Broca de Dados (Drill-down)"}
                </h5>
                <p className="text-[10px] font-bold text-slate-400 mt-1 uppercase tracking-tighter">
                    {viewLevel === 0 ? "Visão consolidada por entidade" : `Path: ${drillDownPath.join(' > ')}`}
                </p>
            </div>
          </div>
          <div className="flex gap-2">
            {activeFilter === 'Regras' && <Button size="sm" onClick={() => handleOpenRuleModal()} className="gap-2 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white px-4 text-[10px] font-black uppercase tracking-widest h-9 shadow-lg shadow-emerald-500/20"><Plus className="w-3.5 h-3.5"/> Criar Regra</Button>}
            {activeFilter === 'Categoria' && <Button size="sm" onClick={() => handleOpenCategoryModal()} className="gap-2 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white px-4 text-[10px] font-black uppercase tracking-widest h-9 shadow-lg shadow-emerald-500/20"><Plus className="w-3.5 h-3.5"/> Tags (Cats)</Button>}
            {activeFilter === 'Caixinhas' && <Button size="sm" onClick={() => handleOpenCaixinhaModal()} className="gap-2 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white px-4 text-[10px] font-black uppercase tracking-widest h-9 shadow-lg shadow-emerald-500/20"><Plus className="w-3.5 h-3.5"/> Novo Cofre</Button>}
          </div>
        </div>
        <div className="p-0 overflow-x-auto">{renderContent()}</div>
      </div>

      <Modal isOpen={isCategoryModalOpen} onClose={() => setIsCategoryModalOpen(false)} title={editingCategory ? "Editar Categoria" : "Criar Nova Categoria"}>
        <CategoryForm initialData={editingCategory} onSubmit={handleSubmitCategory} onCancel={() => setIsCategoryModalOpen(false)} isLoading={isSubmitting} />
      </Modal>
      <Modal isOpen={isCaixinhaModalOpen} onClose={() => setIsCaixinhaModalOpen(false)} title={editingCaixinha ? "Editar Caixinha" : "Criar Nova Caixinha"}>
        <CaixinhaForm initialData={editingCaixinha} onSubmit={handleSubmitCaixinha} onCancel={() => setIsCaixinhaModalOpen(false)} isLoading={isSubmitting} />
      </Modal>
      <Modal isOpen={isRuleModalOpen} onClose={() => setIsRuleModalOpen(false)} title={editingRule?.id ? "Editar Regra" : "Criar Nova Regra"}>
        <RuleForm categories={categories} caixinhas={caixinhas} initialData={editingRule} onSubmit={handleSubmitRule} onCancel={() => setIsRuleModalOpen(false)} isLoading={isSubmitting} />
      </Modal>

      <Modal isOpen={isReconciliationModalOpen} onClose={() => setIsReconciliationModalOpen(false)} title="Conciliar Transação Especial">
        <ReconciliationForm 
          transaction={selectedTransaction} 
          categories={categories} 
          caixinhas={caixinhas} 
          onSubmit={handleSubmitReconciliation} 
          onCancel={() => setIsReconciliationModalOpen(false)} 
          onSwitchToRule={handleSwitchToRule}
          isLoading={isSubmitting} 
        />
      </Modal>
    </div>
  );
};

const TransactionsTable = ({ items, level, onDrillDown }) => (
  <Table>
    <TableHeader className="bg-emerald-50/50 sticky top-0">
        <TableRow className="border-emerald-100 hover:bg-transparent">
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 pl-6">{level === 2 ? "Data" : "Entidade / Agrupamento"}</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-center">{level === 2 ? "Situação" : "Volume"}</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-right">Previsto (ERP)</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-right">Realizado (Banco)</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-right pr-6">Diferença</TableHead>
        </TableRow>
    </TableHeader>
    <TableBody>
      {items.length === 0 ? (
        <TableRow>
          <TableCell colSpan={5} className="text-center py-20 opacity-40 text-[10px] font-black uppercase tracking-widest text-slate-400">Nenhum dado neste nível</TableCell>
        </TableRow>
      ) : (
        items.map((item, idx) => {
          const isTransaction = item.isTransaction;
          const label = isTransaction ? item.name : item.name;
          const amount = item.amount;
          const count = item.count;

          return (
            <TableRow 
              key={idx} 
              className={`cursor-pointer border-emerald-100/50 hover:bg-emerald-50/50 transition-all duration-200 group ${isTransaction ? 'pointer-events-none' : ''}`}
              onClick={() => !isTransaction && onDrillDown(item.name)}
            >
              <TableCell className="py-4 pl-6">
                  <div className="flex items-center gap-2">
                    {!isTransaction && <ChevronRight className="w-3.5 h-3.5 text-slate-400 group-hover:text-emerald-500 group-hover:translate-x-1 transition-all" />}
                    <div className="flex flex-col">
                      <span className="text-sm font-bold text-slate-700 group-hover:text-emerald-600 transition-colors uppercase tracking-tight">{label}</span>
                      {isTransaction && <span className="text-[9px] font-black text-slate-400 uppercase tracking-tighter mt-0.5">Operação Individual</span>}
                    </div>
                  </div>
              </TableCell>
              <TableCell className="text-center">
                {isTransaction ? (
                  <Badge variant="outline" className="bg-emerald-100 text-emerald-700 border-emerald-200 text-[9px] font-black uppercase tracking-widest">Liquidado</Badge>
                ) : (
                  <span className="font-mono text-xs text-slate-500 font-bold">{count}</span>
                )}
              </TableCell>
              <TableCell className="text-right font-mono text-xs text-slate-500 font-medium">
                {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(item.predicted || 0)}
              </TableCell>
              <TableCell className="text-right font-mono text-sm font-black">
                <span className={amount < 0 ? 'text-rose-500' : 'text-emerald-600'}>
                  {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(amount)}
                </span>
              </TableCell>
              <TableCell className="text-right font-mono text-xs text-slate-400 pr-6">
                R$ 0,00
              </TableCell>
            </TableRow>
          );
        })
      )}
    </TableBody>
  </Table>
);

const RulesTable = ({ rules, onEdit, onDelete }) => (
  <Table>
    <TableHeader className="bg-emerald-50/50 sticky top-0">
        <TableRow className="border-emerald-100 hover:bg-transparent">
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 pl-6">Diretriz da Regra</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10">Condição Técnica</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10">Vínculo</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-right pr-6">Controles</TableHead>
        </TableRow>
    </TableHeader>
    <TableBody>
      {rules.map(rule => (
        <TableRow key={rule.id} className="border-emerald-100/50 hover:bg-emerald-50/50 transition-all duration-200 group">
          <TableCell className="py-4 pl-6 font-bold text-slate-700 text-sm">{rule.name}</TableCell>
          <TableCell className="py-4 font-mono text-[11px] text-emerald-600 font-bold italic">"{rule.condition}"</TableCell>
          <TableCell className="py-4"><Badge variant="outline" className="bg-white border-slate-200 text-slate-600 text-[10px] font-bold px-2">{rule.categoryId}</Badge></TableCell>
          <TableCell className="py-4 text-right pr-6">
            <div className="flex gap-1 justify-end opacity-0 group-hover:opacity-100 transition-opacity">
              <Button variant="ghost" size="icon" className="h-8 w-8 rounded-lg hover:bg-emerald-50 text-slate-400 hover:text-emerald-600" onClick={() => onEdit(rule)}><Pencil className="w-3.5 h-3.5" /></Button>
              <Button variant="ghost" size="icon" className="h-8 w-8 rounded-lg hover:bg-rose-50 text-slate-400 hover:text-rose-500" onClick={() => onDelete(rule.id)}><Trash2 className="w-3.5 h-3.5" /></Button>
            </div>
          </TableCell>
        </TableRow>
      ))}
    </TableBody>
  </Table>
);

const CategoriesTable = ({ categories, onEdit, onDelete }) => (
  <Table>
    <TableHeader className="bg-emerald-50/50 sticky top-0">
        <TableRow className="border-emerald-100 hover:bg-transparent">
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 pl-6">Título da Categoria</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10">Identificador</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-right pr-6">Controles</TableHead>
        </TableRow>
    </TableHeader>
    <TableBody>
      {categories.map(cat => (
        <TableRow key={cat.id} className="border-emerald-100/50 hover:bg-emerald-50/50 transition-all duration-200 group">
          <TableCell className="py-4 pl-6 font-bold text-slate-700 text-sm">{cat.name}</TableCell>
          <TableCell className="py-4 font-mono text-[11px] text-slate-500 font-bold">#{cat.id}</TableCell>
          <TableCell className="py-4 text-right pr-6">
            <div className="flex gap-1 justify-end opacity-0 group-hover:opacity-100 transition-opacity">
              <Button variant="ghost" size="icon" className="h-8 w-8 rounded-lg hover:bg-emerald-50 text-slate-400 hover:text-emerald-600" onClick={() => onEdit(cat)}><Pencil className="w-3.5 h-3.5" /></Button>
              <Button variant="ghost" size="icon" className="h-8 w-8 rounded-lg hover:bg-rose-50 text-slate-400 hover:text-rose-500" onClick={() => onDelete(cat.id)}><Trash2 className="w-3.5 h-3.5" /></Button>
            </div>
          </TableCell>
        </TableRow>
      ))}
    </TableBody>
  </Table>
);

const CaixinhasTable = ({ caixinhas, onEdit, onDelete }) => (
  <Table>
    <TableHeader className="bg-emerald-50/50 sticky top-0">
        <TableRow className="border-emerald-100 hover:bg-transparent">
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 pl-6">Nome do Cofre</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10">Token ID</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-right pr-6">Controles</TableHead>
        </TableRow>
    </TableHeader>
    <TableBody>
      {caixinhas.map(item => (
        <TableRow key={item.id} className="border-emerald-100/50 hover:bg-emerald-50/50 transition-all duration-200 group">
          <TableCell className="py-4 pl-6 font-bold text-slate-700 text-sm">{item.name}</TableCell>
          <TableCell className="py-4 font-mono text-[11px] text-slate-500 font-bold">#{item.id}</TableCell>
          <TableCell className="py-4 text-right pr-6">
            <div className="flex gap-1 justify-end opacity-0 group-hover:opacity-100 transition-opacity">
              <Button variant="ghost" size="icon" className="h-8 w-8 rounded-lg hover:bg-emerald-50 text-slate-400 hover:text-emerald-600" onClick={() => onEdit(item)}><Pencil className="w-3.5 h-3.5" /></Button>
              <Button variant="ghost" size="icon" className="h-8 w-8 rounded-lg hover:bg-rose-50 text-slate-400 hover:text-rose-500" onClick={() => onDelete(item.id)}><Trash2 className="w-3.5 h-3.5" /></Button>
            </div>
          </TableCell>
        </TableRow>
      ))}
    </TableBody>
  </Table>
);

const PendingTable = ({ transactions, onReconcile }) => (
  <Table>
    <TableHeader className="bg-emerald-50/50 sticky top-0">
        <TableRow className="border-emerald-100 hover:bg-transparent">
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 pl-6 w-32">Data de Entrada</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10">Descrição da Pendência</TableHead>
            <TableHead className="text-slate-500 font-bold text-[10px] uppercase h-10 text-right pr-6">Montante Operado</TableHead>
        </TableRow>
    </TableHeader>
    <TableBody>
      {transactions.length === 0 ? (
        <TableRow>
          <TableCell colSpan={3} className="text-center py-20">
            <div className="flex flex-col items-center gap-2 opacity-40 text-slate-400 text-[10px] font-black uppercase tracking-widest">
              <CheckCheck className="w-12 h-12" />
              <p>Tudo Conciliado</p>
            </div>
          </TableCell>
        </TableRow>
      ) : (
        transactions.map(t => (
          <TableRow 
            key={t.id} 
            className="cursor-pointer border-emerald-100/50 hover:bg-rose-50/50 transition-all duration-200 group"
            onClick={() => onReconcile(t)}
          >
            <TableCell className="py-4 pl-6">
                <span className="text-[11px] font-mono font-bold text-slate-500 group-hover:text-rose-500 transition-colors">
                  {t.date.toLocaleDateString('pt-BR')}
                </span>
            </TableCell>
            <TableCell className="py-4">
                <div className="flex flex-col">
                  <span className="text-sm font-bold text-slate-700 group-hover:text-rose-600 transition-colors uppercase tracking-tight">{t.description}</span>
                  <span className="text-[9px] font-black text-slate-400 uppercase tracking-tighter mt-0.5">ID: {t.id}</span>
                </div>
            </TableCell>
            <TableCell className="text-right py-4 pr-6">
                <span className={`font-mono text-sm font-black ${t.amount < 0 ? 'text-rose-500' : 'text-emerald-600'}`}>
                  {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(t.amount)}
                </span>
            </TableCell>
          </TableRow>
        ))
      )}
    </TableBody>
  </Table>
);

export default ConciliacaoTables;
