import { useState, useRef, useEffect } from 'react';
import { getWorkNotes, createWorkNoteMultipart, getWorkflowDetails, downloadWorkNoteAttachment, getWorkNoteAttachmentPreviewUrl } from '@/services/workflowApi';
import { sanitizeHTML } from '@/utils/sanitizer';
import { toast } from 'sonner';
import { getSocket, joinRequestRoom, leaveRequestRoom } from '@/utils/socket';
import { formatDateTime } from '@/utils/dateFormatter';
import { FilePreview } from '@/components/common/FilePreview';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import {
  Send,
  Smile,
  Paperclip,
  FileText,
  Download,
  Clock,
  Flag,
  X,
  FileSpreadsheet,
  Image,
  AtSign,
  Activity,
  Search,
  MessageSquare,
  Plus,
  Eye
} from 'lucide-react';
import { Input } from '@/components/ui/input';

interface Message {
  id: string;
  user: {
    name: string;
    avatar: string;
    role: string;
  };
  content: string;
  timestamp: string;
  mentions?: string[];
  isSystem?: boolean;
  attachments?: {
    name: string;
    url: string;
    type: string;
  }[];
  reactions?: {
    emoji: string;
    users: string[];
  }[];
  isHighPriority?: boolean;
}

interface WorkNoteChatSimpleProps {
  requestId: string;
  messages?: any[];
  onSend?: (messageHtml: string, files: File[]) => Promise<void> | void;
}

const formatMessage = (content: string) => {
  const formattedContent = content
    .replace(/@([\w\s]+)(?=\s|$|[.,!?])/g, '<span class="inline-flex items-center px-2 py-1 rounded-md bg-blue-100 text-blue-800 font-medium text-sm">@$1</span>')
    .replace(/\n/g, '<br />');

  return sanitizeHTML(formattedContent);
};

const FileIcon = ({ type }: { type: string }) => {
  const iconClass = "w-4 h-4";
  const lowerType = type.toLowerCase();
  if (lowerType.includes('pdf')) return <FileText className={`${iconClass} text-red-600`} />;
  if (lowerType.includes('excel') || lowerType.includes('spreadsheet') || lowerType.includes('xlsx')) return <FileSpreadsheet className={`${iconClass} text-green-600`} />;
  if (lowerType.includes('powerpoint') || lowerType.includes('presentation') || lowerType.includes('pptx')) return <FileText className={`${iconClass} text-orange-600`} />;
  if (lowerType.includes('word') || lowerType.includes('document') || lowerType.includes('docx')) return <FileText className={`${iconClass} text-blue-600`} />;
  if (lowerType.includes('image') || lowerType.includes('png') || lowerType.includes('jpg') || lowerType.includes('jpeg')) return <Image className={`${iconClass} text-purple-600`} />;
  return <Paperclip className={`${iconClass} text-gray-600`} />;
};

const formatFileSize = (bytes: number): string => {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
};

const formatParticipantRole = (role: string | undefined): string => {
  if (!role) return 'Participant';
  const roleUpper = role.toUpperCase();
  switch (roleUpper) {
    case 'INITIATOR': return 'Initiator';
    case 'APPROVER': return 'Approver';
    case 'SPECTATOR': return 'Spectator';
    default: return role.charAt(0).toUpperCase() + role.slice(1).toLowerCase();
  }
};

export function WorkNoteChatSimple({ requestId, messages: externalMessages, onSend }: WorkNoteChatSimpleProps) {
  const [message, setMessage] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [currentUserId, setCurrentUserId] = useState<string | null>(null);
  const [previewFile, setPreviewFile] = useState<{ fileName: string; fileType: string; fileUrl: string; fileSize?: number; attachmentId?: string } | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const filteredMessages = messages.filter(msg =>
    msg.content.toLowerCase().includes(searchTerm.toLowerCase()) ||
    msg.user.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // Load current user ID on mount
  useEffect(() => {
    const userDataStr = localStorage.getItem('userData');
    if (userDataStr) {
      try {
        const userData = JSON.parse(userDataStr);
        const userId = userData?.id || userData?.userId || userData?.user_id || null;
        setCurrentUserId(userId);
      } catch (err) {
        console.error('[WorkNoteChat] Failed to parse userData:', err);
      }
    }
  }, []);

  // Realtime updates via Socket.IO
  useEffect(() => {
    if (!currentUserId) return; // Wait for currentUserId to be loaded

    let joinedId = requestId;
    (async () => {
      try {
        const details = await getWorkflowDetails(requestId);
        if (details?.workflow?.requestId) {
          joinedId = details.workflow.requestId;
        }
      } catch { }
      try {
        // Get socket using helper function (handles VITE_BASE_URL or VITE_API_BASE_URL)
        const s = getSocket(); // Uses getSocketBaseUrl() helper internally

        joinRequestRoom(s, joinedId, currentUserId || undefined);

        const noteHandler = (payload: any) => {
          const n = payload?.note || payload;
          if (!n) return;

          setMessages(prev => {
            if (prev.some(m => m.id === (n.noteId || n.note_id || n.id))) {
              return prev;
            }

            const userName = n.userName || n.user_name || 'User';
            const userRole = n.userRole || n.user_role;
            const participantRole = formatParticipantRole(userRole);
            const noteUserId = n.userId || n.user_id;

            const newMsg = {
              id: n.noteId || n.note_id || String(Date.now()),
              user: {
                name: userName,
                avatar: userName.split(' ').map((s: string) => s[0]).filter(Boolean).join('').slice(0, 2).toUpperCase(),
                role: participantRole
              },
              content: n.message || '',
              timestamp: n.createdAt || n.created_at || new Date().toISOString(),
              isCurrentUser: noteUserId === currentUserId
            } as any;

            return [...prev, newMsg];
          });
        };

        s.on('worknote:new', noteHandler);

        const cleanup = () => {
          s.off('worknote:new', noteHandler);
          leaveRequestRoom(s, joinedId);
        };
        (window as any).__wn_cleanup = cleanup;
      } catch (err) {
        console.error('[WorkNoteChat] Socket setup error:', err);
      }
    })();
    return () => {
      try { (window as any).__wn_cleanup?.(); } catch { }
    };
  }, [requestId, currentUserId]);

  const handleSendMessage = async () => {
    if (message.trim() || selectedFiles.length > 0) {
      if (onSend) {
        try { await onSend(message, selectedFiles); } catch { /* ignore */ }
      } else {
        try {
          await createWorkNoteMultipart(requestId, { message }, selectedFiles);
          const rows = await getWorkNotes(requestId);
          const mapped = Array.isArray(rows) ? rows.map((m: any) => {
            const userName = m.userName || m.user_name || 'User';
            const userRole = m.userRole || m.user_role;
            const participantRole = formatParticipantRole(userRole);

            return {
              id: m.noteId || m.note_id || m.id || String(Math.random()),
              user: {
                name: userName,
                avatar: userName.split(' ').map((s: string) => s[0]).filter(Boolean).join('').slice(0, 2).toUpperCase(),
                role: participantRole
              },
              content: m.message || '',
              timestamp: m.createdAt || m.created_at || new Date().toISOString(),
            };
          }) : [];
          setMessages(mapped as any);
        } catch { }
      }
      setMessage('');
      setSelectedFiles([]);
    }
  };

  // Load messages
  useEffect(() => {
    if (externalMessages && Array.isArray(externalMessages)) {
      try {
        const mapped: Message[] = externalMessages.map((m: any) => {
          const userName = m.userName || m.user_name || m.user?.name || 'User';
          const userRole = m.userRole || m.user_role;
          const participantRole = formatParticipantRole(userRole);
          const noteUserId = m.userId || m.user_id;

          return {
            id: m.noteId || m.note_id || m.id || String(Math.random()),
            user: {
              name: userName,
              avatar: userName.split(' ').map((s: string) => s[0]).filter(Boolean).join('').slice(0, 2).toUpperCase(),
              role: participantRole
            },
            content: m.message || m.content || '',
            timestamp: m.createdAt || m.created_at || m.timestamp || new Date().toISOString(),
            attachments: Array.isArray(m.attachments) ? m.attachments.map((a: any) => ({
              attachmentId: a.attachmentId || a.attachment_id,
              name: a.fileName || a.file_name || a.name,
              fileName: a.fileName || a.file_name || a.name,
              url: a.storageUrl || a.storage_url || a.url || '#',
              type: a.fileType || a.file_type || a.type || 'file',
              fileType: a.fileType || a.file_type || a.type || 'file',
              fileSize: a.fileSize || a.file_size
            })) : undefined,
            isCurrentUser: noteUserId === currentUserId
          } as any;
        });
        setMessages(mapped);
      } catch { }
    } else {
      (async () => {
        try {
          const rows = await getWorkNotes(requestId);

          const mapped = Array.isArray(rows) ? rows.map((m: any) => {
            const userName = m.userName || m.user_name || 'User';
            const userRole = m.userRole || m.user_role;
            const participantRole = formatParticipantRole(userRole);
            const noteUserId = m.userId || m.user_id;

            return {
              id: m.noteId || m.note_id || m.id || String(Math.random()),
              user: {
                name: userName,
                avatar: userName.split(' ').map((s: string) => s[0]).filter(Boolean).join('').slice(0, 2).toUpperCase(),
                role: participantRole
              },
              content: m.message || '',
              timestamp: m.createdAt || m.created_at || new Date().toISOString(),
              isCurrentUser: noteUserId === currentUserId
            };
          }) : [];
          setMessages(mapped as any);
        } catch (err) {
          console.error('[WorkNoteChat] Error loading notes:', err);
        }
      })();
    }
  }, [externalMessages, requestId, currentUserId]);

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const filesArray = Array.from(e.target.files);
      setSelectedFiles(prev => [...prev, ...filesArray]);
    }
  };

  const handleRemoveFile = (index: number) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index));
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleEmojiSelect = (emoji: string) => {
    setMessage(prev => prev + emoji);
    setShowEmojiPicker(false);
  };

  const handleAttachmentClick = () => {
    fileInputRef.current?.click();
  };

  const emojiList = [
    '😊', '😂', '🤣', '😁', '😃', '😄', '😅', '😆', '😉', '😌',
    '😍', '🥰', '😘', '😗', '😙', '😚', '🙂', '🤗', '🤩', '🤔',
    '👍', '👎', '✊', '👊', '👏', '🙌', '👐', '🤝', '🙏',
    '❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '💔',
    '💼', '📊', '📈', '📉', '💻', '📱', '📧', '✉️', '📄', '📝',
    '✅', '✔️', '☑️', '🎯', '🏆', '⭐', '🌟', '✨', '🔥', '💯', '🎉',
    '⚠️', '🚫', '❌', '⛔', '❗', '❓', '💢', '💬', '💭',
    '⏰', '⏱️', '📅', '📆', '🗓️',
    '🚀', '🎯', '🔍', '🔔', '💡'
  ];

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const addReaction = (messageId: string, emoji: string) => {
    setMessages(prev => prev.map(msg => {
      if (msg.id === messageId) {
        const reactions = msg.reactions || [];
        const existingReaction = reactions.find(r => r.emoji === emoji);

        if (existingReaction) {
          if (existingReaction.users.includes('You')) {
            existingReaction.users = existingReaction.users.filter(u => u !== 'You');
            if (existingReaction.users.length === 0) {
              return { ...msg, reactions: reactions.filter(r => r.emoji !== emoji) };
            }
          } else {
            existingReaction.users.push('You');
          }
        } else {
          reactions.push({ emoji, users: ['You'] });
        }

        return { ...msg, reactions };
      }
      return msg;
    }));
  };

  return (
    <div className="h-full flex flex-col bg-gray-50">
      {/* Header with Search */}
      <div className="bg-white border-b border-gray-200 px-6 py-4 flex-shrink-0">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
              <MessageSquare className="w-5 h-5 text-white" />
            </div>
            <div>
              <h2 className="text-lg font-bold text-gray-900">Work Notes</h2>
              <p className="text-sm text-gray-600">{filteredMessages.length} message{filteredMessages.length !== 1 ? 's' : ''}</p>
            </div>
          </div>
        </div>

        {/* Search Bar */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <Input
            placeholder="Search messages..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 bg-gray-50 border-gray-200 h-10"
          />
        </div>
      </div>

      {/* Messages Area - Scrollable */}
      <div className="flex-1 overflow-y-auto overflow-x-hidden px-4 py-4">
        <div className="space-y-6 max-w-full">
          {filteredMessages.map((msg) => {
            const isCurrentUser = (msg as any).isCurrentUser || msg.user.name === 'You';

            return (
              <div key={msg.id} className={`flex gap-3 ${msg.isSystem ? 'justify-center' : isCurrentUser ? 'justify-end' : ''}`}>
                {!msg.isSystem && !isCurrentUser && (
                  <Avatar className="h-10 w-10 flex-shrink-0 ring-2 ring-white shadow-sm">
                    <AvatarFallback className={`text-white font-semibold text-sm ${msg.user.role === 'Initiator' ? 'bg-green-600' :
                        msg.user.role === 'Approver' ? 'bg-blue-600' :
                          'bg-slate-600'
                      }`}>
                      {msg.user.avatar}
                    </AvatarFallback>
                  </Avatar>
                )}

                <div className={`${isCurrentUser ? 'max-w-[70%]' : 'flex-1'} min-w-0 ${msg.isSystem ? 'text-center max-w-md mx-auto' : ''}`}>
                  {msg.isSystem ? (
                    <div className="inline-flex items-center gap-3 px-4 py-2 bg-gray-100 rounded-full">
                      <Activity className="w-4 h-4 text-gray-500 flex-shrink-0" />
                      <span className="text-sm text-gray-700">{msg.content}</span>
                      <span className="text-xs text-gray-500">{formatDateTime(msg.timestamp)}</span>
                    </div>
                  ) : (
                    <div>
                      {/* Message Header */}
                      <div className={`flex items-center gap-3 mb-2 flex-wrap ${isCurrentUser ? 'justify-end' : ''}`}>
                        <span className="font-semibold text-gray-900 text-base">
                          {msg.user.name} {isCurrentUser && <span className="text-xs text-gray-500 font-normal">(you)</span>}
                        </span>
                        <Badge variant="outline" className="text-xs flex-shrink-0">
                          {msg.user.role}
                        </Badge>
                        <span className="text-xs text-gray-500 flex items-center gap-1 flex-shrink-0">
                          <Clock className="w-3 h-3" />
                          {formatDateTime(msg.timestamp)}
                        </span>
                        {msg.isHighPriority && (
                          <Badge variant="destructive" className="text-xs flex-shrink-0">
                            <Flag className="w-3 h-3 mr-1" />
                            Priority
                          </Badge>
                        )}
                      </div>

                      {/* Message Content */}
                      <div className={`rounded-lg border p-4 shadow-sm ${isCurrentUser ? 'bg-blue-50 border-blue-200' : 'bg-white border-gray-200'}`}>
                        <div
                          className="text-gray-800 leading-relaxed text-base"
                          dangerouslySetInnerHTML={{ __html: formatMessage(msg.content) }}
                        />

                        {/* Attachments */}
                        {msg.attachments && msg.attachments.length > 0 && (
                          <div className="mt-3 pt-3 border-t border-gray-100">
                            <div className="space-y-2">
                              {msg.attachments.map((attachment: any, index) => {
                                const fileSize = attachment.fileSize || attachment.file_size;
                                const fileName = attachment.fileName || attachment.file_name || attachment.name;
                                const fileType = attachment.fileType || attachment.file_type || attachment.type || '';
                                const attachmentId = attachment.attachmentId || attachment.attachment_id;

                                return (
                                  <div key={index} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200 hover:bg-gray-100 transition-colors">
                                    <div className="flex-shrink-0">
                                      <FileIcon type={fileType} />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                      <p className="text-sm font-medium text-gray-700 truncate">
                                        {fileName}
                                      </p>
                                      {fileSize && (
                                        <p className="text-xs text-gray-500">
                                          {formatFileSize(fileSize)}
                                        </p>
                                      )}
                                    </div>

                                    {/* Preview button for images and PDFs */}
                                    {attachmentId && (fileType.includes('image') || fileType.includes('pdf')) && (
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        className="h-8 w-8 p-0 flex-shrink-0 hover:bg-purple-100 hover:text-purple-600"
                                        onClick={(e) => {
                                          e.preventDefault();
                                          e.stopPropagation();
                                          const previewUrl = getWorkNoteAttachmentPreviewUrl(attachmentId);
                                          setPreviewFile({
                                            fileName,
                                            fileType,
                                            fileUrl: previewUrl,
                                            fileSize,
                                            attachmentId
                                          });
                                        }}
                                        title="Preview file"
                                      >
                                        <Eye className="w-4 h-4" />
                                      </Button>
                                    )}

                                    {/* Download button */}
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      className="h-8 w-8 p-0 flex-shrink-0 hover:bg-blue-100 hover:text-blue-600"
                                      onClick={async (e) => {
                                        e.preventDefault();
                                        e.stopPropagation();

                                        if (!attachmentId) {
                                          toast.error('Cannot download: Attachment ID missing');
                                          return;
                                        }

                                        try {
                                          await downloadWorkNoteAttachment(attachmentId);
                                        } catch (error) {
                                          toast.error('Failed to download file');
                                        }
                                      }}
                                      title="Download file"
                                    >
                                      <Download className="w-4 h-4" />
                                    </Button>
                                  </div>
                                );
                              })}
                            </div>
                          </div>
                        )}

                        {/* Reactions */}
                        {msg.reactions && msg.reactions.length > 0 && (
                          <div className="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100 flex-wrap">
                            {msg.reactions.map((reaction, index) => (
                              <button
                                key={index}
                                onClick={() => addReaction(msg.id, reaction.emoji)}
                                className={`flex items-center gap-1 px-2 py-1 rounded-full text-sm transition-colors flex-shrink-0 ${reaction.users.includes('You')
                                    ? 'bg-blue-100 text-blue-800 border border-blue-200'
                                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                                  }`}
                              >
                                <span>{reaction.emoji}</span>
                                <span className="text-xs font-medium">{reaction.users.length}</span>
                              </button>
                            ))}
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 w-7 p-0 flex-shrink-0"
                              onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                            >
                              <Plus className="w-3 h-3" />
                            </Button>
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                {!msg.isSystem && isCurrentUser && (
                  <Avatar className="h-10 w-10 flex-shrink-0 ring-2 ring-white shadow-sm">
                    <AvatarFallback className="bg-blue-500 text-white font-semibold text-sm">
                      {msg.user.avatar}
                    </AvatarFallback>
                  </Avatar>
                )}
              </div>
            );
          })}
          <div ref={messagesEndRef} />
        </div>
      </div>

      {/* Message Input - Fixed at bottom */}
      <div className="bg-white border-t border-gray-200 p-4 flex-shrink-0">
        <div className="max-w-full">
          {/* Hidden File Input */}
          <input
            type="file"
            ref={fileInputRef}
            onChange={handleFileSelect}
            className="hidden"
            multiple
            accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt"
          />

          {/* Selected Files Preview */}
          {selectedFiles.length > 0 && (
            <div className="mb-3 space-y-2 max-h-32 overflow-y-auto">
              {selectedFiles.map((file, index) => (
                <div key={index} className="flex items-center gap-2 p-2 bg-blue-50 rounded-lg border border-blue-200">
                  <div className="flex-shrink-0">
                    <FileIcon type={file.type.split('/')[1] || 'file'} />
                  </div>
                  <span className="text-sm text-gray-700 flex-1 truncate">{file.name}</span>
                  <span className="text-xs text-gray-500 flex-shrink-0">{(file.size / 1024).toFixed(1)} KB</span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleRemoveFile(index)}
                    className="h-6 w-6 p-0 hover:bg-red-100 flex-shrink-0"
                  >
                    <X className="h-3 w-3 text-red-600" />
                  </Button>
                </div>
              ))}
            </div>
          )}

          {/* Textarea with Emoji Picker */}
          <div className="relative mb-2">
            <Textarea
              placeholder="Type your message... Use @username to mention someone"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              className="min-h-[60px] resize-none border-gray-200 focus:ring-blue-500 focus:border-blue-500 w-full"
              rows={2}
            />

            {/* Emoji Picker Popup */}
            {showEmojiPicker && (
              <div className="absolute bottom-full left-0 mb-2 bg-white border border-gray-200 rounded-lg shadow-xl p-3 z-50 w-96 max-h-80 overflow-y-auto">
                <div className="flex items-center justify-between mb-3 sticky top-0 bg-white pb-2 border-b">
                  <span className="text-sm font-semibold text-gray-700">Pick an emoji</span>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setShowEmojiPicker(false)}
                    className="h-6 w-6 p-0"
                  >
                    <X className="h-3 w-3" />
                  </Button>
                </div>
                <div className="grid grid-cols-10 gap-1">
                  {emojiList.map((emoji, index) => (
                    <button
                      key={index}
                      onClick={() => handleEmojiSelect(emoji)}
                      className="text-2xl hover:bg-gray-100 rounded p-1 transition-colors"
                      title={emoji}
                    >
                      {emoji}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Action Buttons Row */}
          <div className="flex items-center justify-between gap-2">
            {/* Left side - Action buttons */}
            <div className="flex items-center gap-2 flex-shrink-0">
              <Button
                variant="ghost"
                size="sm"
                className="text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600"
                onClick={handleAttachmentClick}
                title="Attach file"
              >
                <Paperclip className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600"
                onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                title="Add emoji"
              >
                <Smile className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className="text-gray-500 h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600"
                onClick={() => setMessage(prev => prev + '@')}
                title="Mention someone"
              >
                <AtSign className="h-4 w-4" />
              </Button>
            </div>

            {/* Right side - Character count and Send button */}
            <div className="flex items-center gap-2 ml-auto flex-shrink-0">
              <span className="text-xs text-gray-500 whitespace-nowrap">
                {message.length}/2000
              </span>
              <Button
                onClick={handleSendMessage}
                disabled={!message.trim() && selectedFiles.length === 0}
                className="bg-blue-600 hover:bg-blue-700 h-9 px-4 disabled:opacity-50 disabled:cursor-not-allowed"
                size="sm"
              >
                <Send className="h-4 w-4 mr-2" />
                <span>Send</span>
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* File Preview Modal */}
      {previewFile && (
        <FilePreview
          fileName={previewFile.fileName}
          fileType={previewFile.fileType}
          fileUrl={previewFile.fileUrl}
          fileSize={previewFile.fileSize}
          attachmentId={previewFile.attachmentId}
          onDownload={downloadWorkNoteAttachment}
          open={!!previewFile}
          onClose={() => setPreviewFile(null)}
        />
      )}
    </div>
  );
}

