import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { CreditCard, Plus, Landmark, User, Trash2, Edit2, CheckCircle, ShieldCheck, X, Search, Filter } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Card, CardContent } from '@/components/ui/card';
import { rhService } from '../../../services/rhService';
import { commonService } from '../../../services/commonService';
import { BankDTO } from '../../../types/common';
import { toast } from 'sonner';
import { debounce } from 'lodash';

interface BankAccountFilters {
    query?: string; // Busca por agente (nome, NIF, matrícula)
    bankId?: string;
    isPrimary?: string; // 'true', 'false', ou undefined
    accountNumber?: string; // IBAN ou número de conta
}

export const BankAccountsPage: React.FC = () => {
    const [accounts, setAccounts] = useState<any[]>([]);
    const [agents, setAgents] = useState<any[]>([]);
    const [banks, setBanks] = useState<BankDTO[]>([]);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingAccount, setEditingAccount] = useState<any>(null);
    const [showFilters, setShowFilters] = useState(false);
    const [filters, setFilters] = useState<BankAccountFilters>({});

    // Estados para Autocomplete
    const [selectedAgentForBankAccount, setSelectedAgentForBankAccount] = useState<any>(null);
    const [agentSearch, setAgentSearch] = useState("");
    const [searchingAgents, setSearchingAgents] = useState(false);
    const [showAgentSuggestions, setShowAgentSuggestions] = useState(false);

    useEffect(() => {
        loadAccounts();
        loadAgents();
        loadBanks();
    }, []);

    // Aplicar filtros quando mudarem
    const filteredAccounts = useMemo(() => {
        if (!accounts.length) return [];

        return accounts.filter(acc => {
            const agent = agents.find(a => a.id === acc.agentId);
            
            // Filtro por busca de agente (nome, NIF, matrícula)
            if (filters.query) {
                const query = filters.query.toLowerCase();
                const matchesName = agent?.fullName?.toLowerCase().includes(query);
                const matchesNif = agent?.nif?.toLowerCase().includes(query);
                const matchesMatricula = agent?.matricula?.toLowerCase().includes(query);
                if (!matchesName && !matchesNif && !matchesMatricula) {
                    return false;
                }
            }

            // Filtro por banco
            if (filters.bankId) {
                const bank = banks.find(b => b.id === filters.bankId);
                if (bank) {
                    // Verificar se o banco da conta corresponde ao banco selecionado
                    // A conta pode ter bankName, bank ou bankCode
                    const accountBankName = acc.bankName || acc.bank || '';
                    const accountBankCode = acc.bankCode || '';
                    if (accountBankName !== bank.name && accountBankCode !== bank.code) {
                        return false;
                    }
                }
            }

            // Filtro por conta principal
            if (filters.isPrimary !== undefined && filters.isPrimary !== '') {
                const isPrimaryFilter = filters.isPrimary === 'true';
                if (acc.isPrimary !== isPrimaryFilter) {
                    return false;
                }
            }

            // Filtro por IBAN ou número de conta
            if (filters.accountNumber) {
                const accountFilter = filters.accountNumber.toLowerCase();
                const matchesIban = acc.iban?.toLowerCase().includes(accountFilter);
                const matchesAccountNumber = acc.accountNumber?.toLowerCase().includes(accountFilter);
                if (!matchesIban && !matchesAccountNumber) {
                    return false;
                }
            }

            return true;
        });
    }, [accounts, agents, banks, filters]);

    const loadAccounts = async () => {
        try {
            setLoading(true);
            const data = await rhService.getBankAccounts();
            setAccounts(data);
        } catch (error) {
            toast.error('Erro ao carregar contas bancárias');
        } finally {
            setLoading(false);
        }
    };

    const loadBanks = async () => {
        try {
            const response = await commonService.getBanks({ page: 0, size: 100 });
            setBanks(response.content);
        } catch (error) {
            console.error('Erro ao carregar bancos', error);
        }
    };

    const loadAgents = async (query: string = "") => {
        try {
            setSearchingAgents(true);
            const response = await rhService.getAgents({ page: 0, size: 20, query });
            setAgents(response.content);
        } catch (error) {
            console.error('Erro ao carregar agentes', error);
        } finally {
            setSearchingAgents(false);
        }
    };

    const debouncedSearch = useCallback(
        debounce((query: string) => loadAgents(query), 500),
        []
    );

    const handleAgentSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value;
        setAgentSearch(val);
        debouncedSearch(val);
    };

    const handleEdit = (acc: any) => {
        setEditingAccount(acc);
        const agent = agents.find(a => a.id === acc.agentId);
        if (agent) {
            setSelectedAgentForBankAccount(agent);
        } else {
            // Se o agente não estiver no estado agents atual, podemos carregar por ID ou apenas placeholder
            setSelectedAgentForBankAccount({ id: acc.agentId, fullName: "Agente Selecionado" });
        }
        setIsModalOpen(true);
    };

    const handleDelete = async (id: string) => {
        if (!confirm('Tem a certeza que deseja eliminar esta conta?')) return;
        try {
            await rhService.deleteBankAccount(id);
            toast.success('Conta eliminada com sucesso');
            loadAccounts();
        } catch (error) {
            toast.error('Erro ao eliminar conta');
        }
    };

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget);

        const bankId = formData.get('bankId') as string;
        const selectedBank = banks.find(b => b.id === bankId);

        if (!selectedBank) {
            toast.error('Banco inválido selecionado');
            return;
        }

        const data = {
            id: editingAccount?.id,
            agent: { id: formData.get('agentId') },
            bank: selectedBank.name,
            branchCode: selectedBank.code,
            accountNumber: formData.get('accountNumber'),
            iban: formData.get('iban'),
            isPrimary: formData.get('isPrimary') === 'on'
        };

        try {
            if (editingAccount) {
                await rhService.updateBankAccount(editingAccount.id, data);
                toast.success('Conta atualizada com sucesso');
            } else {
                await rhService.saveBankAccount(data);
                toast.success('Conta vinculada com sucesso');
            }
            setIsModalOpen(false);
            setEditingAccount(null);
            setSelectedAgentForBankAccount(null);
            setAgentSearch("");
            loadAccounts();
        } catch (error) {
            toast.error(editingAccount ? 'Erro ao atualizar conta' : 'Erro ao vincular conta');
        }
    };

    return (
        <div className="p-6 space-y-6">
            <PageHeader
                title="Contas Bancárias"
                description="Gestão de domiciliação bancária dos agentes do Estado"
                actions={
                    <div className="flex gap-2">
                        <Button variant="outline" size="sm" onClick={() => setShowFilters(!showFilters)}>
                            <Filter className="h-4 w-4 mr-1" />
                            Filtros
                        </Button>
                        <Button onClick={() => {
                            setEditingAccount(null);
                            setSelectedAgentForBankAccount(null);
                            setAgentSearch("");
                            setIsModalOpen(true);
                        }} className="flex items-center gap-2">
                            <Plus className="w-4 h-4" /> Vincular Conta
                        </Button>
                    </div>
                }
            />

            {/* Painel de Filtros */}
            {showFilters && (
                <Card className="mb-6">
                    <CardContent className="p-4">
                        <div className="space-y-4">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <Filter className="h-4 w-4 text-primary" />
                                    <span className="text-sm font-semibold">Filtros de Pesquisa</span>
                                    {Object.values(filters).filter(v => v !== undefined && v !== '').length > 0 && (
                                        <span className="ml-2 bg-primary/10 text-primary text-[10px] font-bold px-2 py-0.5 rounded-full uppercase">
                                            {Object.values(filters).filter(v => v !== undefined && v !== '').length} Ativos
                                        </span>
                                    )}
                                </div>
                                <Button variant="ghost" size="sm" onClick={() => setFilters({})}>
                                    <X className="h-4 w-4 mr-1" />
                                    Limpar
                                </Button>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                                {/* Busca por Agente */}
                                <div className="space-y-1.5">
                                    <label className="text-xs font-semibold text-gray-600">Buscar Agente</label>
                                    <div className="relative">
                                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                                        <Input
                                            placeholder="Nome, NIF ou Matrícula..."
                                            className="pl-9"
                                            value={filters.query || ''}
                                            onChange={(e) => setFilters({ ...filters, query: e.target.value })}
                                        />
                                    </div>
                                </div>

                                {/* Filtro por Banco */}
                                <div className="space-y-1.5">
                                    <label className="text-xs font-semibold text-gray-600">Banco</label>
                                    <Select
                                        value={filters.bankId || '__ALL__'}
                                        onValueChange={(value) => setFilters({ ...filters, bankId: value === '__ALL__' ? undefined : value })}
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder="Todos os bancos" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="__ALL__">Todos os bancos</SelectItem>
                                            {banks.map(bank => (
                                                <SelectItem key={bank.id} value={bank.id}>
                                                    {bank.code} - {bank.name}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </div>

                                {/* Filtro por Conta Principal */}
                                <div className="space-y-1.5">
                                    <label className="text-xs font-semibold text-gray-600">Conta Principal</label>
                                    <Select
                                        value={filters.isPrimary || '__ALL__'}
                                        onValueChange={(value) => setFilters({ ...filters, isPrimary: value === '__ALL__' ? undefined : value })}
                                    >
                                        <SelectTrigger>
                                            <SelectValue placeholder="Todas" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="__ALL__">Todas</SelectItem>
                                            <SelectItem value="true">Apenas Principais</SelectItem>
                                            <SelectItem value="false">Apenas Secundárias</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>

                                {/* Busca por IBAN/Conta */}
                                <div className="space-y-1.5">
                                    <label className="text-xs font-semibold text-gray-600">IBAN / Conta</label>
                                    <div className="relative">
                                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                                        <Input
                                            placeholder="IBAN ou Número de Conta..."
                                            className="pl-9 font-mono"
                                            value={filters.accountNumber || ''}
                                            onChange={(e) => setFilters({ ...filters, accountNumber: e.target.value })}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </CardContent>
                </Card>
            )}

            {/* Contador de resultados */}
            {!loading && (
                <div className="text-sm text-gray-600 mb-2">
                    {filteredAccounts.length === accounts.length ? (
                        <span>Total: <strong>{accounts.length}</strong> conta{accounts.length !== 1 ? 's' : ''}</span>
                    ) : (
                        <span>
                            Mostrando <strong>{filteredAccounts.length}</strong> de <strong>{accounts.length}</strong> conta{accounts.length !== 1 ? 's' : ''}
                            {Object.values(filters).some(v => v !== undefined && v !== '') && ' (filtradas)'}
                        </span>
                    )}
                </div>
            )}

            <div className="bg-white rounded-lg shadow overflow-hidden border">
                <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50 text-gray-500 uppercase text-xs font-semibold tracking-wider">
                        <tr>
                            <th className="px-6 py-3 text-left">Agente</th>
                            <th className="px-6 py-3 text-left">Banco</th>
                            <th className="px-6 py-3 text-left">IBAN / Conta</th>
                            <th className="px-6 py-3 text-left">Principal</th>
                            <th className="px-6 py-3 text-right">Ações</th>
                        </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200 text-sm">
                        {loading ? (
                            <tr><td colSpan={5} className="px-6 py-4 text-center">Carregando dados...</td></tr>
                        ) : filteredAccounts.length === 0 ? (
                            <tr>
                                <td colSpan={5} className="px-6 py-4 text-center text-gray-500">
                                    {Object.values(filters).some(v => v !== undefined && v !== '') 
                                        ? 'Nenhuma conta encontrada com os filtros aplicados' 
                                        : 'Nenhuma conta encontrada'}
                                </td>
                            </tr>
                        ) : (
                            filteredAccounts.map((acc) => {
                                const agent = agents.find(a => a.id === acc.agentId);
                                return (
                                    <tr key={acc.id} className="hover:bg-gray-50">
                                        <td className="px-6 py-4 flex items-center gap-2">
                                            <div className="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-700 font-bold">
                                                {agent?.fullName?.substring(0, 2) || acc.agentId?.substring(0, 2)}
                                            </div>
                                            <div>
                                                <div className="font-medium text-gray-900">{agent?.fullName || `Agente ID: ${acc.agentId?.substring(0, 8)}...`}</div>
                                                <div className="text-xs text-gray-500 font-mono">NIF: {agent?.nif || '---'} | Matrícula: {agent?.matricula || '---'}</div>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4">
                                            <div className="flex items-center gap-2">
                                                <Landmark className="w-4 h-4 text-gray-400" />
                                                <span>{acc.bankCode} - {acc.bankName || 'Banco Comercial'}</span>
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 font-mono text-gray-600">
                                            {acc.iban || acc.accountNumber}
                                        </td>
                                        <td className="px-6 py-4">
                                            {acc.isPrimary ? (
                                                <CheckCircle className="w-5 h-5 text-green-500" />
                                            ) : (
                                                <span className="text-gray-300">---</span>
                                            )}
                                        </td>
                                        <td className="px-6 py-4 text-right flex justify-end gap-2">
                                            <Button variant="ghost" size="sm" onClick={() => handleEdit(acc)} className="text-blue-600 hover:bg-blue-50" title="Editar">
                                                <Edit2 className="w-4 h-4" />
                                            </Button>
                                            <Button variant="ghost" size="sm" onClick={() => handleDelete(acc.id)} className="text-red-600 hover:bg-red-50" title="Excluir">
                                                <Trash2 className="w-4 h-4" />
                                            </Button>
                                        </td>
                                    </tr>
                                );
                            })
                        )}
                    </tbody>
                </table>
            </div>

            {isModalOpen && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
                    <div className="bg-white rounded-xl shadow-2xl max-w-md w-full overflow-hidden">
                        <div className="px-6 py-4 border-b flex justify-between items-center bg-gray-50">
                            <h3 className="text-lg font-bold text-gray-900">
                                {editingAccount ? 'Editar Conta Bancária' : 'Vincular Conta Bancária'}
                            </h3>
                            <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-gray-600">
                                <X className="w-5 h-5" />
                            </button>
                        </div>
                        <form
                            onSubmit={handleSubmit}
                            className="p-6 space-y-4"
                            onClick={() => setShowAgentSuggestions(false)}
                        >
                            <div className="space-y-1 relative" onClick={(e) => e.stopPropagation()}>
                                <label className="text-xs font-bold text-gray-500 uppercase">Agente Beneficiário</label>
                                <div className="relative">
                                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                    <input
                                        type="text"
                                        placeholder={selectedAgentForBankAccount ? `${selectedAgentForBankAccount.fullName} (${selectedAgentForBankAccount.matricula})` : "Buscar por nome ou matrícula..."}
                                        value={agentSearch}
                                        onChange={handleAgentSearchChange}
                                        onFocus={() => setShowAgentSuggestions(true)}
                                        className="w-full border rounded-lg pl-9 pr-3 py-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                                        required={!selectedAgentForBankAccount}
                                    />
                                    {selectedAgentForBankAccount && (
                                        <button
                                            type="button"
                                            onClick={() => {
                                                setSelectedAgentForBankAccount(null);
                                                setAgentSearch("");
                                            }}
                                            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-red-500"
                                        >
                                            <X className="w-4 h-4" />
                                        </button>
                                    )}
                                </div>
                                <input type="hidden" name="agentId" value={selectedAgentForBankAccount?.id || ""} required />

                                {showAgentSuggestions && agentSearch.length > 0 && (
                                    <div className="absolute z-10 left-0 right-0 top-full mt-1 bg-white border rounded-lg shadow-xl max-h-48 overflow-y-auto">
                                        {searchingAgents ? (
                                            <div className="p-3 text-xs text-center text-gray-500 animate-pulse">Buscando...</div>
                                        ) : agents.length === 0 ? (
                                            <div className="p-3 text-xs text-center text-gray-500">Agente não encontrado</div>
                                        ) : (
                                            agents.map(agent => (
                                                <div
                                                    key={agent.id}
                                                    onClick={() => {
                                                        setSelectedAgentForBankAccount(agent);
                                                        setAgentSearch("");
                                                        setShowAgentSuggestions(false);
                                                    }}
                                                    className="p-3 border-b last:border-0 hover:bg-primary/5 cursor-pointer flex flex-col"
                                                >
                                                    <span className="text-sm font-bold text-gray-900">{agent.fullName}</span>
                                                    <span className="text-[10px] text-gray-500">Matrícula: {agent.matricula} | NIF: {agent.nif}</span>
                                                </div>
                                            ))
                                        )}
                                    </div>
                                )}
                            </div>

                            <div className="space-y-1">
                                <label className="text-xs font-bold text-gray-500 uppercase">Banco Comercial</label>
                                <select
                                    name="bankId"
                                    required
                                    className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                                    defaultValue={banks.find(b => b.name === editingAccount?.bank)?.id || ""}
                                >
                                    <option value="">Selecione o banco...</option>
                                    {banks.map(bank => (
                                        <option key={bank.id} value={bank.id}>
                                            {bank.code} - {bank.name}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div className="space-y-1">
                                <label className="text-xs font-bold text-gray-500 uppercase">Número de Conta</label>
                                <input name="accountNumber" defaultValue={editingAccount?.accountNumber} required placeholder="Número da Conta" className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none" />
                            </div>

                            <div className="space-y-1">
                                <label className="text-xs font-bold text-gray-500 uppercase">IBAN</label>
                                <input name="iban" defaultValue={editingAccount?.iban} placeholder="GW00 0000 0000 0000 0000 00" className="w-full border rounded-lg p-2 text-sm font-mono focus:ring-2 focus:ring-primary focus:outline-none" />
                            </div>

                            <div className="flex items-center gap-2 pt-2">
                                <input type="checkbox" name="isPrimary" id="isPrimary" defaultChecked={editingAccount ? editingAccount.isPrimary : true} className="rounded border-gray-300 text-primary focus:ring-primary" />
                                <label htmlFor="isPrimary" className="text-sm font-medium text-gray-700">Definir como conta principal de recebimento</label>
                            </div>

                            <div className="pt-4 flex gap-3">
                                <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)} className="flex-1">Cancelar</Button>
                                <Button type="submit" className="flex-1">
                                    {editingAccount ? 'Salvar Alterações' : 'Vincular'}
                                </Button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg flex gap-3 text-blue-800 text-sm">
                <ShieldCheck className="w-5 h-5 flex-shrink-0" />
                <p>As contas bancárias são utilizadas para a geração automática de lotes de pagamento e remessas bancárias para o BCEAO e bancos comerciais locais.</p>
            </div>
        </div>
    );
};
