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

interface SendMessageModalProps {
    isOpen: boolean;
    onClose: () => void;
    recipientId: string;
    recipientName: string;
    existingMessage?: {
        id: string;
        message: string;
    };
    onMessageSent: () => void;
}

export const SendMessageModal: React.FC<SendMessageModalProps> = ({
    isOpen,
    onClose,
    recipientId,
    recipientName,
    existingMessage,
    onMessageSent,
}) => {
    const [message, setMessage] = useState(existingMessage?.message || '');
    const [isSending, setIsSending] = useState(false);

    if (!isOpen) return null;

    const handleSend = async () => {
        if (!message.trim()) {
            alert('Digite uma mensagem primeiro');
            return;
        }

        setIsSending(true);
        try {
            await api.post('/messages', {
                toUserId: recipientId,
                message: message.trim(),
            });
            alert('Mensagem enviada com sucesso!');
            onMessageSent();
            onClose();
        } catch (error) {
            console.error('Error sending message:', error);
            alert('Erro ao enviar mensagem');
        } finally {
            setIsSending(false);
        }
    };

    const handleDelete = async () => {
        if (!existingMessage?.id) return;

        if (!confirm('Deseja realmente deletar esta mensagem?')) return;

        setIsSending(true);
        try {
            await api.delete(`/messages/${existingMessage.id}`);
            alert('Mensagem deletada com sucesso!');
            onMessageSent();
            onClose();
        } catch (error) {
            console.error('Error deleting message:', error);
            alert('Erro ao deletar mensagem');
        } finally {
            setIsSending(false);
        }
    };

    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-md w-full border border-border/40 animate-in slide-in-from-bottom-4">
                {/* Header */}
                <div className="flex items-center justify-between p-6 border-b border-border/40">
                    <div>
                        <h2 className="text-lg font-bold text-text-main">
                            {existingMessage ? 'Editar Mensagem' : 'Enviar Mensagem'}
                        </h2>
                        <p className="text-sm text-text-muted mt-1">
                            Para: <span className="font-semibold text-primary">{recipientName}</span>
                        </p>
                    </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="p-6 space-y-4">
                    <div>
                        <label className="block text-sm font-semibold text-text-main mb-2">
                            Mensagem
                        </label>
                        <textarea
                            value={message}
                            onChange={(e) => setMessage(e.target.value)}
                            maxLength={255}
                            rows={4}
                            className="w-full px-4 py-3 bg-surface-soft border border-border/40 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/50 text-text-main resize-none"
                            placeholder="Digite sua mensagem (máximo 255 caracteres)..."
                            autoFocus
                        />
                        <div className="text-xs text-text-muted text-right mt-1">
                            {message.length}/255 caracteres
                        </div>
                    </div>

                    {existingMessage && (
                        <div className="bg-amber-500/10 border border-amber-500/30 rounded-lg p-3">
                            <p className="text-xs text-amber-600 dark:text-amber-400">
                                ℹ️ Você já enviou uma mensagem para este usuário. Esta ação vai substituir a mensagem anterior (se ainda não foi lida).
                            </p>
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div className="flex items-center justify-between p-6 border-t border-border/40 bg-surface-soft/50">
                    {existingMessage && (
                        <button
                            onClick={handleDelete}
                            disabled={isSending}
                            className="flex items-center gap-2 px-4 py-2 bg-error/10 hover:bg-error/20 text-error rounded-lg font-semibold transition-colors disabled:opacity-50"
                        >
                            <Trash2 size={16} />
                            Deletar
                        </button>
                    )}
                    <div className={`flex items-center gap-2 ${existingMessage ? '' : 'ml-auto'}`}>
                        <button
                            onClick={onClose}
                            className="px-4 py-2 hover:bg-surface-hover rounded-lg font-semibold text-text-secondary transition-colors"
                        >
                            Cancelar
                        </button>
                        <button
                            onClick={handleSend}
                            disabled={isSending || !message.trim()}
                            className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            <Send size={16} />
                            {isSending ? 'Enviando...' : 'Enviar'}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};
