import React, { useState, useEffect, useRef, useCallback } from 'react';
import { 
  MessageSquare, 
  Users, 
  Hash, 
  Plus, 
  Send, 
  Search,
  Settings,
  User,
  Circle,
  Trash2,
  Edit2,
  Megaphone,
  X,
  Check,
  AlertCircle
} from 'lucide-react';
import { toast } from 'react-toastify';
import teamChatService, { 
  TeamChannel, 
  TeamMessage, 
  TeamUser 
} from '../services/teamChatService';
import useAuthStore from '../../../store/useAuthStore';
import { normalizeImageUrl } from '../../../shared/utils/imageUtils';
import { formatDistanceToNow } from 'date-fns';

interface TeamChatPageProps {
  role: 'admin' | 'staff' | 'housekeeping';
}

const TeamChatPage: React.FC<TeamChatPageProps> = ({ role }) => {
  const { userInfo } = useAuthStore();
  const [channels, setChannels] = useState<TeamChannel[]>([]);
  const [selectedChannel, setSelectedChannel] = useState<TeamChannel | null>(null);
  const [messages, setMessages] = useState<TeamMessage[]>([]);
  const [teamUsers, setTeamUsers] = useState<TeamUser[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [isSending, setIsSending] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [showNewChannelModal, setShowNewChannelModal] = useState(false);
  const [showNewDMModal, setShowNewDMModal] = useState(false);
  const [editingMessage, setEditingMessage] = useState<number | null>(null);
  const [editContent, setEditContent] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [ws, setWs] = useState<WebSocket | null>(null);
  const selectedChannelRef = useRef<TeamChannel | null>(null);
  
  // Keep ref in sync with state
  useEffect(() => {
    selectedChannelRef.current = selectedChannel;
  }, [selectedChannel]);

  // Fetch channels
  const fetchChannels = useCallback(async () => {
    try {
      const response = await teamChatService.getMyChannels();
      if (response.success) {
        setChannels(response.data);
        // Auto-select first channel if none selected
        if (!selectedChannel && response.data.length > 0) {
          setSelectedChannel(response.data[0]);
        }
      }
    } catch (error) {
      console.error('Error fetching channels:', error);
    }
  }, [selectedChannel]);

  // Fetch team users
  const fetchTeamUsers = useCallback(async () => {
    try {
      const response = await teamChatService.getTeamUsers();
      if (response.success) {
        setTeamUsers(response.data);
      }
    } catch (error) {
      console.error('Error fetching team users:', error);
    }
  }, []);

  // Fetch messages for selected channel
  const fetchMessages = useCallback(async (channelId: number) => {
    try {
      const response = await teamChatService.getChannelMessages(channelId);
      if (response.success) {
        setMessages(response.data);
        // Scroll to bottom
        setTimeout(() => messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 100);
      }
    } catch (error) {
      console.error('Error fetching messages:', error);
    }
  }, []);

  // Initialize WebSocket
  useEffect(() => {
    if (!userInfo?.id) return;

    const wsUrl = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/api/v1/team-chat/ws`;
    const socket = new WebSocket(wsUrl);

    socket.onopen = () => {
      // Send authentication only when socket is open
      if (socket.readyState === WebSocket.OPEN) {
        try {
          socket.send(JSON.stringify({ type: 'auth', user_id: userInfo.id }));
        } catch (error) {
          console.error('Error sending WebSocket auth:', error);
        }
      }
    };

    socket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        
        // Use ref to get current selectedChannel without causing re-renders
        const currentChannel = selectedChannelRef.current;
        
        if (data.type === 'new_message' && data.data.channel_id === currentChannel?.id) {
          setMessages(prev => [...prev, data.data]);
          messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
        } else if (data.type === 'new_message_notification') {
          // Show notification for messages in other channels
          toast.info(`New message in ${data.data.channel_name || 'Team Chat'}`);
          fetchChannels(); // Refresh unread counts
        } else if (data.type === 'message_edited') {
          setMessages(prev => prev.map(m => m.id === data.data.id ? data.data : m));
        } else if (data.type === 'message_deleted') {
          setMessages(prev => prev.filter(m => m.id !== data.data.id));
        }
      } catch (error) {
        console.error('Error parsing WebSocket message:', error);
      }
    };

    socket.onerror = (error) => {
      console.error('WebSocket error:', error);
    };

    socket.onclose = () => {
      console.log('WebSocket closed');
    };

    setWs(socket);

    return () => {
      if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {
        socket.close();
      }
      setWs(null);
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userInfo?.id]); // Removed selectedChannel?.id and fetchChannels from dependencies

  // Initial data load
  useEffect(() => {
    const loadData = async () => {
      setIsLoading(true);
      await Promise.all([fetchChannels(), fetchTeamUsers()]);
      setIsLoading(false);
    };
    loadData();
  }, [fetchChannels, fetchTeamUsers]);

  // Load messages when channel changes
  useEffect(() => {
    if (selectedChannel) {
      fetchMessages(selectedChannel.id);
      // Join channel in WebSocket - only if socket is open
      if (ws && ws.readyState === WebSocket.OPEN) {
        try {
          ws.send(JSON.stringify({ type: 'join_channel', channel_id: selectedChannel.id }));
        } catch (error) {
          console.error('Error joining channel via WebSocket:', error);
        }
      }
    }
  }, [selectedChannel, fetchMessages, ws]);

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

    setIsSending(true);
    try {
      const response = await teamChatService.sendMessage(selectedChannel.id, {
        content: newMessage.trim()
      });
      if (response.success) {
        setMessages(prev => [...prev, response.data]);
        setNewMessage('');
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
      }
    } catch (error) {
      console.error('Error sending message:', error);
      toast.error('Failed to send message');
    } finally {
      setIsSending(false);
    }
  };

  // Edit message
  const handleEditMessage = async (messageId: number) => {
    if (!editContent.trim()) return;
    try {
      const response = await teamChatService.editMessage(messageId, editContent.trim());
      if (response.success) {
        setMessages(prev => prev.map(m => m.id === messageId ? response.data : m));
        setEditingMessage(null);
        setEditContent('');
        toast.success('Message edited');
      }
    } catch (error) {
      toast.error('Failed to edit message');
    }
  };

  // Delete message
  const handleDeleteMessage = async (messageId: number) => {
    if (!confirm('Delete this message?')) return;
    try {
      await teamChatService.deleteMessage(messageId);
      setMessages(prev => prev.filter(m => m.id !== messageId));
      toast.success('Message deleted');
    } catch (error) {
      toast.error('Failed to delete message');
    }
  };

  // Start DM
  const handleStartDM = async (userId: number) => {
    try {
      const response = await teamChatService.sendDirectMessage({
        recipient_id: userId,
        content: '👋 Hi!'
      });
      if (response.success) {
        await fetchChannels();
        const newChannel = channels.find(c => c.id === response.data.channel_id);
        if (newChannel) setSelectedChannel(newChannel);
        setShowNewDMModal(false);
        toast.success('Conversation started!');
      }
    } catch (error) {
      toast.error('Failed to start conversation');
    }
  };

  // Create channel
  const handleCreateChannel = async (name: string, memberIds: number[]) => {
    try {
      const response = await teamChatService.createChannel({
        name,
        channel_type: 'group',
        member_ids: memberIds
      });
      if (response.success) {
        await fetchChannels();
        setSelectedChannel(response.data);
        setShowNewChannelModal(false);
        toast.success('Channel created!');
      }
    } catch (error) {
      toast.error('Failed to create channel');
    }
  };

  // Get channel icon
  const getChannelIcon = (channel: TeamChannel) => {
    switch (channel.channel_type) {
      case 'direct':
        return <User className="w-4 h-4" />;
      case 'announcement':
        return <Megaphone className="w-4 h-4" />;
      case 'department':
        return <Users className="w-4 h-4" />;
      default:
        return <Hash className="w-4 h-4" />;
    }
  };

  // Filter channels
  const filteredChannels = channels.filter(c => 
    c.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    c.members.some(m => m.full_name.toLowerCase().includes(searchQuery.toLowerCase()))
  );

  // Get role color
  const getRoleColor = (userRole: string | null) => {
    switch (userRole) {
      case 'admin': return 'bg-purple-100 text-purple-700';
      case 'staff': return 'bg-blue-100 text-blue-700';
      case 'housekeeping': return 'bg-amber-100 text-amber-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  // Get status color
  const getStatusColor = (status?: string) => {
    switch (status) {
      case 'online': return 'bg-green-500';
      case 'away': return 'bg-yellow-500';
      case 'busy': return 'bg-red-500';
      default: return 'bg-gray-400';
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-[calc(100vh-100px)]">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading team chat...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-[calc(100vh-100px)] flex bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200">
      {/* Sidebar - Channels List */}
      <div className="w-72 bg-gradient-to-b from-gray-900 to-gray-800 flex flex-col">
        {/* Header */}
        <div className="p-4 border-b border-gray-700">
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-lg font-bold text-white flex items-center gap-2">
              <MessageSquare className="w-5 h-5 text-blue-400" />
              Team Chat
            </h2>
            <div className="flex gap-1">
              <button
                onClick={() => setShowNewDMModal(true)}
                className="p-2 hover:bg-gray-700 rounded-lg transition-colors text-gray-400 hover:text-white"
                title="New Direct Message"
              >
                <User className="w-4 h-4" />
              </button>
              <button
                onClick={() => setShowNewChannelModal(true)}
                className="p-2 hover:bg-gray-700 rounded-lg transition-colors text-gray-400 hover:text-white"
                title="New Channel"
              >
                <Plus className="w-4 h-4" />
              </button>
            </div>
          </div>
          
          {/* Search */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search channels..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-9 pr-4 py-2 bg-gray-700 border border-gray-600 rounded-lg text-sm text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
        </div>

        {/* Channels List */}
        <div className="flex-1 overflow-y-auto p-2">
          {/* Department Channels */}
          <div className="mb-4">
            <h3 className="px-2 py-1 text-xs font-semibold text-gray-400 uppercase tracking-wider">
              Channels
            </h3>
            {filteredChannels
              .filter(c => c.channel_type !== 'direct')
              .map(channel => (
                <button
                  key={channel.id}
                  onClick={() => setSelectedChannel(channel)}
                  className={`w-full flex items-center gap-2 px-3 py-2 rounded-lg text-left transition-colors ${
                    selectedChannel?.id === channel.id
                      ? 'bg-blue-600 text-white'
                      : 'text-gray-300 hover:bg-gray-700'
                  }`}
                >
                  {getChannelIcon(channel)}
                  <span className="flex-1 truncate text-sm font-medium">{channel.name}</span>
                  {channel.unread_count > 0 && (
                    <span className="bg-red-500 text-white text-xs px-2 py-0.5 rounded-full">
                      {channel.unread_count}
                    </span>
                  )}
                </button>
              ))}
          </div>

          {/* Direct Messages */}
          <div>
            <h3 className="px-2 py-1 text-xs font-semibold text-gray-400 uppercase tracking-wider">
              Direct Messages
            </h3>
            {filteredChannels
              .filter(c => c.channel_type === 'direct')
              .map(channel => {
                const otherMember = channel.members.find(m => m.id !== userInfo?.id);
                return (
                  <button
                    key={channel.id}
                    onClick={() => setSelectedChannel(channel)}
                    className={`w-full flex items-center gap-2 px-3 py-2 rounded-lg text-left transition-colors ${
                      selectedChannel?.id === channel.id
                        ? 'bg-blue-600 text-white'
                        : 'text-gray-300 hover:bg-gray-700'
                    }`}
                  >
                    <div className="relative">
                      {otherMember?.avatar_url ? (
                        <img
                          src={normalizeImageUrl(otherMember.avatar_url)}
                          alt=""
                          className="w-6 h-6 rounded-full"
                        />
                      ) : (
                        <div className="w-6 h-6 rounded-full bg-gray-600 flex items-center justify-center">
                          <User className="w-3 h-3 text-gray-300" />
                        </div>
                      )}
                      <Circle className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 ${getStatusColor('online')} rounded-full border-2 border-gray-800`} fill="currentColor" />
                    </div>
                    <span className="flex-1 truncate text-sm">
                      {otherMember?.full_name || 'Unknown'}
                    </span>
                    {channel.unread_count > 0 && (
                      <span className="bg-red-500 text-white text-xs px-2 py-0.5 rounded-full">
                        {channel.unread_count}
                      </span>
                    )}
                  </button>
                );
              })}
          </div>
        </div>

        {/* User Status */}
        <div className="p-3 border-t border-gray-700 bg-gray-800">
          <div className="flex items-center gap-2">
            <div className="relative">
              {userInfo?.avatar ? (
                <img
                  src={normalizeImageUrl(userInfo.avatar)}
                  alt=""
                  className="w-8 h-8 rounded-full"
                />
              ) : (
                <div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center">
                  <User className="w-4 h-4 text-white" />
                </div>
              )}
              <Circle className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 ${getStatusColor('online')} rounded-full border-2 border-gray-800`} fill="currentColor" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-white truncate">{userInfo?.name}</p>
              <p className="text-xs text-gray-400 capitalize">{role}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Main Chat Area */}
      <div className="flex-1 flex flex-col">
        {selectedChannel ? (
          <>
            {/* Channel Header */}
            <div className="px-4 py-3 border-b border-gray-200 bg-white flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className={`p-2 rounded-lg ${
                  selectedChannel.channel_type === 'announcement' 
                    ? 'bg-purple-100 text-purple-600'
                    : selectedChannel.channel_type === 'department'
                    ? 'bg-green-100 text-green-600'
                    : selectedChannel.channel_type === 'direct'
                    ? 'bg-blue-100 text-blue-600'
                    : 'bg-gray-100 text-gray-600'
                }`}>
                  {getChannelIcon(selectedChannel)}
                </div>
                <div>
                  <h3 className="font-semibold text-gray-900">{selectedChannel.name}</h3>
                  <p className="text-xs text-gray-500">
                    {selectedChannel.members.length} members
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <button className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
                  <Users className="w-5 h-5 text-gray-500" />
                </button>
                <button className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
                  <Settings className="w-5 h-5 text-gray-500" />
                </button>
              </div>
            </div>

            {/* Messages Area */}
            <div className="flex-1 overflow-y-auto p-4 bg-gray-50">
              {messages.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-full text-gray-500">
                  <MessageSquare className="w-12 h-12 mb-3 opacity-50" />
                  <p>No messages yet</p>
                  <p className="text-sm">Start the conversation!</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {messages.map((message, index) => {
                    const isOwn = message.sender_id === userInfo?.id;
                    const showAvatar = index === 0 || 
                      messages[index - 1]?.sender_id !== message.sender_id;
                    
                    return (
                      <div
                        key={message.id}
                        className={`flex gap-3 group ${isOwn ? 'flex-row-reverse' : ''}`}
                      >
                        {/* Avatar */}
                        <div className="w-8 flex-shrink-0">
                          {showAvatar && (
                            message.sender?.avatar_url ? (
                              <img
                                src={normalizeImageUrl(message.sender.avatar_url)}
                                alt=""
                                className="w-8 h-8 rounded-full"
                              />
                            ) : (
                              <div className="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center">
                                <User className="w-4 h-4 text-gray-500" />
                              </div>
                            )
                          )}
                        </div>

                        {/* Message Content */}
                        <div className={`max-w-[70%] ${isOwn ? 'items-end' : ''}`}>
                          {showAvatar && (
                            <div className={`flex items-center gap-2 mb-1 ${isOwn ? 'flex-row-reverse' : ''}`}>
                              <span className="text-sm font-medium text-gray-900">
                                {message.sender?.full_name || 'Unknown'}
                              </span>
                              {message.sender?.role && (
                                <span className={`text-xs px-2 py-0.5 rounded-full ${getRoleColor(message.sender.role)}`}>
                                  {message.sender.role}
                                </span>
                              )}
                              <span className="text-xs text-gray-400">
                                {formatDistanceToNow(new Date(message.created_at), { addSuffix: true })}
                              </span>
                            </div>
                          )}
                          
                          {editingMessage === message.id ? (
                            <div className="flex gap-2">
                              <input
                                type="text"
                                value={editContent}
                                onChange={(e) => setEditContent(e.target.value)}
                                className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500"
                                autoFocus
                              />
                              <button
                                onClick={() => handleEditMessage(message.id)}
                                className="p-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                              >
                                <Check className="w-4 h-4" />
                              </button>
                              <button
                                onClick={() => { setEditingMessage(null); setEditContent(''); }}
                                className="p-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400"
                              >
                                <X className="w-4 h-4" />
                              </button>
                            </div>
                          ) : (
                            <div className={`relative group px-4 py-2 rounded-2xl ${
                              isOwn 
                                ? 'bg-blue-600 text-white rounded-br-md'
                                : 'bg-white text-gray-900 border border-gray-200 rounded-bl-md'
                            } ${message.priority === 'urgent' ? 'ring-2 ring-red-500' : ''}`}>
                              <p className="text-sm whitespace-pre-wrap break-words">
                                {message.content}
                              </p>
                              {message.is_edited && (
                                <span className={`text-xs ${isOwn ? 'text-blue-200' : 'text-gray-400'}`}>
                                  (edited)
                                </span>
                              )}
                              
                              {/* Message Actions */}
                              {isOwn && (
                                <div className="absolute -top-2 right-0 hidden group-hover:flex gap-1 bg-white rounded-lg shadow-lg border border-gray-200 p-1">
                                  <button
                                    onClick={() => { setEditingMessage(message.id); setEditContent(message.content); }}
                                    className="p-1 hover:bg-gray-100 rounded text-gray-500"
                                    title="Edit"
                                  >
                                    <Edit2 className="w-3 h-3" />
                                  </button>
                                  <button
                                    onClick={() => handleDeleteMessage(message.id)}
                                    className="p-1 hover:bg-red-100 rounded text-red-500"
                                    title="Delete"
                                  >
                                    <Trash2 className="w-3 h-3" />
                                  </button>
                                </div>
                              )}
                            </div>
                          )}
                        </div>
                      </div>
                    );
                  })}
                  <div ref={messagesEndRef} />
                </div>
              )}
            </div>

            {/* Message Input */}
            <form onSubmit={handleSendMessage} className="p-4 bg-white border-t border-gray-200">
              <div className="flex gap-3">
                <input
                  type="text"
                  value={newMessage}
                  onChange={(e) => setNewMessage(e.target.value)}
                  placeholder={`Message ${selectedChannel.name}...`}
                  className="flex-1 px-4 py-3 bg-gray-100 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent focus:bg-white transition-colors"
                  disabled={selectedChannel.channel_type === 'announcement' && role !== 'admin'}
                />
                <button
                  type="submit"
                  disabled={!newMessage.trim() || isSending || (selectedChannel.channel_type === 'announcement' && role !== 'admin')}
                  className="px-6 py-3 bg-blue-600 text-white rounded-xl font-medium hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-2"
                >
                  <Send className="w-4 h-4" />
                  Send
                </button>
              </div>
              {selectedChannel.channel_type === 'announcement' && role !== 'admin' && (
                <p className="text-xs text-gray-500 mt-2 flex items-center gap-1">
                  <AlertCircle className="w-3 h-3" />
                  Only admins can post in announcement channels
                </p>
              )}
            </form>
          </>
        ) : (
          <div className="flex-1 flex items-center justify-center bg-gray-50">
            <div className="text-center">
              <MessageSquare className="w-16 h-16 mx-auto mb-4 text-gray-300" />
              <h3 className="text-xl font-semibold text-gray-700 mb-2">Welcome to Team Chat</h3>
              <p className="text-gray-500 max-w-md">
                Select a channel or start a new conversation to communicate with your team.
              </p>
              <div className="mt-6 flex gap-3 justify-center">
                <button
                  onClick={() => setShowNewChannelModal(true)}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors flex items-center gap-2"
                >
                  <Plus className="w-4 h-4" />
                  New Channel
                </button>
                <button
                  onClick={() => setShowNewDMModal(true)}
                  className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors flex items-center gap-2"
                >
                  <User className="w-4 h-4" />
                  New Message
                </button>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* New Channel Modal */}
      {showNewChannelModal && (
        <NewChannelModal
          users={teamUsers}
          onClose={() => setShowNewChannelModal(false)}
          onCreate={handleCreateChannel}
        />
      )}

      {/* New DM Modal */}
      {showNewDMModal && (
        <NewDMModal
          users={teamUsers}
          onClose={() => setShowNewDMModal(false)}
          onSelect={handleStartDM}
        />
      )}
    </div>
  );
};

// New Channel Modal Component
const NewChannelModal: React.FC<{
  users: TeamUser[];
  onClose: () => void;
  onCreate: (name: string, memberIds: number[]) => void;
}> = ({ users, onClose, onCreate }) => {
  const [name, setName] = useState('');
  const [selectedUsers, setSelectedUsers] = useState<number[]>([]);
  const [search, setSearch] = useState('');

  const filteredUsers = users.filter(u =>
    u.full_name.toLowerCase().includes(search.toLowerCase()) ||
    u.email.toLowerCase().includes(search.toLowerCase())
  );

  const toggleUser = (userId: number) => {
    setSelectedUsers(prev =>
      prev.includes(userId) ? prev.filter(id => id !== userId) : [...prev, userId]
    );
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl">
        <div className="p-4 border-b border-gray-200 flex items-center justify-between">
          <h3 className="text-lg font-semibold">Create Channel</h3>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
            <X className="w-5 h-5" />
          </button>
        </div>
        <div className="p-4 space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Channel Name</label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g., morning-shift"
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Add Members</label>
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search team members..."
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 mb-2"
            />
            <div className="max-h-48 overflow-y-auto border border-gray-200 rounded-lg">
              {filteredUsers.map(user => (
                <button
                  key={user.id}
                  onClick={() => toggleUser(user.id)}
                  className={`w-full flex items-center gap-3 p-3 hover:bg-gray-50 transition-colors ${
                    selectedUsers.includes(user.id) ? 'bg-blue-50' : ''
                  }`}
                >
                  <div className={`w-5 h-5 rounded border-2 flex items-center justify-center ${
                    selectedUsers.includes(user.id) ? 'border-blue-600 bg-blue-600' : 'border-gray-300'
                  }`}>
                    {selectedUsers.includes(user.id) && <Check className="w-3 h-3 text-white" />}
                  </div>
                  {user.avatar_url ? (
                    <img src={normalizeImageUrl(user.avatar_url)} alt="" className="w-8 h-8 rounded-full" />
                  ) : (
                    <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                      <User className="w-4 h-4 text-gray-500" />
                    </div>
                  )}
                  <div className="flex-1 text-left">
                    <p className="text-sm font-medium">{user.full_name}</p>
                    <p className="text-xs text-gray-500 capitalize">{user.role}</p>
                  </div>
                </button>
              ))}
            </div>
          </div>
        </div>
        <div className="p-4 border-t border-gray-200 flex gap-3">
          <button
            onClick={onClose}
            className="flex-1 px-4 py-2 border border-gray-300 rounded-lg font-medium hover:bg-gray-50"
          >
            Cancel
          </button>
          <button
            onClick={() => onCreate(name, selectedUsers)}
            disabled={!name.trim()}
            className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 disabled:opacity-50"
          >
            Create Channel
          </button>
        </div>
      </div>
    </div>
  );
};

// New DM Modal Component
const NewDMModal: React.FC<{
  users: TeamUser[];
  onClose: () => void;
  onSelect: (userId: number) => void;
}> = ({ users, onClose, onSelect }) => {
  const [search, setSearch] = useState('');

  const filteredUsers = users.filter(u =>
    u.full_name.toLowerCase().includes(search.toLowerCase()) ||
    u.email.toLowerCase().includes(search.toLowerCase())
  );

  const getRoleColor = (role: string | null) => {
    switch (role) {
      case 'admin': return 'bg-purple-100 text-purple-700';
      case 'staff': return 'bg-blue-100 text-blue-700';
      case 'housekeeping': return 'bg-amber-100 text-amber-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl">
        <div className="p-4 border-b border-gray-200 flex items-center justify-between">
          <h3 className="text-lg font-semibold">New Message</h3>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-lg">
            <X className="w-5 h-5" />
          </button>
        </div>
        <div className="p-4">
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search team members..."
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 mb-4"
            autoFocus
          />
          <div className="max-h-80 overflow-y-auto">
            {filteredUsers.length === 0 ? (
              <p className="text-center text-gray-500 py-8">No team members found</p>
            ) : (
              filteredUsers.map(user => (
                <button
                  key={user.id}
                  onClick={() => onSelect(user.id)}
                  className="w-full flex items-center gap-3 p-3 hover:bg-gray-50 rounded-lg transition-colors"
                >
                  {user.avatar_url ? (
                    <img src={normalizeImageUrl(user.avatar_url)} alt="" className="w-10 h-10 rounded-full" />
                  ) : (
                    <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
                      <User className="w-5 h-5 text-gray-500" />
                    </div>
                  )}
                  <div className="flex-1 text-left">
                    <p className="font-medium text-gray-900">{user.full_name}</p>
                    <p className="text-sm text-gray-500">{user.email}</p>
                  </div>
                  <span className={`text-xs px-2 py-1 rounded-full ${getRoleColor(user.role)}`}>
                    {user.role}
                  </span>
                </button>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default TeamChatPage;

