import React, { useState, useEffect } from 'react';
import { Bell, Search, Filter, CheckCircle2, Trash2, Calendar, DollarSign, UserCheck, ShieldAlert, MessageSquare, Inbox, ArrowRight, MoreHorizontal } from 'lucide-react';
import { HybridBackend } from '../services/backend.ts';
import { Notificacao } from '../types.ts';
import { useToast } from '../contexts/ToastContext.tsx';
import { PageHeader } from '../components/PageHeader.tsx';

export const NotificationsView: React.FC = () => {
    const [notificacoes, setNotificacoes] = useState<Notificacao[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [activeTab, setActiveTab] = useState<'all' | 'unread' | 'important'>('all');
    const [filterType, setFilterType] = useState<string>('all');
    const toast = useToast();

    const fetchNotificacoes = async () => {
        setLoading(true);
        try {
            const data = await HybridBackend.getNotifications();
            // Data de mais nova para mais antiga
            setNotificacoes(data.sort((a, b) => new Date(b.data).getTime() - new Date(a.data).getTime()));
        } catch (err) {
            toast.error("Erro ao carregar notificações");
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchNotificacoes();
    }, []);

    const markAsRead = async (id: string) => {
        try {
            await HybridBackend.markNotificationRead(id);
            setNotificacoes(prev => prev.map(n => n.id === id ? { ...n, lida: true } : n));
            toast.success("Notificação marcada como lida");
        } catch (err) {
            toast.error("Erro ao atualizar notificação");
        }
    };

    const markAllAsRead = async () => {
        const unread = notificacoes.filter(n => !n.lida);
        if (unread.length === 0) return;

        try {
            await HybridBackend.markAllNotificationsRead();
            setNotificacoes(prev => prev.map(n => ({ ...n, lida: true })));
            toast.success("Todas as notificações foram marcadas como lidas");
        } catch (err) {
            toast.error("Erro ao atualizar notificações");
        }
    };

    const deleteNotification = async (id: string) => {
        try {
            await HybridBackend.deleteNotification(id);
            setNotificacoes(prev => prev.filter(n => n.id !== id));
            toast.success("Notificação removida");
        } catch (err) {
            toast.error("Erro ao excluir notificação");
        }
    };

    const getIcon = (tipo: string) => {
        switch (tipo) {
            case 'agenda': return <Calendar size={20} className="text-blue-500" />;
            case 'financeiro': return <DollarSign size={20} className="text-emerald-500" />;
            case 'lead': return <UserCheck size={20} className="text-amber-500" />;
            case 'sistema': return <ShieldAlert size={20} className="text-red-500" />;
            default: return <MessageSquare size={20} className="text-gray-500" />;
        }
    };

    const filteredNotificacoes = notificacoes.filter(n => {
        const matchesSearch = n.titulo.toLowerCase().includes(searchTerm.toLowerCase()) ||
            n.mensagem.toLowerCase().includes(searchTerm.toLowerCase());
        const matchesTab = activeTab === 'all' || (activeTab === 'unread' && !n.lida) || (activeTab === 'important' && n.tipo === 'sistema');
        const matchesType = filterType === 'all' || n.tipo === filterType;
        return matchesSearch && matchesTab && matchesType;
    });

    const unreadCount = notificacoes.filter(n => !n.lida).length;

    return (
        <div className="space-y-6 animate-in fade-in duration-500">
            <PageHeader title="CENTRO DE NOTIFICAÇÕES">
                <div className="flex gap-3">
                    <button
                        onClick={markAllAsRead}
                        className="flex items-center gap-2 px-4 py-2 bg-white border border-slate-200 text-slate-600 hover:text-blue-600 hover:border-blue-200 rounded-xl font-bold text-xs uppercase tracking-wider transition-all shadow-sm"
                    >
                        <CheckCircle2 size={16} /> Marcar todas como lidas
                    </button>
                    <button
                        onClick={fetchNotificacoes}
                        className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 rounded-xl font-bold text-xs uppercase tracking-wider transition-all shadow-md active:scale-95"
                    >
                        <Bell size={16} /> Atualizar
                    </button>
                </div>
            </PageHeader>

            {/* Stats Dashboard */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                {[
                    { label: 'Total', count: notificacoes.length, icon: Inbox, color: 'text-slate-600', bg: 'bg-slate-100' },
                    { label: 'Não Lidas', count: unreadCount, icon: Bell, color: 'text-blue-600', bg: 'bg-blue-50' },
                    { label: 'Sistema', count: notificacoes.filter(n => n.tipo === 'sistema').length, icon: ShieldAlert, color: 'text-red-600', bg: 'bg-red-50' },
                    { label: 'Financeiro', count: notificacoes.filter(n => n.tipo === 'financeiro').length, icon: DollarSign, color: 'text-emerald-600', bg: 'bg-emerald-50' },
                ].map((stat, i) => (
                    <div key={i} className="bg-white p-5 rounded-2xl border border-slate-100 shadow-sm flex items-center gap-4 group hover:shadow-md transition-all">
                        <div className={`p-3 rounded-xl ${stat.bg} ${stat.color} group-hover:scale-110 transition-transform`}>
                            <stat.icon size={24} />
                        </div>
                        <div>
                            <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{stat.label}</p>
                            <h4 className="text-2xl font-black text-slate-800 tracking-tighter">{stat.count}</h4>
                        </div>
                    </div>
                ))}
            </div>

            <div className="bg-white rounded-[2.5rem] border border-slate-100 shadow-sm overflow-hidden min-h-[600px] flex flex-col">
                {/* Filters Bar */}
                <div className="p-8 border-b border-slate-50 flex flex-col lg:flex-row lg:items-center justify-between gap-6 bg-slate-50/30">
                    <div className="flex p-1.5 bg-slate-100 rounded-2xl w-fit">
                        {[
                            { id: 'all', label: 'Todas' },
                            { id: 'unread', label: 'Não Lidas' },
                            { id: 'important', label: 'Importantes' },
                        ].map(tab => (
                            <button
                                key={tab.id}
                                onClick={() => setActiveTab(tab.id as any)}
                                className={`px-6 py-2.5 rounded-xl text-xs font-black uppercase tracking-widest transition-all ${activeTab === tab.id ? 'bg-white text-blue-600 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
                            >
                                {tab.label}
                                {tab.id === 'unread' && unreadCount > 0 && (
                                    <span className="ml-2 bg-blue-600 text-white px-1.5 py-0.5 rounded-md text-[9px]">{unreadCount}</span>
                                )}
                            </button>
                        ))}
                    </div>

                    <div className="flex flex-1 max-w-2xl gap-3">
                        <div className="relative flex-1 group">
                            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-blue-500 transition-colors" size={18} />
                            <input
                                type="text"
                                placeholder="Pesquisar notificações..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="w-full pl-12 pr-4 py-3.5 bg-white border border-slate-200 rounded-2xl text-sm font-bold uppercase tracking-tight focus:ring-4 focus:ring-blue-50 focus:border-blue-500 outline-none transition-all placeholder:text-slate-300"
                            />
                        </div>
                        <select
                            value={filterType}
                            onChange={(e) => setFilterType(e.target.value)}
                            className="px-4 py-3.5 bg-white border border-slate-200 rounded-2xl text-xs font-black uppercase tracking-widest focus:ring-4 focus:ring-blue-50 outline-none cursor-pointer"
                        >
                            <option value="all">Filtro: Todos</option>
                            <option value="lead">Novos Leads</option>
                            <option value="agenda">Agendamentos</option>
                            <option value="financeiro">Financeiro</option>
                            <option value="sistema">Alertas de Sistema</option>
                        </select>
                    </div>
                </div>

                {/* List */}
                <div className="flex-1 overflow-y-auto custom-scrollbar">
                    {loading ? (
                        <div className="flex flex-col items-center justify-center h-[400px]">
                            <div className="w-12 h-12 border-4 border-blue-100 border-t-blue-600 rounded-full animate-spin mb-4" />
                            <p className="text-slate-400 font-black uppercase tracking-widest text-xs">Carregando Histórico...</p>
                        </div>
                    ) : filteredNotificacoes.length === 0 ? (
                        <div className="flex flex-col items-center justify-center p-20 text-center">
                            <div className="w-32 h-32 bg-slate-50 rounded-[3rem] flex items-center justify-center mb-6">
                                <Inbox size={48} className="text-slate-200" />
                            </div>
                            <h3 className="text-xl font-black text-slate-800 uppercase tracking-tighter">Nenhuma notificação encontrada</h3>
                            <p className="text-slate-400 text-sm mt-2 max-w-sm">
                                Não existem registros que correspondam aos seus filtros ou pesquisa no momento.
                            </p>
                        </div>
                    ) : (
                        <div className="divide-y divide-slate-50">
                            {filteredNotificacoes.map((notif, idx) => (
                                <div
                                    key={notif.id}
                                    className={`group p-8 transition-all hover:bg-slate-50/50 flex flex-col md:flex-row md:items-center gap-6 relative ${!notif.lida ? 'bg-blue-50/20' : ''}`}
                                    style={{ animationDelay: `${idx * 50}ms` }}
                                >
                                    {!notif.lida && (
                                        <div className="absolute left-0 top-0 bottom-0 w-1.5 bg-blue-600 rounded-r-full shadow-[2px_0_10px_rgba(37,99,235,0.3)]" />
                                    )}

                                    <div className={`p-4 rounded-[1.5rem] flex-shrink-0 shadow-sm border border-white transition-transform group-hover:scale-110 ${notif.tipo === 'agenda' ? 'bg-blue-100/50 text-blue-600' :
                                        notif.tipo === 'financeiro' ? 'bg-emerald-100/50 text-emerald-600' :
                                            notif.tipo === 'lead' ? 'bg-amber-100/50 text-amber-600' :
                                                'bg-red-100/50 text-red-600'
                                        }`}>
                                        {getIcon(notif.tipo)}
                                    </div>

                                    <div className="flex-1 space-y-2">
                                        <div className="flex flex-wrap items-center gap-3">
                                            <span className={`text-[10px] font-black uppercase tracking-[0.2em] px-3 py-1 rounded-full ${notif.tipo === 'agenda' ? 'bg-blue-100 text-blue-600' :
                                                notif.tipo === 'financeiro' ? 'bg-emerald-100 text-emerald-600' :
                                                    notif.tipo === 'lead' ? 'bg-amber-100 text-amber-600' :
                                                        'bg-red-100 text-red-600'
                                                }`}>
                                                {notif.tipo}
                                            </span>
                                            <span className="text-[11px] font-bold text-slate-300 flex items-center gap-1.5 uppercase tracking-wider">
                                                <Calendar size={12} />
                                                {new Date(notif.data).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric' })}
                                            </span>
                                            <span className="text-[11px] font-bold text-slate-300 flex items-center gap-1.5 uppercase tracking-wider">
                                                <Clock size={12} className="ml-2" />
                                                {new Date(notif.data).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })}
                                            </span>
                                        </div>
                                        <h3 className={`text-lg font-black tracking-tighter uppercase ${!notif.lida ? 'text-slate-900' : 'text-slate-600'}`}>
                                            {notif.titulo}
                                        </h3>
                                        <p className="text-slate-500 text-sm leading-relaxed max-w-4xl">
                                            {notif.mensagem}
                                        </p>
                                    </div>

                                    <div className="flex items-center gap-3 opacity-0 group-hover:opacity-100 transition-all transform translate-x-4 group-hover:translate-x-0">
                                        {!notif.lida && (
                                            <button
                                                onClick={() => markAsRead(notif.id)}
                                                className="p-3 bg-blue-600 text-white rounded-xl shadow-lg shadow-blue-100 hover:bg-blue-700 hover:-translate-y-1 transition-all"
                                                title="Marcar como lida"
                                            >
                                                <CheckCircle2 size={20} />
                                            </button>
                                        )}
                                        <button
                                            onClick={() => deleteNotification(notif.id)}
                                            className="p-3 bg-white text-slate-400 border border-slate-100 rounded-xl shadow-sm hover:text-red-600 hover:border-red-100 hover:-translate-y-1 transition-all"
                                            title="Excluir"
                                        >
                                            <Trash2 size={20} />
                                        </button>
                                        <button className="p-3 bg-white text-slate-400 border border-slate-100 rounded-xl shadow-sm hover:text-slate-600 hover:-translate-y-1 transition-all">
                                            <MoreHorizontal size={20} />
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                {/* Footer Info */}
                <div className="p-6 bg-slate-50 border-t border-slate-100 flex items-center justify-between">
                    <p className="text-[11px] font-bold text-slate-400 uppercase tracking-widest">
                        Mostrando {filteredNotificacoes.length} de {notificacoes.length} registros
                    </p>
                    <div className="flex gap-2">
                        <button className="px-5 py-2 rounded-xl bg-white border border-slate-200 text-[11px] font-black uppercase tracking-wider text-slate-500 hover:bg-slate-50 transition-colors">Voltar</button>
                        <button className="px-5 py-2 rounded-xl bg-white border border-slate-200 text-[11px] font-black uppercase tracking-wider text-slate-500 hover:bg-slate-50 transition-colors">Próximo</button>
                    </div>
                </div>
            </div>
        </div>
    );
};

const Clock = ({ size, className }: { size: number, className?: string }) => (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><circle cx="12" cy="12" r="10" /><polyline points="12 6 12 12 16 14" /></svg>
);
