import React, { useState, useEffect } from 'react';
import { 
  X, 
  Plus, 
  Trash2, 
  Search,
  AlertCircle,
  CheckCircle2,
  Link as LinkIcon,
  Unlink
} from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { conciliacaoService } from '@/services/conciliacaoService';
import { useToast } from '../hooks/useToast';
import { cn } from '@/lib/utils';

export function CategoryRulesPopup({ isOpen, onClose, category, onUpdate }) {
  const [loading, setLoading] = useState(false);
  const [rules, setRules] = useState([]);
  const [allRules, setAllRules] = useState([]);
  const [selectedRuleId, setSelectedRuleId] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const toast = useToast();

  // Load rules when popup opens or category changes
  useEffect(() => {
    if (isOpen && category?.id) {
      loadData();
    }
  }, [isOpen, category]);

  const loadData = async () => {
    setLoading(true);
    try {
      // 1. Fetch rules linked to this category
      const response = await conciliacaoService.fetchRulesByCategory(category.id);
      const raw = response?.data ?? response;
      // O backend retorna as regras em 'regras' ou 'Base_Dados_API' dependendo do endpoint
      const linkedRules = raw?.regras || (Array.isArray(raw) ? raw : (raw?.Base_Dados_API ?? []));
      
      // Normalize linked rules
      const formattedLinked = linkedRules.map(r => ({
        id: r.idregras_financeiro || r.id,
        nome: r.regra || r.nome || r.condicional,
        condicao: r.condicional || r.condicao,
        beneficiario: r.beneficiario_pagador || r.beneficiario,
        caixinha: r.caixinha
      }));
      setRules(formattedLinked);

      // 2. Fetch all rules for the dropdown (if not already passed or cached)
      // Ideally this should be optimized, but for now we fetch all
      const allRes = await conciliacaoService.fetchRules();
      const allRaw = allRes?.data ?? allRes;
      const allList = (Array.isArray(allRaw) ? allRaw : (allRaw?.Base_Dados_API ?? []));
      
      // Normalize all rules
      const formattedAll = allList.map(r => ({
        id: r.idregras_financeiro || r.id,
        nome: r.regra || r.nome || r.condicional,
        condicao: r.condicional || r.condicao,
        categoriaId: r.categoria,
        beneficiario: r.beneficiario_pagador || r.beneficiario
      }));
      setAllRules(formattedAll);

    } catch (error) {
      console.error('Erro ao carregar regras:', error);
      toast.error("Não foi possível carregar as regras da categoria.", "Erro");
    } finally {
      setLoading(false);
    }
  };

  const handleLinkRule = async () => {
    if (!selectedRuleId) return;

    try {
      setLoading(true);
      const ruleToLink = allRules.find(r => String(r.id) === String(selectedRuleId));
      if (!ruleToLink) return;

      // Update rule with new category
      await conciliacaoService.updateRule({
        idregras_financeiro: ruleToLink.id,
        regra: ruleToLink.nome,
        condicional: ruleToLink.condicao,
        beneficiario_pagador: ruleToLink.beneficiario || '',
        categoria: category.id, // Link to current category
        caixinha: '0' // Keep or reset box? Assuming 0 for generic constraint or keep existing if needed. Plan said change category.
      });

      toast.success("Regra vinculada com sucesso!");

      // Refresh list
      loadData();
      setSelectedRuleId('');
      if (onUpdate) onUpdate();

    } catch (error) {
      console.error('Erro ao vincular regra:', error);
      toast.error("Erro ao vincular regra.", "Erro");
    } finally {
      setLoading(false);
    }
  };

  const handleUnlinkRule = async (rule) => {
    if (!window.confirm(`Deseja desvincular a regra "${rule.nome}" desta categoria?`)) return;

    try {
      setLoading(true);
      
      // Update rule to remove category (set to 0)
      await conciliacaoService.updateRule({
        idregras_financeiro: rule.id,
        regra: rule.nome,
        condicional: rule.condicao,
        beneficiario_pagador: rule.beneficiario || '',
        categoria: '0', // Unlink
        caixinha: '0'
      });

      toast.success("Regra desvinculada com sucesso!");

      // Refresh list
      loadData();
      if (onUpdate) onUpdate();

    } catch (error) {
      console.error('Erro ao desvincular regra:', error);
      toast.error("Erro ao desvincular regra.", "Erro");
    } finally {
      setLoading(false);
    }
  };

  // Filter available rules: exclude those already linked to THIS category
  // Also filter by search term
  const availableRules = allRules.filter(r => {
    const isLinked = rules.some(linked => String(linked.id) === String(r.id));
    const matchesSearch = r.nome?.toLowerCase().includes(searchTerm.toLowerCase()) || 
                          r.condicao?.toLowerCase().includes(searchTerm.toLowerCase());
    return !isLinked && matchesSearch;
  });

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800 max-w-2xl max-h-[85vh] flex flex-col p-0 gap-0">
        <DialogHeader className="p-6 pb-2 border-b border-slate-100 dark:border-slate-800">
          <DialogTitle className="flex items-center gap-3 text-xl">
            <div className="p-2 bg-blue-500/10 rounded-lg">
              <LinkIcon className="w-5 h-5 text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <h2 className="text-slate-900 dark:text-white font-bold">Gerenciar Regras</h2>
              <p className="text-sm font-normal text-slate-500 dark:text-slate-400 mt-1">
                Categoria: <span className="font-semibold text-blue-600 dark:text-blue-400">{category?.nome}</span>
              </p>
            </div>
          </DialogTitle>
        </DialogHeader>

        <div className="flex-1 overflow-hidden flex flex-col">
          {/* Section: Linked Rules */}
          <div className="p-6 py-4 flex-1 flex flex-col min-h-0">
            <h3 className="text-sm font-semibold text-slate-900 dark:text-white mb-3 flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-emerald-500" />
              Regras Vinculadas ({rules.length})
            </h3>
            
            <div className="bg-slate-50 dark:bg-slate-800/50 rounded-xl border border-slate-200 dark:border-slate-800 flex-1 min-h-[200px] max-h-[400px] overflow-hidden relative">
                <div className="p-2 space-y-2 max-h-[300px] overflow-y-auto custom-scrollbar">
                  {loading && rules.length === 0 ? (
                    <div className="p-8 text-center text-slate-400 text-sm">Carregando...</div>
                  ) : rules.length === 0 ? (
                    <div className="p-8 text-center flex flex-col items-center gap-2">
                        <AlertCircle className="w-8 h-8 text-slate-300" />
                        <p className="text-slate-500 dark:text-slate-400 text-sm">Nenhuma regra vinculada a esta categoria.</p>
                    </div>
                  ) : (
                    rules.map(rule => (
                      <div key={rule.id} className="group flex items-center justify-between p-3 bg-white dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-800 shadow-sm hover:border-blue-300 dark:hover:border-blue-700 transition-all">
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-2">
                            <p className="font-bold text-slate-900 dark:text-white text-sm truncate">{rule.nome}</p>
                            {rule.caixinha && rule.caixinha !== '0' && (
                              <Badge variant="outline" className="text-[10px] bg-amber-500/10 text-amber-600 border-amber-500/20 py-0 px-1.5 h-4">
                                Caixa: {rule.caixinha}
                              </Badge>
                            )}
                          </div>
                          <p className="text-[11px] text-slate-500 dark:text-slate-400 truncate mt-1 bg-slate-50 dark:bg-slate-800/80 px-2 py-1 rounded border border-slate-100 dark:border-slate-800 font-medium">
                            {rule.condicao}
                          </p>
                          {rule.beneficiario && (
                            <p className="text-[10px] text-slate-400 mt-1 flex items-center gap-1">
                              <span className="font-semibold text-slate-500">Beneficiário:</span> {rule.beneficiario}
                            </p>
                          )}
                        </div>
                        <Button 
                          variant="ghost" 
                          size="sm" 
                          className="text-slate-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 ml-2 opacity-0 group-hover:opacity-100 transition-opacity shrink-0"
                          onClick={() => handleUnlinkRule(rule)}
                          title="Desvincular Regra"
                        >
                          <Unlink className="w-4 h-4" />
                        </Button>
                      </div>
                    ))
                  )}
                </div>
            </div>
          </div>

          {/* Section: Link New Rule */}
          <div className="p-6 pt-2 bg-slate-50/50 dark:bg-slate-900/50 border-t border-slate-200 dark:border-slate-800">
            <h3 className="text-sm font-semibold text-slate-900 dark:text-white mb-3">Vincular Nova Regra</h3>
            <div className="flex gap-2">
               <div className="flex-1">
                 <Select value={selectedRuleId} onValueChange={setSelectedRuleId}>
                    <SelectTrigger className="bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700">
                      <SelectValue placeholder="Selecione uma regra para vincular..." />
                    </SelectTrigger>
                    <SelectContent>
                        <div className="p-2 sticky top-0 bg-white dark:bg-slate-950 z-10 border-b border-slate-100 dark:border-slate-800 mb-2">
                            <div className="relative">
                                <Search className="w-3 h-3 absolute left-2 top-1/2 -translate-y-1/2 text-slate-400" />
                                <Input 
                                    placeholder="Filtrar regras..." 
                                    className="h-8 pl-7 text-xs" 
                                    value={searchTerm}
                                    onChange={e => setSearchTerm(e.target.value)}
                                    onKeyDown={e => e.stopPropagation()} 
                                />
                            </div>
                        </div>
                        <ScrollArea className="h-[200px]">
                            {availableRules.length === 0 ? (
                                <div className="p-2 text-center text-xs text-slate-400">Nenhuma regra disponível</div>
                            ) : (
                                availableRules.map(r => (
                                    <SelectItem key={r.id} value={String(r.id)}>
                                        <span className="font-medium">{r.nome}</span>
                                        <span className="text-slate-400 ml-2 text-xs">({r.condicao})</span>
                                    </SelectItem>
                                ))
                            )}
                        </ScrollArea>
                    </SelectContent>
                 </Select>
               </div>
               <Button 
                  onClick={handleLinkRule} 
                  disabled={!selectedRuleId || loading}
                  className="bg-blue-600 hover:bg-blue-700 text-white gap-2"
                >
                  <Plus className="w-4 h-4" />
                  Vincular
               </Button>
            </div>
          </div>
        </div>

        <DialogFooter className="p-4 border-t border-slate-100 dark:border-slate-800">
           <Button variant="outline" onClick={onClose}>Fechar</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
