# Table Chat Feature Documentation

## Overview

The Table Chat feature is a comprehensive real-time messaging system integrated with the Table component. It provides a complete chat experience with channels, direct messaging, rich text editing, file sharing, and advanced message management capabilities.

## Architecture

### Component Hierarchy

```
Table (with isChatEnabled=true)
└── TableChatSidePanel (Main chat container)
    ├── TableChatChannelHeader (Left panel header)
    ├── Channel/Chat Lists (Left panel content)
    └── TableChatRightSection (Right panel)
        ├── ChatHeader (Header with actions)
        ├── Message List (Infinite scroll)
        └── ChatInput (Rich text editor)
```

## Core Components

### 1. TableChatSidePanel

**Purpose**: Main container component that orchestrates the entire chat interface.

**Key Responsibilities**:

- Manages chat state and navigation between channels/chats
- Handles real-time message updates
- Coordinates left and right panel interactions
- Manages loading states and error handling

**Props**:

```javascript
{
  isOpen: boolean,           // Controls panel visibility
  handleClose: function,     // Panel close handler
  chatConfiguration: object // Complete chat configuration
}
```

**Key Methods**:

#### `handleChatClick(chatId, selectedChatData)`

- **Purpose**: Handles chat selection and opens the message view
- **Parameters**:
  - `chatId`: Unique identifier for the chat
  - `selectedChatData`: Complete chat object with metadata
- **Flow**: Sets loading state → calls external handler → loads messages

#### `fetchChatList(currentActiveChannelInfo)`

- **Purpose**: Loads chat list for a selected channel
- **Parameters**:
  - `currentActiveChannelInfo`: Channel object with id and metadata
- **Returns**: Promise resolving to array of chat objects

#### `fetchChannelList()`

- **Purpose**: Loads available channels for the user
- **Returns**: Promise resolving to array of channel objects

#### `handleDeleteChat()`

- **Purpose**: Handles batch deletion of selected chats
- **Flow**: Validates selection → calls delete API → updates UI → handles cleanup

#### `clearnupLocalStates()`

- **Purpose**: Resets all local state when panel closes
- **Called**: When panel closes or navigation changes

### 2. TableChatRightSection

**Purpose**: Manages message display, real-time updates, and user interactions.

**Key Responsibilities**:

- Infinite scroll message loading
- Real-time message synchronization
- Message actions (pin, reply, edit, delete)
- Search functionality
- Message state management

**Props**:

```javascript
{
  chatId: string,           // Current chat identifier
  title: string,            // Chat title
  messageConfig: object,    // Message configuration
  inputChatConfig: object,  // Input configuration
  chatHeaderConfig: object  // Header configuration
}
```

**Key Methods**:

#### `fetchMoreMessages(page)`

- **Purpose**: Implements infinite scroll pagination
- **Parameters**:
  - `page`: Page number to load
- **Returns**: Promise resolving to array of messages
- **Features**: Handles both old format (array) and new format (object with metadata)

#### `handleSend(payload)`

- **Purpose**: Sends new messages or updates existing ones
- **Parameters**:
  - `payload`: Message content and metadata
- **Flow**: Validates content → calls send handler → updates UI → handles real-time sync

#### `handleUpdateMessage(updatedContent)`

- **Purpose**: Updates existing messages
- **Parameters**:
  - `updatedContent`: New message content
- **Flow**: Calls update API → handles real-time vs API message sync

#### `handleMessageDelete(messageId)`

- **Purpose**: Deletes messages with proper state management
- **Parameters**:
  - `messageId`: ID of message to delete
- **Flow**: Determines message type → calls delete handler → updates local state

#### `handleSearchMessage(searchValue, chatId)`

- **Purpose**: Searches messages within the chat
- **Parameters**:
  - `searchValue`: Search query
  - `chatId`: Chat to search in
- **Returns**: Promise resolving to search results

#### `groupMessagesByDate(messages)`

- **Purpose**: Groups messages by date for display
- **Parameters**:
  - `messages`: Array of message objects
- **Returns**: Array with date separators inserted

### 3. ChatInput

**Purpose**: Rich text editor with advanced formatting and interaction capabilities.

**Key Responsibilities**:

- Rich text editing with mentions
- File and image upload
- Emoji picker integration
- Message formatting and validation
- Priority and quick actions

**Props**:

```javascript
{
  placeholder: string,      // Input placeholder text
  value: string,           // Current input value
  onChange: function,      // Value change handler
  onSend: function,        // Message send handler
  messageConfig: object,   // Configuration for mentions, etc.
  isEditMode: boolean,     // Whether in edit mode
  chatId: string          // Current chat ID
}
```

**Key Methods**:

#### `handleSend()`

- **Purpose**: Processes and sends messages
- **Flow**: Validates content → extracts mentions → calls send handler → clears input

#### `getMentionedUsers()`

- **Purpose**: Extracts mentioned users from rich text content
- **Returns**: Array of mentioned user objects with IDs and positions

#### `handleInputChange(htmlContent)`

- **Purpose**: Handles rich text content changes
- **Parameters**:
  - `htmlContent`: HTML content from editor
- **Flow**: Updates state → calls onChange callback

#### `handleEmojiClick(emoji)`

- **Purpose**: Inserts emoji into the editor
- **Parameters**:
  - `emoji`: Emoji object or string

#### `handleFileUpload(file)`

- **Purpose**: Handles file upload with progress tracking
- **Parameters**:
  - `file`: File object to upload

### 4. ChatHeader

**Purpose**: Header component with participant management and search functionality.

**Key Responsibilities**:

- Participant management (add/remove)
- Message search interface
- Notification settings
- Pinned message access

**Props**:

```javascript
{
  title: string,            // Chat title
  chatId: string,          // Chat identifier
  chatHeaderConfig: object, // Header configuration
  participants: array      // Current participants
}
```

**Key Methods**:

#### `fetchOptionsForRadio(radioValue)`

- **Purpose**: Loads participant options based on selection type
- **Parameters**:
  - `radioValue`: "existing" or "new" participants
- **Returns**: Promise resolving to participant array

#### `handleRadioButtonChange(value)`

- **Purpose**: Handles participant type selection
- **Parameters**:
  - `value`: Selected radio button value
- **Flow**: Updates state → fetches new options

#### `handleMessageSearchChange(e)`

- **Purpose**: Handles message search with debouncing
- **Parameters**:
  - `e`: Input event
- **Flow**: Updates search value → calls debounced search

#### `handleParticipantsClick()`

- **Purpose**: Opens participant management interface
- **Flow**: Calls external handler → loads participant data

## Configuration Structure

### chatConfiguration Object

The main configuration object that controls all chat functionality:

```javascript
{
  // Message-related configuration
  messageChatConfig: {
    // Real-time messaging
    realTimeMessages: [],
    isWebSocketConnected: boolean,
    currentTopicId: string,
    currentUserId: number,
    onRealTimeMessageUpdate: function,

    // Message actions
    onMessageReply: function,
    onMessageBookmark: function,
    onMessagePin: function,
    onMessageUpdate: function,
    onMessageDelete: function,
    onThreadClick: function,

    // Data loading
    loadThreadMessages: function,
    loadPinnedMsg: function,
    onSearchMessage: function,

    // Configuration
    messageConfig: {
      showActions: boolean,
      priorityOptions: array,
      quickActionProps: array
    }
  },

  // Header configuration
  headerChatConfig: {
    // Participant management
    participants: array,
    loadParticipants: function,
    loadParticipantsAvatar: function,
    onParticipantAdd: function,
    onParticipantRemove: function,

    // Search and actions
    onSearchChange: function,
    onPinnedClick: function,
    onNotificationSettingChange: function,

    // Header settings
    headerConfig: {
      showSearch: boolean,
      showParticipants: boolean,
      showPinned: boolean,
      radioOptions: array
    }
  },

  // Input configuration
  inputChatConfig: {
    onSend: function,
    onAttachFile: function,
    onImageUpload: function,
    inputConfig: {
      placeholder: string,
      maxLength: number,
      showFormatting: boolean
    }
  },

  // Left panel configuration
  leftPanel: {
    loadChannelsList: function,
    loadChatList: function,
    handleChatName: function,
    deleteChat: function,
    directChatList: array,
    hasDirectChatList: boolean
  },

  // Right panel configuration
  rightPanel: {
    loadMessages: function,
    loadOlderMessages: function,
    messagesClearedTrigger: number
  }
}
```

## Message Flow

### 1. Real-time Message Updates

```
WebSocket Event → onRealTimeMessageUpdate →
TableChatSidePanel → memoizedMessageConfig →
TableChatRightSection → Message State Update → UI Render
```

### 2. Message Sending

```
ChatInput → handleSend → inputChatConfig.onSend →
API Call → Real-time Update → Message List Update
```

### 3. Message Actions

```
ChatMessage Action → TableChatRightSection Handler →
messageConfig Handler → API Call → State Update
```

## Data Structures

### Message Object

```javascript
{
  id: string,              // Unique message identifier
  author: string,          // "user" | "assistant" | "system"
  authorName: string,      // Display name
  content: string,         // HTML content
  timestamp: string,       // Display timestamp
  date: string,           // ISO date string
  priority: string,       // "low" | "medium" | "high"
  isPinned: boolean,      // Pin status
  deleted: boolean,       // Deletion status
  edited: boolean,        // Edit status
  showActions: boolean,   // Show action buttons
  otherProps: {
    sender_id: number,    // Sender's user ID
    created_at: string,   // Creation timestamp
    isRealTime: boolean   // Real-time message flag
  }
}
```

### Chat Object

```javascript
{
  id: string,             // Unique chat identifier
  title: string,          // Chat display name
  subtitle: string,       // Chat description/preview
  user: string,           // Last message author
  text: string,           // Last message preview
  time: string,           // Last activity time
  isChecked: boolean,     // Selection status
  isPinned: boolean,      // Pin status
  unreadCount: number,    // Unread message count
  otherProps: {
    object_ids: array,    // Related object IDs
    object_type: string   // Object type ("deal", etc.)
  }
}
```

### Channel Object

```javascript
{
  id: string,             // Unique channel identifier
  title: string,          // Channel name
  time: string,           // Last activity
  unreadCount: number     // Unread messages
}
```

## Advanced Features

### 1. Infinite Scroll Implementation

The chat uses a custom `useInfiniteScroll` hook that:

- Triggers loading when scrolling near the top (for older messages)
- Handles loading states and error conditions
- Supports both array and object response formats
- Prevents duplicate message loading

### 2. Real-time Synchronization

Real-time updates are handled through:

- WebSocket connection status monitoring
- Message deduplication by ID
- Optimistic updates with rollback support
- Proper chronological ordering

### 3. Rich Text Editor Features

The MentionEditor component provides:

- @mention autocomplete with user search
- Text formatting (bold, italic, links, etc.)
- Emoji picker integration
- File and image upload with preview
- HTML content validation

### 4. Search Functionality

Two types of search are supported:

1. **Message Search**: Search within chat messages
2. **Participant Search**: Search and filter participants

Both support debouncing and async loading states.

### 5. State Management

The chat feature uses a combination of:

- Local React state for UI interactions
- Memoized configurations to prevent re-renders
- External state management through configuration callbacks
- Cleanup functions for proper resource management

## Usage Examples

### Basic Integration

```javascript
<Table
  isChatEnabled={true}
  isChatOpen={isChatOpen}
  handleChatClick={handleChatClick}
  handleChatClose={handleChatClose}
  chatConfiguration={chatConfiguration}
  // ... other table props
/>
```

### Custom Message Handler

```javascript
const chatConfiguration = {
  messageChatConfig: {
    onMessageUpdate: async (messageId, updatedData) => {
      // Custom update logic
      const response = await api.updateMessage(messageId, updatedData);
      return response.data;
    },
  },
};
```

### Real-time Integration

```javascript
const chatConfiguration = {
  messageChatConfig: {
    realTimeMessages: webSocketMessages,
    isWebSocketConnected: wsConnection.readyState === WebSocket.OPEN,
    onRealTimeMessageUpdate: (newMessage) => {
      setWebSocketMessages((prev) => [...prev, newMessage]);
    },
  },
};
```

## Best Practices

1. **Performance**:

   - Use memoized configurations to prevent unnecessary re-renders
   - Implement proper cleanup in useEffect hooks
   - Debounce search and input handlers

2. **Error Handling**:

   - Always wrap async operations in try-catch blocks
   - Provide user feedback for failed operations
   - Implement retry mechanisms for critical operations

3. **State Management**:

   - Keep local state minimal and focused
   - Use external handlers for persistent data
   - Implement proper cleanup when components unmount

4. **Accessibility**:

   - Provide proper ARIA labels for interactive elements
   - Ensure keyboard navigation support
   - Use semantic HTML structures

5. **Real-time Updates**:
   - Handle message deduplication properly
   - Implement proper chronological ordering
   - Provide visual feedback for connection status

## Troubleshooting

### Common Issues

1. **Messages not updating in real-time**:

   - Check WebSocket connection status
   - Verify `currentTopicId` matches active chat
   - Ensure `onRealTimeMessageUpdate` is properly configured

2. **Infinite scroll not working**:

   - Check `loadMessages` function implementation
   - Verify page parameter handling
   - Ensure proper return format (array or object with messages)

3. **Mentions not working**:

   - Verify `loadParticipantsAvatar` function
   - Check `chatId` parameter passing
   - Ensure participant data format is correct

4. **File upload issues**:
   - Check file type restrictions
   - Verify upload handler implementation
   - Ensure proper error handling

### Debug Tools

Enable debug logging by setting:

```javascript
window.CHAT_DEBUG = true;
```

This will provide detailed console logs for:

- Message state changes
- API calls and responses
- Real-time update processing
- Component lifecycle events
