import React, { useEffect, useState, useRef } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import { getPageTitle } from '../config';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { fetch as fetchConversations } from '../stores/conversations/conversationsSlice';
import { fetch as fetchMessages, create as createMessage } from '../stores/messages/messagesSlice';
import UserAvatar from '../components/UserAvatar';
import BaseIcon from '../components/BaseIcon';
import { mdiSend, mdiImageOutline, mdiDotsVertical, mdiMagnify } from '@mdi/js';
import dataFormatter from '../helpers/dataFormatter';

export default function MessagesPage() {
    const dispatch = useAppDispatch();
    const { conversations, loading: convLoading } = useAppSelector((state) => state.conversations);
    const { messages, loading: msgLoading } = useAppSelector((state) => state.messages);
    const { currentUser } = useAppSelector((state) => state.auth);
    
    const [selectedConversation, setSelectedConversation] = useState<any>(null);
    const [newMessage, setNewMessage] = useState('');
    const messagesEndRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        dispatch(fetchConversations({ page: 1, limit: 20 }));
    }, [dispatch]);

    useEffect(() => {
        if (selectedConversation) {
            dispatch(fetchMessages({ query: `?conversation=${selectedConversation.id}&limit=50&page=0` }));
        }
    }, [selectedConversation, dispatch]);

    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    const handleSendMessage = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!newMessage.trim() || !selectedConversation || !currentUser) return;

        try {
            await dispatch(createMessage({
                body: newMessage,
                message_type: 'text',
                sent_at: new Date().toISOString(),
                conversation: selectedConversation.id,
                sender: currentUser.id,
                delivery_status: 'sent'
            })).unwrap();
            setNewMessage('');
            dispatch(fetchMessages({ query: `?conversation=${selectedConversation.id}&limit=50&page=0` }));
        } catch (err) {
            console.error('Failed to send message', err);
        }
    };

    const getChatPartner = (conv: any) => {
        if (conv.conversation_type === 'group') return { name: conv.title, avatar: conv.group_image };
        const otherMember = conv.conversation_members_conversation?.find((m: any) => m.user?.id !== currentUser?.id);
        return { 
            name: otherMember ? `${otherMember.user.firstName} ${otherMember.user.lastName}` : 'Chat',
            avatar: otherMember?.user?.avatar
        };
    };

    return (
        <>
            <Head>
                <title>{getPageTitle('Messages')}</title>
            </Head>
            <SectionMain className="h-[calc(100vh-80px)] p-0">
                <div className="flex h-full overflow-hidden bg-white dark:bg-[#0b0e14]">
                    {/* Sidebar: Chat List */}
                    <div className="w-80 border-r border-gray-200 dark:border-gray-800 flex flex-col h-full bg-gray-50 dark:bg-[#1a1d23]/30">
                        <div className="p-4 border-b border-gray-200 dark:border-gray-800">
                            <h2 className="text-xl font-black dark:text-white mb-4">Messages</h2>
                            <div className="relative">
                                <BaseIcon path={mdiMagnify} className="absolute left-3 top-2.5 text-gray-400" size={18} />
                                <input 
                                    type="text" 
                                    placeholder="Search chats..." 
                                    className="w-full bg-white dark:bg-[#0b0e14] border-gray-200 dark:border-gray-800 rounded-xl pl-10 text-sm py-2 focus:ring-[#00d4ff] focus:border-[#00d4ff]"
                                />
                            </div>
                        </div>
                        
                        <div className="flex-1 overflow-y-auto">
                            {conversations.map((conv: any) => {
                                const partner = getChatPartner(conv);
                                const isActive = selectedConversation?.id === conv.id;
                                return (
                                    <div 
                                        key={conv.id} 
                                        onClick={() => setSelectedConversation(conv)}
                                        className={`flex items-center p-4 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800/50 transition-colors ${isActive ? 'bg-white dark:bg-gray-800/80 border-l-4 border-[#00d4ff]' : ''}`}
                                    >
                                        <UserAvatar username={partner.name} image={partner.avatar} className="w-12 h-12 flex-shrink-0" />
                                        <div className="ml-3 flex-1 overflow-hidden">
                                            <div className="flex justify-between items-baseline">
                                                <h3 className="text-sm font-bold dark:text-white truncate">{partner.name}</h3>
                                                <span className="text-[10px] text-gray-400">
                                                    {conv.last_message_at ? dataFormatter.dateTimeFormatter(conv.last_message_at) : ''}
                                                </span>
                                            </div>
                                            <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
                                                {conv.last_message_body || 'No messages yet'}
                                            </p>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </div>

                    {/* Main Chat Area */}
                    <div className="flex-1 flex flex-col h-full bg-white dark:bg-[#0b0e14]">
                        {selectedConversation ? (
                            <>
                                {/* Chat Header */}
                                <div className="p-4 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between bg-white dark:bg-[#0b0e14]">
                                    <div className="flex items-center">
                                        <UserAvatar 
                                            username={getChatPartner(selectedConversation).name} 
                                            image={getChatPartner(selectedConversation).avatar} 
                                            className="w-10 h-10" 
                                        />
                                        <div className="ml-3">
                                            <h3 className="font-bold text-sm dark:text-white">{getChatPartner(selectedConversation).name}</h3>
                                            <p className="text-[10px] text-green-500 font-medium">Online</p>
                                        </div>
                                    </div>
                                    <button className="text-gray-400 hover:text-gray-600 dark:hover:text-white">
                                        <BaseIcon path={mdiDotsVertical} size={24} />
                                    </button>
                                </div>

                                {/* Messages Area */}
                                <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50 dark:bg-[#0b0e14]">
                                    {messages.map((msg: any) => {
                                        const isMine = msg.sender?.id === currentUser?.id;
                                        return (
                                            <div key={msg.id} className={`flex ${isMine ? 'justify-end' : 'justify-start'}`}>
                                                {!isMine && (
                                                    <UserAvatar 
                                                        username={msg.sender?.firstName || 'User'} 
                                                        image={msg.sender?.avatar} 
                                                        className="w-8 h-8 self-end mr-2 mb-1" 
                                                    />
                                                )}
                                                <div className={`max-w-[70%] group`}>
                                                    <div className={`p-3 rounded-2xl text-sm ${
                                                        isMine 
                                                            ? 'bg-[#00d4ff] text-white rounded-br-none' 
                                                            : 'bg-white dark:bg-gray-800 dark:text-white border border-gray-200 dark:border-gray-700 rounded-bl-none'
                                                    }`}>
                                                        {msg.body}
                                                    </div>
                                                    <p className={`text-[9px] text-gray-400 mt-1 ${isMine ? 'text-right' : 'text-left'}`}>
                                                        {dataFormatter.dateTimeFormatter(msg.sent_at)}
                                                    </p>
                                                </div>
                                            </div>
                                        );
                                    })}
                                    <div ref={messagesEndRef} />
                                </div>

                                {/* Message Input */}
                                <form onSubmit={handleSendMessage} className="p-4 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-[#0b0e14]">
                                    <div className="flex items-center bg-gray-100 dark:bg-gray-800 rounded-2xl px-4 py-2">
                                        <button type="button" className="text-gray-400 hover:text-[#00d4ff]">
                                            <BaseIcon path={mdiImageOutline} size={24} />
                                        </button>
                                        <input 
                                            type="text" 
                                            placeholder="Type a message..." 
                                            className="flex-1 bg-transparent border-none focus:ring-0 text-sm dark:text-white mx-2"
                                            value={newMessage}
                                            onChange={(e) => setNewMessage(e.target.value)}
                                        />
                                        <button 
                                            type="submit" 
                                            disabled={!newMessage.trim()}
                                            className="text-[#00d4ff] hover:scale-110 transition-transform disabled:opacity-50"
                                        >
                                            <BaseIcon path={mdiSend} size={24} />
                                        </button>
                                    </div>
                                </form>
                            </>
                        ) : (
                            <div className="flex-1 flex flex-col items-center justify-center text-center p-8">
                                <div className="w-20 h-20 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mb-4">
                                    <BaseIcon path={mdiChatOutline} size={40} className="text-gray-400" />
                                </div>
                                <h3 className="text-lg font-bold dark:text-white">Your Messages</h3>
                                <p className="text-sm text-gray-500 dark:text-gray-400 max-w-xs mt-2">
                                    Select a conversation from the sidebar to start chatting or create a new one.
                                </p>
                            </div>
                        )}
                    </div>
                </div>
            </SectionMain>
        </>
    );
}

MessagesPage.getLayout = function getLayout(page: ReactElement) {
    return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};