import { useState, useEffect, useRef } from 'react';
import { Send, Loader, X } from 'lucide-react';

export default function TicketThreadModal({ ticket, onClose, onReply, isLoadingConversation }) {
    const [replyMessage, setReplyMessage] = useState('');
    const messagesEndRef = useRef(null);

    // Défilement automatique
    useEffect(() => {
        if (ticket && ticket.messages && !isLoadingConversation) {
            messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
        }
    }, [ticket?.messages, isLoadingConversation]);

    if (!ticket) return null;

    const handleReplySubmit = (e) => {
        e.preventDefault();
        if (!replyMessage.trim()) return;
        onReply(replyMessage);
        setReplyMessage(''); // Reset auto du champ
    };

    return (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-2 sm:p-4">
            <div className="bg-gray-950 border border-gray-800 rounded-lg shadow-2xl max-w-3xl w-full h-[85vh] flex flex-col">
                <div className="bg-gray-900 border-b border-gray-800 p-4 sm:p-6 flex justify-between items-start rounded-t-lg">
                    <div>
                        <div className="flex items-center gap-3 mb-1">
                            <span className="text-cyan-500 font-mono text-sm">{ticket.id}</span>
                            <span className="bg-gray-800 text-gray-300 text-[10px] uppercase font-bold tracking-wider px-2 py-0.5 rounded border border-gray-700">{ticket.department}</span>
                        </div>
                        <h3 className="text-xl font-bold text-white line-clamp-1">{ticket.subject}</h3>
                    </div>
                    <button onClick={onClose} className="p-2 text-gray-500 hover:text-white bg-gray-900 hover:bg-gray-800 rounded-lg transition-colors">
                        <X className="w-5 h-5" />
                    </button>
                </div>

                <div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-6 scrollbar-thin scrollbar-thumb-gray-800">
                    {isLoadingConversation ? (
                        <div className="flex flex-col items-center justify-center h-full text-cyan-400 gap-2 font-mono text-xs">
                            <Loader className="w-6 h-6 animate-spin" /><span>Téléchargement des paquets de discussion sécurisés...</span>
                        </div>
                    ) : ticket.messages.length === 0 ? (
                        <div className="text-center text-gray-600 font-mono text-xs pt-10">Aucun message trouvé dans ce fil.</div>
                    ) : (
                        ticket.messages.map((msg, idx) => (
                            <div key={idx} className={`flex flex-col ${msg.sender === 'client' ? 'items-end' : 'items-start'}`}>
                                <div className="flex items-baseline gap-2 mb-1 px-1">
                                    <span className={`text-[10px] font-bold uppercase tracking-widest ${msg.sender === 'client' ? 'text-gray-500' : 'text-cyan-400'}`}>
                                        {msg.sender === 'client' ? 'VOUS' : 'INGÉNIEUR GISE'}
                                    </span>
                                    <span className="text-[10px] text-gray-600 font-mono">{msg.date}</span>
                                </div>
                                <div className={`p-4 rounded-xl max-w-[85%] text-sm leading-relaxed ${msg.sender === 'client' ? 'bg-gray-800 text-gray-200 rounded-tr-none' : 'bg-cyan-900/20 border border-cyan-800/30 text-cyan-50 rounded-tl-none'}`}>
                                    {msg.text}
                                </div>
                            </div>
                        ))
                    )}
                    <div ref={messagesEndRef} />
                </div>

                {ticket.status !== 'closed' ? (
                    <form onSubmit={handleReplySubmit} className="bg-gray-900 border-t border-gray-800 p-4 rounded-b-lg">
                        <div className="flex gap-2">
                            <textarea rows="2" value={replyMessage} onChange={(e) => setReplyMessage(e.target.value)} required placeholder="Taper une réponse sécurisée..." className="flex-1 bg-black border border-gray-800 text-white p-3 rounded-lg text-sm focus:border-cyan-500 outline-none transition resize-none"></textarea>
                            <button type="submit" className="bg-cyan-600 hover:bg-cyan-500 text-white px-6 rounded-lg font-bold font-mono tracking-widest transition flex flex-col items-center justify-center gap-1 shadow-lg shadow-cyan-500/20">
                                <Send className="w-4 h-4" /><span className="text-[10px]">ENVOYER</span>
                            </button>
                        </div>
                    </form>
                ) : (
                    <div className="bg-gray-900 border-t border-gray-800 p-4 rounded-b-lg text-center font-mono text-sm text-gray-500">
                        [ CE TICKET EST VERROUILLÉ ET ARCHIVÉ ]
                    </div>
                )}
            </div>
        </div>
    );
}