import React, { useEffect, useState } from 'react';
import { X, Mail, Check, Trash2 } from 'lucide-react';
import api from '../services/api';

interface UnreadMessage {
    _id: string;
    message: string;
    createdAt: string;
    fromUser: {
        name: string;
        email: string;
    };
}

interface UnreadMessagesModalProps {
    isOpen: boolean;
    onClose: () => void;
}

export const UnreadMessagesModal: React.FC<UnreadMessagesModalProps> = ({
    isOpen,
    onClose,
}) => {
    const [messages, setMessages] = useState<UnreadMessage[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [confirmActionId, setConfirmActionId] = useState<string | null>(null);

    useEffect(() => {
        if (isOpen) {
            fetchMessages();
        }
    }, [isOpen]);

    const fetchMessages = async () => {
        setIsLoading(true);
        try {
            const response = await api.get<UnreadMessage[]>('/messages/unread');
            setMessages(response.data);
        } catch (error) {
            console.error('Error fetching messages:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const markAsRead = async (messageId: string) => {
        try {
            await api.patch(`/messages/${messageId}/read`);
            removeMessage(messageId);
        } catch (error) {
            console.error('Error marking message as read:', error);
            alert('Erro ao marcar mensagem como lida');
        }
    };

    const archiveMessage = async (messageId: string) => {
        try {
            await api.patch(`/messages/${messageId}/archive`);
            removeMessage(messageId);
        } catch (error) {
            console.error('Error archiving message:', error);
            alert('Erro ao arquivar mensagem');
        }
    };

    const deleteMessage = async (messageId: string) => {
        try {
            await api.delete(`/messages/${messageId}/recipient`);
            removeMessage(messageId);
        } catch (error) {
            console.error('Error deleting message:', error);
            alert('Erro ao excluir mensagem');
        }
    };

    const removeMessage = (messageId: string) => {
        setMessages(prev => prev.filter(m => m._id !== messageId));
        if (messages.length === 1) {
            onClose();
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-in fade-in">
            <div className="bg-surface rounded-2xl shadow-2xl max-w-lg w-full border border-border/40 animate-in slide-in-from-bottom-4 max-h-[80vh] flex flex-col">
                {/* Header */}
                <div className="flex items-center justify-between p-6 border-b border-border/40">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
                            <Mail className="text-primary" size={20} />
                        </div>
                        <div>
                            <h2 className="text-lg font-bold text-text-main">Mensagens Recebidas</h2>
                            <p className="text-sm text-text-muted">
                                {messages.length} {messages.length === 1 ? 'mensagem nova' : 'mensagens novas'}
                            </p>
                        </div>
                    </div>
                    <button
                        onClick={onClose}
                        className="p-2 hover:bg-surface-hover rounded-lg transition-colors"
                    >
                        <X size={20} className="text-text-muted" />
                    </button>
                </div>

                {/* Body */}
                <div className="flex-1 overflow-y-auto p-6 space-y-4">
                    {isLoading ? (
                        <div className="text-center py-8">
                            <p className="text-text-muted">Carregando mensagens...</p>
                        </div>
                    ) : messages.length === 0 ? (
                        <div className="text-center py-12">
                            <Mail size={48} className="text-text-muted/30 mx-auto mb-4" />
                            <p className="text-text-muted font-semibold">Nenhuma mensagem nova</p>
                            <p className="text-text-muted/60 text-sm mt-1">
                                Você está em dia com suas mensagens!
                            </p>
                        </div>
                    ) : (
                        messages.map((msg) => (
                            <div
                                key={msg._id}
                                className="bg-surface-soft border border-border/40 rounded-xl p-4 hover:shadow-lg transition-shadow"
                            >
                                <div className="flex items-start justify-between mb-3">
                                    <div>
                                        <div className="font-bold text-text-main">{msg.fromUser.name}</div>
                                        <div className="text-xs text-text-muted">{msg.fromUser.email}</div>
                                    </div>
                                    <div className="text-xs text-text-muted">
                                        {new Date(msg.createdAt).toLocaleString('pt-BR', {
                                            day: '2-digit',
                                            month: '2-digit',
                                            hour: '2-digit',
                                            minute: '2-digit',
                                        })}
                                    </div>
                                </div>
                                <div className="bg-white dark:bg-surface rounded-lg p-3 mb-3">
                                    <p className="text-text-main text-sm leading-relaxed">{msg.message}</p>
                                </div>
                                <div className="flex justify-between items-center gap-2 relative">
                                    <button
                                        onClick={() => markAsRead(msg._id)}
                                        className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg font-semibold text-sm transition-colors flex-1"
                                    >
                                        <Check size={16} />
                                        Lida
                                    </button>
                                    <button
                                        onClick={() => setConfirmActionId(msg._id)}
                                        className="p-2 bg-surface hover:bg-red-500/10 text-text-muted hover:text-red-500 rounded-lg border border-border/40 transition-all"
                                        title="Apagar ou Arquivar"
                                    >
                                        <Trash2 size={18} />
                                    </button>

                                    {/* Action Prompt */}
                                    {confirmActionId === msg._id && (
                                        <div className="absolute inset-0 bg-surface border border-primary/20 rounded-lg shadow-xl flex flex-col items-center justify-center p-2 z-10 animate-in zoom-in-95 duration-200">
                                            <p className="text-[10px] font-bold text-text-main mb-2">Deseja apagar ou arquivar?</p>
                                            <div className="flex gap-2 w-full">
                                                <button
                                                    onClick={() => archiveMessage(msg._id)}
                                                    className="flex-1 py-1 bg-surface-hover hover:bg-border/40 text-[10px] font-bold rounded border border-border/40"
                                                >
                                                    Arquivar
                                                </button>
                                                <button
                                                    onClick={() => deleteMessage(msg._id)}
                                                    className="flex-1 py-1 bg-red-600 text-white text-[10px] font-bold rounded"
                                                >
                                                    Apagar
                                                </button>
                                            </div>
                                            <button
                                                onClick={() => setConfirmActionId(null)}
                                                className="mt-1 text-[8px] text-text-muted hover:underline"
                                            >
                                                Fechar
                                            </button>
                                        </div>
                                    )}
                                </div>
                            </div>
                        ))
                    )}
                </div>

                {/* Footer */}
                {messages.length > 0 && (
                    <div className="p-6 border-t border-border/40 bg-surface-soft/50">
                        <button
                            onClick={onClose}
                            className="w-full px-4 py-2 bg-surface-hover hover:bg-border/40 rounded-lg font-semibold text-text-main transition-colors"
                        >
                            Fechar
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
};
