import React, { useState } from 'react';
import { 
  Building2,
  FolderTree,
  Users,
  Plus,
  Edit,
  Trash2,
  Search,
  Settings
} from 'lucide-react';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { ArrowUpRight, ArrowDownRight } from 'lucide-react';
import ExcelTable from '../../components/ExcelTable';
import { formatCurrency } from '../../utils/dateUtils';
import { CategoryRulesPopup } from '../../components/CategoryRulesPopup';

export function GerenciamentoView({ state, actions }) {
    const { caixas, categorias, regras } = state;
    const [activeTab, setActiveTab] = useState('caixas');
    const [searchTerm, setSearchTerm] = useState('');
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [editingItem, setEditingItem] = useState(null);
    const [selectedCategoryForRules, setSelectedCategoryForRules] = useState(null);
    const [formData, setFormData] = useState({});


    const handleOpenDialog = (item = null, tipo) => {
        if (item) {
            setEditingItem({ ...item, tipo });
            if (tipo === 'categoria') {
                setFormData({ ...item, tipo: item.tipo ?? item.tipoMovimento ?? 'saida' });
            } else {
                setFormData(item);
            }
        } else {
            setEditingItem({ tipo });
            if (tipo === 'caixa') {
                setFormData({ nome: '', descricao: '', banco: '', agencia: '', conta: '' });
            } else if (tipo === 'categoria') {
                setFormData({ nome: '', descricao: '', cor: '#3b82f6', tipo: 'saida' });
            } else if (tipo === 'regra') {
                setFormData({ nome: '', condicao: '', categoriaId: '', caixaId: '', beneficiario: '' });
            }
        }
        setIsDialogOpen(true);
    };

    const handleSave = () => {
        if (!editingItem) return;
        
        if (editingItem.id) {
            if (editingItem.tipo === 'caixa') {
                actions.updateCaixa(editingItem.id, formData);
            } else if (editingItem.tipo === 'categoria') {
                actions.updateCategoria(editingItem.id, formData);
            } else if (editingItem.tipo === 'regra') {
                actions.updateRegra(editingItem.id, formData);
            }
        } else {
            if (editingItem.tipo === 'caixa') {
                actions.createCaixa(formData);
            } else if (editingItem.tipo === 'categoria') {
                actions.createCategoria(formData);
            } else if (editingItem.tipo === 'regra') {
                actions.createRegra(formData);
            }
        }
        setIsDialogOpen(false);
        setEditingItem(null);
    };

    const handleDelete = (id, tipo) => {
        if (window.confirm('Tem certeza que deseja excluir este item?')) {
            if (tipo === 'caixa') {
                actions.deleteCaixa(id);
            } else if (tipo === 'categoria') {
                actions.deleteCategoria(id);
            } else if (tipo === 'regra') {
                actions.deleteRegra(id);
            }
        }
    };

    const filteredCaixas = caixas.filter(c => 
        c.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        c.banco?.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const filteredCategorias = categorias.filter(c => 
        c.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        c.descricao?.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const filteredRegras = regras.filter(r => 
        r.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        r.condicao?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        r.beneficiario?.toLowerCase().includes(searchTerm.toLowerCase())
    );

    return (
        <div className="animate-in fade-in duration-700 space-y-6">
            <Card className="bg-white dark:bg-[#1e293b]/40 backdrop-blur-md border-slate-200 dark:border-slate-800 shadow-xl rounded-lg overflow-hidden">
                <CardHeader className="py-4 px-4 sm:px-6 border-b border-slate-200 dark:border-slate-800/50">
                    <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                        <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-xl bg-blue-500/10 dark:bg-blue-500/10 flex items-center justify-center border border-blue-500/20 shrink-0">
                                <Settings className="w-5 h-5 text-blue-500" />
                            </div>
                            <div>
                                <h3 className="font-bold text-slate-900 dark:text-white flex items-center gap-2 flex-wrap text-base sm:text-lg">
                                    Gerenciamento
                                </h3>
                                <p className="text-[10px] text-slate-500 dark:text-slate-400 font-medium uppercase tracking-wider hidden sm:block">
                                    Gerencie caixas, categorias e regras
                                </p>
                            </div>
                        </div>
                        <div className="flex items-center gap-2 w-full sm:w-auto">
                            <div className="relative group flex-1 sm:flex-initial">
                                <Search className="w-3.5 h-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 dark:text-slate-500" />
                                <Input 
                                    placeholder="Pesquisar..." 
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="bg-white dark:bg-slate-900/80 border-slate-200 dark:border-slate-700 pl-9 h-9 text-xs text-slate-900 dark:text-white placeholder:text-slate-400 dark:placeholder:text-slate-600 focus:border-blue-500/50 rounded-lg w-full sm:w-64"
                                />
                            </div>
                        </div>
                    </div>
                </CardHeader>
                <CardContent className="p-0">
                    <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
                        <div className="px-4 sm:px-6 pt-4 border-b border-slate-200 dark:border-slate-800">
                            <TabsList className="bg-transparent border-b-0 rounded-none h-auto p-0 gap-3 sm:gap-6">
                                <TabsTrigger 
                                    value="caixas" 
                                    className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-blue-600 data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 rounded-none pb-3 text-slate-600 dark:text-slate-400"
                                >
                                    <Building2 className="w-4 h-4 mr-2" />
                                    Caixas
                                </TabsTrigger>
                                <TabsTrigger 
                                    value="categorias" 
                                    className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-blue-600 data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 rounded-none pb-3 text-slate-600 dark:text-slate-400"
                                >
                                    <FolderTree className="w-4 h-4 mr-2" />
                                    Categorias
                                </TabsTrigger>
                                <TabsTrigger 
                                    value="regras" 
                                    className="text-xs sm:text-sm font-medium data-[state=active]:border-b-2 data-[state=active]:border-blue-600 data-[state=active]:text-blue-600 dark:data-[state=active]:text-blue-400 rounded-none pb-3 text-slate-600 dark:text-slate-400"
                                >
                                    <Users className="w-4 h-4 mr-2" />
                                    Regras
                                </TabsTrigger>
                            </TabsList>
                        </div>

                        <TabsContent value="caixas" className="m-0 p-4 sm:p-6">
                            <div className="mb-4 flex justify-end">
                                <Button 
                                    size="sm" 
                                    className="bg-blue-600 hover:bg-blue-700 text-white"
                                    onClick={() => handleOpenDialog(null, 'caixa')}
                                >
                                    <Plus className="w-4 h-4 mr-2" />
                                    Novo Caixa
                                </Button>
                            </div>
                            <div className="h-[500px]">
                                <ExcelTable
                                    data={filteredCaixas}
                                    columns={[
                                        {
                                            field: 'acoes',
                                            header: 'Ações',
                                            width: '150px',
                                            render: (row) => (
                                                <div className="flex items-center gap-2">
                                                    <Button
                                                        size="sm"
                                                        variant="ghost"
                                                        className="h-7 px-2 text-xs hover:bg-slate-200 dark:hover:bg-slate-700"
                                                        onClick={() => handleOpenDialog(row, 'caixa')}
                                                    >
                                                        <Edit className="w-3 h-3" />
                                                    </Button>
                                                    <Button
                                                        size="sm"
                                                        variant="ghost"
                                                        className="h-7 px-2 text-xs text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20"
                                                        onClick={() => handleDelete(row.id, 'caixa')}
                                                    >
                                                        <Trash2 className="w-3 h-3" />
                                                    </Button>
                                                </div>
                                            )
                                        },
                                        {
                                            field: 'nome',
                                            header: 'Nome',
                                            width: '200px',
                                            render: (row) => (
                                                <div className="flex items-center gap-2">
                                                    <Building2 className="w-4 h-4 text-blue-500" />
                                                    <span className="font-bold text-slate-900 dark:text-white">{row.nome}</span>
                                                </div>
                                            )
                                        },
                                        { field: 'descricao', header: 'Descrição', width: '250px' },
                                        { field: 'banco', header: 'Banco', width: '150px' },
                                        { field: 'agencia', header: 'Agência', width: '120px' },
                                        { field: 'conta', header: 'Conta', width: '150px' }
                                    ]}
                                    rowKey="id"
                                    pageSize={25}
                                />
                            </div>
                        </TabsContent>

                        <TabsContent value="categorias" className="m-0 p-4 sm:p-6">
                            <div className="mb-4 flex justify-end">
                                <Button 
                                    size="sm" 
                                    className="bg-blue-600 hover:bg-blue-700 text-white"
                                    onClick={() => handleOpenDialog(null, 'categoria')}
                                >
                                    <Plus className="w-4 h-4 mr-2" />
                                    Nova Categoria
                                </Button>
                            </div>
                            <div className="h-[500px]">
                                <ExcelTable
                                    data={filteredCategorias}
                                    columns={[
                                        {
                                            field: 'acoes',
                                            header: 'Ações',
                                            width: '150px',
                                            render: (row) => (
                                                <div className="flex items-center gap-2">
                                                    <Button
                                                        size="sm"
                                                        variant="ghost"
                                                        className="h-7 px-2 text-xs hover:bg-slate-200 dark:hover:bg-slate-700"
                                                        onClick={() => handleOpenDialog(row, 'categoria')}
                                                        title="Editar"
                                                    >
                                                        <Edit className="w-3 h-3" />
                                                    </Button>
                                                    <Button
                                                        size="sm"
                                                        variant="ghost"
                                                        className="h-7 px-2 text-xs text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:hover:bg-blue-900/20"
                                                        onClick={() => setSelectedCategoryForRules(row)}
                                                        title="Ver Regras"
                                                    >
                                                        <FolderTree className="w-3 h-3" />
                                                    </Button>
                                                    <Button
                                                        size="sm"
                                                        variant="ghost"
                                                        className="h-7 px-2 text-xs text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20"
                                                        onClick={() => handleDelete(row.id, 'categoria')}
                                                        title="Excluir"
                                                    >
                                                        <Trash2 className="w-3 h-3" />
                                                    </Button>
                                                </div>
                                            )
                                        },
                                        {
                                            field: 'nome',
                                            header: 'Nome',
                                            width: '200px',
                                            render: (row) => (
                                                <div className="flex items-center gap-2">
                                                    <div 
                                                        className="w-4 h-4 rounded"
                                                        style={{ backgroundColor: row.cor }}
                                                    />
                                                    <span className="font-bold text-slate-900 dark:text-white">{row.nome}</span>
                                                </div>
                                            )
                                        },
                                        { field: 'descricao', header: 'Descrição', width: '300px' },
                                        {
                                            field: 'cor',
                                            header: 'Cor',
                                            width: '100px',
                                            render: (row) => (
                                                <div className="flex items-center gap-2">
                                                    <div 
                                                        className="w-6 h-6 rounded border border-slate-300 dark:border-slate-700"
                                                        style={{ backgroundColor: row.cor }}
                                                    />
                                                    <span className="text-xs text-slate-600 dark:text-slate-400">{row.cor}</span>
                                                </div>
                                            )
                                        },
                                        {
                                            field: 'tipo',
                                            header: 'Entrada / Saída',
                                            width: '120px',
                                            render: (row) => {
                                                const t = row.tipo ?? row.tipoMovimento ?? 'saida';
                                                const isEntrada = t === 'entrada';
                                                return (
                                                    <Badge variant="outline" className={cn(
                                                        'text-[9px] font-bold',
                                                        isEntrada ? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20' : 'bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-500/20'
                                                    )}>
                                                        {isEntrada ? <ArrowUpRight className="w-3 h-3 mr-0.5 inline" /> : <ArrowDownRight className="w-3 h-3 mr-0.5 inline" />}
                                                        {isEntrada ? 'Entrada' : 'Saída'}
                                                    </Badge>
                                                );
                                            }
                                        }
                                    ]}
                                    rowKey="id"
                                    pageSize={25}
                                />
                            </div>
                        </TabsContent>

                        <TabsContent value="regras" className="m-0 p-4 sm:p-6">
                            <div className="mb-4 flex justify-end">
                                <Button 
                                    size="sm" 
                                    className="bg-blue-600 hover:bg-blue-700 text-white"
                                    onClick={() => handleOpenDialog(null, 'regra')}
                                >
                                    <Plus className="w-4 h-4 mr-2" />
                                    Nova Regra
                                </Button>
                            </div>
                            <div className="h-[500px]">
                                <ExcelTable
                                    data={filteredRegras}
                                    columns={[
                                        {
                                            field: 'acoes',
                                            header: 'Ações',
                                            width: '150px',
                                            render: (row) => (
                                                <div className="flex items-center gap-2">
                                                    <Button
                                                        size="sm"
                                                        variant="ghost"
                                                        className="h-7 px-2 text-xs hover:bg-slate-200 dark:hover:bg-slate-700"
                                                        onClick={() => handleOpenDialog(row, 'regra')}
                                                    >
                                                        <Edit className="w-3 h-3" />
                                                    </Button>
                                                    <Button
                                                        size="sm"
                                                        variant="ghost"
                                                        className="h-7 px-2 text-xs text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20"
                                                        onClick={() => handleDelete(row.id, 'regra')}
                                                    >
                                                        <Trash2 className="w-3 h-3" />
                                                    </Button>
                                                </div>
                                            )
                                        },
                                        {
                                            field: 'nome',
                                            header: 'Nome',
                                            width: '200px',
                                            render: (row) => (
                                                <div className="flex items-center gap-2">
                                                    <Users className="w-4 h-4 text-purple-500" />
                                                    <span className="font-bold text-slate-900 dark:text-white">{row.nome}</span>
                                                </div>
                                            )
                                        },
                                        { field: 'condicao', header: 'Condição', width: '250px' },
                                        { field: 'beneficiario', header: 'Beneficiário', width: '200px' },
                                        {
                                            field: 'categoriaId',
                                            header: 'Categoria',
                                            width: '150px',
                                            render: (row) => {
                                                const categoria = categorias.find(c => c.id === row.categoriaId);
                                                return categoria ? (
                                                    <Badge className="text-xs" style={{ backgroundColor: `${categoria.cor}20`, color: categoria.cor, borderColor: `${categoria.cor}40` }}>
                                                        {categoria.nome}
                                                    </Badge>
                                                ) : 'N/D';
                                            }
                                        }
                                    ]}
                                    rowKey="id"
                                    pageSize={25}
                                />
                            </div>
                        </TabsContent>
                    </Tabs>
                </CardContent>
            </Card>

            {/* Dialog de Edição/Criação */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle className="text-slate-900 dark:text-white font-bold text-lg">
                            {editingItem?.id ? `Editar ${editingItem.tipo === 'caixa' ? 'Caixa' : editingItem.tipo === 'categoria' ? 'Categoria' : 'Regra'}` : `Novo ${editingItem?.tipo === 'caixa' ? 'Caixa' : editingItem?.tipo === 'categoria' ? 'Categoria' : 'Regra'}`}
                        </DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                        {editingItem?.tipo === 'caixa' && (
                            <>
                                <div>
                                    <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Nome</Label>
                                    <Input
                                        value={formData.nome || ''}
                                        onChange={(e) => setFormData({ ...formData, nome: e.target.value })}
                                        className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    />
                                </div>
                                <div>
                                    <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Descrição</Label>
                                    <Input
                                        value={formData.descricao || ''}
                                        onChange={(e) => setFormData({ ...formData, descricao: e.target.value })}
                                        className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    />
                                </div>
                                <div className="grid grid-cols-3 gap-4">
                                    <div>
                                        <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Banco</Label>
                                        <Input
                                            value={formData.banco || ''}
                                            onChange={(e) => setFormData({ ...formData, banco: e.target.value })}
                                            className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                        />
                                    </div>
                                    <div>
                                        <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Agência</Label>
                                        <Input
                                            value={formData.agencia || ''}
                                            onChange={(e) => setFormData({ ...formData, agencia: e.target.value })}
                                            className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                        />
                                    </div>
                                    <div>
                                        <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Conta</Label>
                                        <Input
                                            value={formData.conta || ''}
                                            onChange={(e) => setFormData({ ...formData, conta: e.target.value })}
                                            className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                        />
                                    </div>
                                </div>
                            </>
                        )}
                        {editingItem?.tipo === 'categoria' && (
                            <>
                                <div>
                                    <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Nome</Label>
                                    <Input
                                        value={formData.nome || ''}
                                        onChange={(e) => setFormData({ ...formData, nome: e.target.value })}
                                        className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    />
                                </div>
                                <div>
                                    <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Entrada ou Saída</Label>
                                    <Select
                                        value={formData.tipo || 'saida'}
                                        onValueChange={(value) => setFormData({ ...formData, tipo: value })}
                                    >
                                        <SelectTrigger className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700">
                                            <SelectValue placeholder="Selecione" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="entrada">
                                                <span className="flex items-center gap-2">
                                                    <ArrowUpRight className="w-4 h-4 text-emerald-500" />
                                                    Entrada
                                                </span>
                                            </SelectItem>
                                            <SelectItem value="saida">
                                                <span className="flex items-center gap-2">
                                                    <ArrowDownRight className="w-4 h-4 text-rose-500" />
                                                    Saída
                                                </span>
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                                <div>
                                    <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Descrição</Label>
                                    <Input
                                        value={formData.descricao || ''}
                                        onChange={(e) => setFormData({ ...formData, descricao: e.target.value })}
                                        className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    />
                                </div>
                                <div>
                                    <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Cor</Label>
                                    <Input
                                        type="color"
                                        value={formData.cor || '#3b82f6'}
                                        onChange={(e) => setFormData({ ...formData, cor: e.target.value })}
                                        className="mt-1 h-12 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    />
                                </div>
                            </>
                        )}
                        {editingItem?.tipo === 'regra' && (
                            <>
                                <div>
                                    <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Nome</Label>
                                    <Input
                                        value={formData.nome || ''}
                                        onChange={(e) => setFormData({ ...formData, nome: e.target.value })}
                                        className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    />
                                </div>
                                <div>
                                    <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Condição</Label>
                                    <Input
                                        value={formData.condicao || ''}
                                        onChange={(e) => setFormData({ ...formData, condicao: e.target.value })}
                                        placeholder="Ex: descricao contém 'FORNECEDOR ABC'"
                                        className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    />
                                </div>
                                <div>
                                    <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Beneficiário</Label>
                                    <Input
                                        value={formData.beneficiario || ''}
                                        onChange={(e) => setFormData({ ...formData, beneficiario: e.target.value })}
                                        className="mt-1 bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700"
                                    />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <div>
                                        <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Categoria</Label>
                                        <select
                                            value={formData.categoriaId || ''}
                                            onChange={(e) => setFormData({ ...formData, categoriaId: parseInt(e.target.value) })}
                                            className="mt-1 w-full px-3 py-2 border border-slate-200 dark:border-slate-700 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white text-sm"
                                        >
                                            <option value="">Selecione...</option>
                                            {categorias.map(cat => (
                                                <option key={cat.id} value={cat.id}>{cat.nome}</option>
                                            ))}
                                        </select>
                                    </div>
                                    <div>
                                        <Label className="text-xs font-bold text-slate-700 dark:text-slate-300">Caixa</Label>
                                        <select
                                            value={formData.caixaId || ''}
                                            onChange={(e) => setFormData({ ...formData, caixaId: parseInt(e.target.value) })}
                                            className="mt-1 w-full px-3 py-2 border border-slate-200 dark:border-slate-700 rounded-lg bg-white dark:bg-slate-800 text-slate-900 dark:text-white text-sm"
                                        >
                                            <option value="">Selecione...</option>
                                            {caixas.map(caixa => (
                                                <option key={caixa.id} value={caixa.id}>{caixa.nome}</option>
                                            ))}
                                        </select>
                                    </div>
                                </div>
                            </>
                        )}
                    </div>
                    <DialogFooter>
                        <Button variant="ghost" onClick={() => setIsDialogOpen(false)}>
                            Cancelar
                        </Button>
                        <Button onClick={handleSave} className="bg-blue-600 hover:bg-blue-700 text-white">
                            Salvar
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Popup de Regras da Categoria */}
            {selectedCategoryForRules && (
                <CategoryRulesPopup 
                    isOpen={!!selectedCategoryForRules}
                    onClose={() => setSelectedCategoryForRules(null)}
                    category={selectedCategoryForRules}
                    onUpdate={() => {
                        // Opcional: Recarregar regras se necessário, mas o popup já gerencia suas regras
                    }}
                />
            )}
        </div>
    );
};
