import React, { useState, useEffect } from 'react';
import { useMessaging, useConversations, useMessages, useNotifications } from '../../hooks/useMessaging';
import { Conversation, Message } from '../../types';

const MessagingExample: React.FC = () => {
  const { conversations, currentConversation, setCurrentConversation, createConversation } = useConversations();
  const { messages, sendMessage, isLoading } = useMessages(currentConversation?.id);
  const { notifications, unreadCount } = useNotifications();
  const [newMessage, setNewMessage] = useState('');
  const [newConversationName, setNewConversationName] = useState('');

  // Load conversations on mount
  useEffect(() => {
    // This would typically be called when the component mounts
    // refreshConversations();
  }, []);

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

    try {
      await sendMessage(newMessage);
      setNewMessage('');
    } catch (error) {
      console.error('Failed to send message:', error);
    }
  };

  const handleCreateConversation = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newConversationName.trim()) return;

    try {
      // This would typically get participant IDs from a user selection
      const participantIds = [1, 2]; // Example participant IDs
      await createConversation('group', participantIds, newConversationName);
      setNewConversationName('');
    } catch (error) {
      console.error('Failed to create conversation:', error);
    }
  };

  const formatMessageTime = (timestamp: string) => {
    return new Date(timestamp).toLocaleTimeString();
  };

  return (
    <div className="flex h-screen bg-gray-100">
      {/* Sidebar */}
      <div className="w-1/3 bg-white border-r border-gray-200 flex flex-col">
        {/* Header */}
        <div className="p-4 border-b border-gray-200">
          <h2 className="text-lg font-semibold">Messages</h2>
          <p className="text-sm text-gray-500">{unreadCount} unread messages</p>
        </div>

        {/* Create Conversation Form */}
        <div className="p-4 border-b border-gray-200">
          <form onSubmit={handleCreateConversation} className="flex gap-2">
            <input
              type="text"
              value={newConversationName}
              onChange={(e) => setNewConversationName(e.target.value)}
              placeholder="Create group conversation..."
              className="flex-1 px-3 py-2 border border-gray-300 rounded-md text-sm"
            />
            <button
              type="submit"
              className="px-4 py-2 bg-blue-500 text-white rounded-md text-sm hover:bg-blue-600"
            >
              Create
            </button>
          </form>
        </div>

        {/* Conversations List */}
        <div className="flex-1 overflow-y-auto">
          {conversations.map((conversation) => (
            <div
              key={conversation.id}
              onClick={() => setCurrentConversation(conversation)}
              className={`p-4 border-b border-gray-100 cursor-pointer hover:bg-gray-50 ${
                currentConversation?.id === conversation.id ? 'bg-blue-50 border-l-4 border-l-blue-500' : ''
              }`}
            >
              <div className="flex justify-between items-start">
                <div className="flex-1">
                  <h3 className="font-medium text-gray-900">
                    {conversation.name || 'Direct Message'}
                  </h3>
                  <p className="text-sm text-gray-500 truncate">
                    {conversation.last_message?.content || 'No messages yet'}
                  </p>
                </div>
                <div className="text-xs text-gray-400">
                  {conversation.last_message && formatMessageTime(conversation.last_message.created_at)}
                </div>
              </div>
              {conversation.unread_count > 0 && (
                <div className="mt-1">
                  <span className="inline-block bg-red-500 text-white text-xs px-2 py-1 rounded-full">
                    {conversation.unread_count}
                  </span>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Main Chat Area */}
      <div className="flex-1 flex flex-col">
        {currentConversation ? (
          <>
            {/* Chat Header */}
            <div className="p-4 border-b border-gray-200 bg-white">
              <h3 className="font-semibold text-gray-900">
                {currentConversation.name || 'Direct Message'}
              </h3>
              <p className="text-sm text-gray-500">
                {currentConversation.participants.length} participants
              </p>
            </div>

            {/* Messages */}
            <div className="flex-1 overflow-y-auto p-4 space-y-4">
              {isLoading ? (
                <div className="text-center text-gray-500">Loading messages...</div>
              ) : (
                messages.map((message) => (
                  <div
                    key={message.id}
                    className={`flex ${message.sender_id === 1 ? 'justify-end' : 'justify-start'}`}
                  >
                    <div
                      className={`max-w-xs lg:max-w-md px-4 py-2 rounded-lg ${
                        message.sender_id === 1
                          ? 'bg-blue-500 text-white'
                          : 'bg-gray-200 text-gray-900'
                      }`}
                    >
                      <div className="text-sm">{message.content}</div>
                      <div className="text-xs opacity-75 mt-1">
                        {formatMessageTime(message.created_at)}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>

            {/* Message Input */}
            <div className="p-4 border-t border-gray-200 bg-white">
              <form onSubmit={handleSendMessage} className="flex gap-2">
                <input
                  type="text"
                  value={newMessage}
                  onChange={(e) => setNewMessage(e.target.value)}
                  placeholder="Type a message..."
                  className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
                <button
                  type="submit"
                  disabled={!newMessage.trim()}
                  className="px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Send
                </button>
              </form>
            </div>
          </>
        ) : (
          <div className="flex-1 flex items-center justify-center text-gray-500">
            <div className="text-center">
              <h3 className="text-lg font-medium mb-2">No conversation selected</h3>
              <p>Select a conversation from the sidebar to start messaging</p>
            </div>
          </div>
        )}
      </div>

      {/* Notifications Panel */}
      <div className="w-80 bg-white border-l border-gray-200 flex flex-col">
        <div className="p-4 border-b border-gray-200">
          <h3 className="font-semibold text-gray-900">Notifications</h3>
        </div>
        <div className="flex-1 overflow-y-auto p-4">
          {notifications.length === 0 ? (
            <p className="text-gray-500 text-sm">No notifications</p>
          ) : (
            notifications.map((notification) => (
              <div
                key={notification.id}
                className={`p-3 border-b border-gray-100 ${
                  !notification.is_read ? 'bg-blue-50' : ''
                }`}
              >
                <h4 className="font-medium text-sm text-gray-900">{notification.title}</h4>
                <p className="text-xs text-gray-600 mt-1">{notification.message}</p>
                <p className="text-xs text-gray-400 mt-1">
                  {formatMessageTime(notification.created_at)}
                </p>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
};

export default MessagingExample;
