import React from "react";
import { Table } from "../components/Table";
import { Button } from "../components/Button";
import { useState, useCallback } from "react";
import { fn } from "@storybook/test";

// Mock data for demonstration
const mockRowData = [
  {
    id: 1,
    make: "Tesla",
    model: "Model Y",
    price: 64950,
    electric: true,
    year: 2023,
    status: "Active",
  },
  {
    id: 2,
    make: "Ford",
    model: "F-Series",
    price: 33850,
    electric: false,
    year: 2023,
    status: "Active",
  },
  {
    id: 3,
    make: "Toyota",
    model: "Corolla",
    price: 29600,
    electric: false,
    year: 2023,
    status: "Inactive",
  },
];

const mockColumnDefs = [
  { field: "make", headerName: "Make", filter: "agTextColumnFilter" },
  { field: "model", headerName: "Model", filter: "agTextColumnFilter" },
  { field: "price", headerName: "Price", filter: "agNumberColumnFilter" },
  { field: "year", headerName: "Year", filter: "agNumberColumnFilter" },
  { field: "status", headerName: "Status", filter: "agTextColumnFilter" },
];

// Debounce utility function
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

export default {
  title: "Components/TableChat",
  component: Table,
  parameters: {
    docs: {
      description: {
        component: `
# Table Chat Feature

The Table Chat feature provides a comprehensive real-time messaging system integrated with the Table component. It includes:

- **Channel Management**: Organize conversations by channels
- **Real-time Messaging**: Live message updates with WebSocket support
- **Rich Text Editor**: Full-featured text editor with mentions, formatting, and emoji support
- **File & Image Sharing**: Upload and share files and images
- **Message Actions**: Pin, reply, bookmark, edit, and delete messages
- **Participant Management**: Add/remove participants and manage permissions
- **Search**: Search messages and participants
- **Notifications**: Configurable notification settings
- **Thread Support**: Threaded conversations for better organization

## Architecture

The chat feature consists of several key components:

### 1. TableChatSidePanel
The main container component that manages the chat interface state and handles the communication between left and right panels.

### 2. TableChatRightSection  
Handles the message display, infinite scroll, real-time updates, and message interactions.

### 3. ChatInput
Rich text editor with mention support, formatting tools, file upload, and emoji picker.

### 4. ChatHeader
Header with participant management, search functionality, and notification settings.

## Configuration Structure

The chat feature is configured through a comprehensive \`chatConfiguration\` object with the following main sections:

- \`messageChatConfig\`: Message-related handlers and real-time configuration
- \`headerChatConfig\`: Header actions, participant management, and search
- \`inputChatConfig\`: Input handling, formatting, and file upload
- \`leftPanel\`: Channel and chat list management
- \`rightPanel\`: Message loading and pagination

## Key Features

### Real-time Messaging
- WebSocket integration for live updates
- Message state synchronization
- Optimistic updates with rollback support

### Rich Text Editor
- @mentions with autocomplete
- Text formatting (bold, italic, links, etc.)
- Emoji picker integration
- File and image upload

### Message Management
- Pin/unpin messages
- Reply to messages
- Edit and delete messages
- Message search functionality

### Participant Management
- Add/remove participants
- Role-based permissions
- Participant search and filtering

### Notification System
- Configurable notification settings
- Channel-specific notifications
- Mention notifications

### Testing pin/unpin (chat list)
1. Open a story that shows the chat side panel (e.g. "Basic Chat Feature" or "Direct Messaging").
2. Select a channel (e.g. General) so the chat list loads.
3. Use the pin icon on a chat row to pin or unpin; the list re-sorts so pinned chats stay at the top.
        `,
      },
    },
  },
  argTypes: {
    isChatEnabled: {
      description: "Enables the chat feature in the table component",
      control: { type: "boolean" },
      table: {
        defaultValue: { summary: "false" },
        type: { summary: "boolean" },
      },
    },
    handleChatClick: {
      description: "Handler function called when chat button is clicked",
      table: {
        type: { summary: "() => void" },
      },
    },
    isChatOpen: {
      description: "Controls whether the chat panel is open",
      control: { type: "boolean" },
      table: {
        defaultValue: { summary: "false" },
        type: { summary: "boolean" },
      },
    },
    handleChatClose: {
      description: "Handler function called when chat panel is closed",
      table: {
        type: { summary: "() => void" },
      },
    },
    chatConfiguration: {
      description: `
## Chat Configuration Object

The \`chatConfiguration\` prop is a comprehensive object that configures all aspects of the chat feature:

### messageChatConfig
Handles message-related functionality and real-time updates:

- \`realTimeMessages\`: Array of real-time messages
- \`isWebSocketConnected\`: WebSocket connection status
- \`currentTopicId\`: Current active topic/chat ID
- \`currentUserId\`: Current user's ID for message ownership
- \`onRealTimeMessageUpdate\`: Callback for real-time message updates
- \`loadMessages\`: Function to load messages with pagination
- \`onMessageReply\`: Handler for message replies
- \`onMessageBookmark\`: Handler for bookmarking messages
- \`onMessagePin\`: Handler for pinning/unpinning messages
- \`onMessageUpdate\`: Handler for editing messages
- \`onMessageDelete\`: Handler for deleting messages
- \`onThreadClick\`: Handler for opening message threads
- \`loadThreadMessages\`: Function to load thread messages
- \`loadPinnedMsg\`: Function to load pinned messages
- \`onSearchMessage\`: Function to search messages
- \`messageConfig\`: Message display configuration (priority, formatting, etc.)

### headerChatConfig
Manages header functionality and participant interactions:

- \`participants\`: Array of current participants
- \`loadParticipants\`: Function to load participant list
- \`loadParticipantsAvatar\`: Function to load participant avatars
- \`onParticipantsClick\`: Handler for participant menu
- \`onParticipantAdd\`: Handler for adding participants
- \`onParticipantRemove\`: Handler for removing participants
- \`onPinnedClick\`: Handler for viewing pinned messages
- \`onSearchChange\`: Handler for participant search
- \`onNotificationSettingChange\`: Handler for notification settings
- \`headerConfig\`: Header display configuration

### inputChatConfig
Controls message input and sending:

- \`onSend\`: Handler for sending messages
- \`onMessageReply\`: Handler for replying to messages
- \`onMessageBookmark\`: Handler for bookmarking from input
- \`onAttachFile\`: Handler for file attachments
- \`onImageUpload\`: Handler for image uploads
- \`onEmojiSelect\`: Handler for emoji selection
- \`inputConfig\`: Input field configuration

### leftPanel
Manages channels and chat lists:

- \`loadChannelsList\`: Function to load available channels
- \`loadChatList\`: Function to load chats for a channel
- \`handleChatName\`: Handler for creating new chats
- \`deleteChat\`: Handler for deleting chats
- \`directChatList\`: Direct chat list for bypassing channels
- \`leftHeaderPanel\`: Left header configuration
- \`leftChatPanel\`: Left chat panel configuration
- \`rightHeaderPanel\`: Right header configuration

### rightPanel
Handles message display and loading:

- \`loadMessages\`: Function to load messages with pagination
- \`loadOlderMessages\`: Function to load historical messages
- \`messagesClearedTrigger\`: Trigger for clearing messages
      `,
      control: { type: "object" },
      table: {
        type: { summary: "ChatConfiguration" },
      },
    },
  },
  args: {
    handleChatClick: fn(),
    handleChatClose: fn(),
  },
};

// Base chat configuration for reuse across stories
const createBaseChatConfiguration = () => ({
  tooltipConfig: {
    title: "New chat feature",
    description:
      '"Chat" allows you to collaborate with your companions on the go.',
  },
  // Message related configuration and handlers
  messageChatConfig: {
    // Real-time message props
    realTimeMessages: [],
    isWebSocketConnected: false,
    currentTopicId: null,
    isThreadIconVisible: true,
    isPinChatIconVisible: true,
    emptyChannelStateTitle: "No channels selected",
    emptyChannelStateSubTitle: "Select a channel to view chats",
    emptyChatStateTitle: "No chat selected",
    emptyChatStateSubTitle: "Select a chat to start messaging",
    currentUserId: 89,

    // Message action handlers
    onRealTimeMessageUpdate: (newMessage) => {
      console.log("Real-time message update:", newMessage);
    },

    onMessageReply: (messageId, message) => {
      console.log("Reply to message:", messageId, message);
    },

    onMessageBookmark: (messageId, message) => {
      console.log("Bookmark message:", messageId, message);
    },

    onMessagePin: async (
      messageId,
      pinned,
      item,
      selectedChannelInfo,
      selectedChatInfo
    ) => {
      console.log("Pin message:", messageId, pinned, item);
      return new Promise((resolve) => {
        setTimeout(() => resolve(pinned), 1000);
      });
    },

    onMessageUpdate: async (messageId, updatedData) => {
      console.log("Update message:", messageId, updatedData);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true, messageId, updatedData });
        }, 1000);
      });
    },

    onMessageDelete: async (messageId) => {
      console.log("Delete message:", messageId);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true, messageId });
        }, 1000);
      });
    },

    onThreadClick: (messageId, message) => {
      console.log("Open thread for message:", messageId, message);
    },

    loadThreadMessages: async (parentMessageId) => {
      const threadMessages = [
        {
          user: "You",
          userInitials: "YO",
          timestamp: "Today",
          quote: "Original message content here...",
          text: "Reply in thread goes here",
          time: "06:00 AM",
        },
        {
          user: "Assistant",
          userInitials: "AS",
          timestamp: "Today",
          quote: "Sure, I checked that already",
          text: "Yes looks good 👍",
          time: "06:05 AM",
        },
      ];

      return new Promise((resolve) => {
        setTimeout(() => resolve(threadMessages), 1000);
      });
    },

    loadPinnedMsg: async () => {
      const pinnedMessages = [
        {
          user: "Me",
          userInitials: "AM",
          timestamp: "Jul 21, 12:57 PM",
          text: "Important pinned message here...",
          deleted: true,
        },
        {
          user: "Me",
          userInitials: "AM",
          timestamp: "Jul 21, 12:58 PM",
          text: "Another pinned message for reference...",
          edited: true,
        },
      ];

      return new Promise((resolve) => {
        setTimeout(() => resolve(pinnedMessages), 1000);
      });
    },

    onSearchMessage: async (value, chatId) => {
      console.log("Searching messages:", value, chatId);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve([
            {
              id: "search-1",
              author: "user",
              authorName: "You",
              content: `Search result for: ${value}`,
              timestamp: "06:05 AM",
              date: new Date().toISOString(),
              showReplyBadge: true,
              replyText: "Reply",
              priority: "low",
            },
          ]);
        }, 1000);
      });
    },

    // Message configuration
    messageConfig: {
      showActions: true,
      priorityOptions: [
        { value: "normal", label: "Normal Priority" },
        { value: "high", label: "High Priority" },
        { value: "medium", label: "Medium Priority" },
        { value: "low", label: "Low Priority" },
      ],
      quickActionProps: [
        {
          value: "requestReview",
          label: "Request Review",
          prefillText: "Please review this request and provide feedback.",
        },
        {
          value: "finalOffer",
          label: "Final Offer",
          prefillText: "Sharing the final offer. Please confirm.",
        },
      ],
      isMsgFormat: false,
    },

    leaveCurrentTopic: () => {
      console.log("Leaving current topic");
    },

    markTopicAsDeleted: (topicId) => {
      console.log("Marking topic as deleted:", topicId);
    },
  },

  // Header related configuration
  headerChatConfig: {
    participants: [
      { id: 1, name: "John Doe", avatar: "JD", status: "online" },
      { id: 2, name: "Jane Smith", avatar: "JS", status: "offline" },
    ],

    loadParticipants: async (
      radioValue,
      selectedChannelInfo,
      selectedChatInfo
    ) => {
      console.log("Loading participants:", radioValue);

      return new Promise((resolve) => {
        setTimeout(() => {
          const participants =
            radioValue === "existing"
              ? [
                  {
                    id: 1,
                    label: "Existing User 1",
                    value: "user1",
                    role: "Admin",
                  },
                  {
                    id: 2,
                    label: "Existing User 2",
                    value: "user2",
                    role: "Member",
                  },
                ]
              : [
                  {
                    id: 85,
                    label: "John Doe",
                    value: 85,
                    otherProps: {
                      user_name: "John Doe",
                      user_code: 85,
                      email: "john.doe@example.com",
                    },
                  },
                  {
                    id: 84,
                    label: "Jane Smith",
                    value: 84,
                    otherProps: {
                      user_name: "Jane Smith",
                      user_code: 84,
                      email: "jane.smith@example.com",
                    },
                  },
                ];
          resolve(participants);
        }, 1000);
      });
    },

    loadParticipantsAvatar: async (selectedRadioOption, chatId) => {
      console.log("Loading participant avatars:", selectedRadioOption, chatId);

      const participantsList = [
        { id: 1, label: "John Doe", avatar: "JD", status: "online" },
        { id: 2, label: "Jane Smith", avatar: "JS", status: "offline" },
        { id: 3, label: "Bob Wilson", avatar: "BW", status: "online" },
      ];

      return new Promise((resolve) => {
        setTimeout(() => resolve(participantsList), 1000);
      });
    },

    onParticipantsClick: async (radioValue) => {
      console.log("Participants clicked:", radioValue);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve([
            { id: 1, label: "User 1", value: "user1", role: "Admin" },
            { id: 2, label: "User 2", value: "user2", role: "Member" },
          ]);
        }, 1000);
      });
    },

    onParticipantAdd: async (participant, selectedRadioOption, chatId) => {
      console.log("Adding participant:", participant);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true, participant });
        }, 1500);
      });
    },

    onParticipantRemove: async (participant) => {
      console.log("Removing participant:", participant);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true, participant });
        }, 800);
      });
    },

    onPinnedClick: async (chatId) => {
      console.log("Pinned messages clicked:", chatId);
      const pinnedMessages = [
        {
          user: "Me",
          userInitials: "AM",
          timestamp: "Jul 21, 12:57 PM",
          content: "This is a pinned message for reference...",
          edited: true,
          deleted: true,
        },
      ];

      return new Promise((resolve) => {
        setTimeout(() => resolve(pinnedMessages), 1000);
      });
    },

    onSearchChange: async (value, radioValue, chatId) => {
      console.log("Search participants:", value, radioValue, chatId);
      return new Promise((resolve) => {
        setTimeout(() => {
          const results = [
            {
              id: 85,
              label: "John Doe",
              value: 85,
              otherProps: {
                user_name: "John Doe",
                user_code: 85,
                email: "john.doe@example.com",
              },
            },
          ].filter((item) =>
            item.label.toLowerCase().includes(value.toLowerCase())
          );
          resolve(results);
        }, 500);
      });
    },

    onNotificationSettingChange: async (settings) => {
      console.log("Saving notification settings:", settings);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true, settings });
        }, 600);
      });
    },

    onPinnedChatClick: async (chatId, isPinned) => {
      console.log("Pin/unpin chat:", chatId, "→", isPinned ? "pinned" : "unpinned");
      return new Promise((resolve) => {
        setTimeout(() => resolve(isPinned), 300);
      });
    },

    notificationSettings: {
      notificationSetting: "all",
      includeChannelMentions: false,
      muteChannel: false,
      channelName: "general",
    },

    // Header configuration
    headerConfig: {
      showSearch: true,
      showParticipants: true,
      showPinned: true,
      showNotifications: true,
      selectedRadioOptionMenu: "existing",
      maxAvatars: 3,
      radioOptions: [
        { label: "New", value: "new" },
        { label: "Existing", value: "existing" },
      ],
      searchConfig: {
        placeholder: "Search in chat...",
        debounceMs: 300,
        minChars: 2,
      },
    },
  },

  // Input related configuration
  inputChatConfig: {
    onSend: async (payload, chatId) => {
      console.log("Send message:", payload, chatId);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true, message: payload.content });
        }, 1000);
      });
    },

    onMessageReply: (messageId, chatId) => {
      console.log("Reply message:", messageId, chatId);
    },

    onMessageBookmark: (messageId, chatId) => {
      console.log("Bookmark message:", messageId, chatId);
    },

    onMessageMore: (messageId, chatId) => {
      console.log("More message options:", messageId, chatId);
    },

    onAttachFile: (file) => {
      console.log("File attached:", file);
    },

    onImageUpload: (image) => {
      console.log("Image uploaded:", image);
    },

    onEmojiSelect: (emoji) => {
      console.log("Emoji selected:", emoji);
    },

    // Input configuration
    inputConfig: {
      placeholder: "Type your message...",
      maxLength: 5000,
      showFormatting: true,
      showEmojiPicker: true,
      showAttachments: true,
      allowedFileTypes: ["image/*", "application/pdf"],
    },
  },

  // Left panel configuration
  leftPanel: {
    leftHeaderPanel: {
      showAddChat: true,
    },

    leftChatPanel: {
      showCheckbox: true,
    },

    rightHeaderPanel: {
      showParticipants: true,
      showPinnedChat: true,
      showChatSearch: true,
      showActionBtn: true,
    },

    loadChannelsList: async () => {
      const data = [
        { id: 1, title: "General", time: "11:56", unreadCount: 3 },
        { id: 2, title: "Development", time: "11:56" },
        { id: 3, title: "Design", time: "11:56" },
        { id: 4, title: "Marketing", time: "11:56", unreadCount: 2 },
      ];

      return new Promise((resolve) => {
        setTimeout(() => resolve(data), 1000);
      });
    },

    loadChatList: async (selectedChannelInfo) => {
      // Backend-shaped chat list (matches API: id, user, text, title, subtitle, timestamp, otherProps)
      const chatData = {
        1: [
          {
            id: "49b7cdc7-bb14-4ba8-acd9-84661683ff3c",
            user: "Malay Sharma",
            text: "Coding",
            title: "ms checking v1",
            subtitle: "wefwefwqefeqwf",
            isChecked: false,
            isPinned: false,
            unreadCount: 0,
            messageCount: 9,
            timestamp: "9 hours ago",
            otherProps: {
              topic_id: "49b7cdc7-bb14-4ba8-acd9-84661683ff3c",
              name: "ms checking v5",
              description: "wefwefwqefeqwf",
              object_type: "landing_workbench_table",
              object_ids: ["45"],
              app_code: "basesmart",
              created_by: 110,
              created_at: "2026-03-05T05:20:05.467545",
              created_by_user: "Malay Sharma",
              message_count: 9,
              pinned_message_count: 1,
              unread_count: 0,
              is_pinned: false,
            },
          },
          {
            id: "c238312b-7a5d-4198-92b0-dd5f8485314c",
            user: "Qa user",
            text: null,
            title: "MS CHECKING V6",
            subtitle: null,
            isChecked: false,
            isPinned: false,
            unreadCount: 0,
            messageCount: 0,
            timestamp: "7 hours ago",
            otherProps: {
              topic_id: "c238312b-7a5d-4198-92b0-dd5f8485314c",
              name: "MS CHECKING V6",
              description: null,
              object_type: "landing_workbench_table",
              object_ids: ["45"],
              app_code: "basesmart",
              created_by: 251,
              created_at: "2026-03-05T06:43:23.936548",
              created_by_user: "Qa user",
              message_count: 0,
              pinned_message_count: 0,
              unread_count: 0,
              is_pinned: false,
            },
          },
        ],
        2: [
          {
            id: "c238312b-7a5d-4198-92b0-dd5f8485314c",
            user: "Qa user",
            text: null,
            title: "MS CHECKING V6",
            subtitle: null,
            isChecked: false,
            isPinned: false,
            unreadCount: 0,
            messageCount: 0,
            timestamp: "7 hours ago",
            otherProps: {
              topic_id: "c238312b-7a5d-4198-92b0-dd5f8485314c",
              created_by_user: "Qa user",
              created_at: "2026-03-05T06:43:23.936548",
            },
          },
        ],
      };

      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(chatData[selectedChannelInfo?.id] || []);
        }, 1000);
      });
    },

    handleChatName: async (formData, selectedChannel) => {
      console.log("Creating new chat:", formData, selectedChannel);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({
            success: true,
            chatName: formData?.chatName,
            description: formData?.chatDescription,
            selectedChannel,
          });
        }, 1000);
      });
    },

    deleteChat: async (topicId) => {
      console.log("Deleting chat:", topicId);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ success: true, topicId });
        }, 2000);
      });
    },

    // Direct chat configuration
    directChatList: [],
    hasDirectChatList: false,
    clearDirectChatList: () => {
      console.log("Clearing direct chat list");
    },
  },

  // Right panel configuration
  rightPanel: {
    loadMessages: async (chatId, page = 1) => {
      // Generate dummy messages for pagination
      const generateMessages = (page, limit = 10) => {
        const messages = [];
        const startId = (page - 1) * limit + 1;

        for (let i = 0; i < limit; i++) {
          const messageId = startId + i;
          const isUser = messageId % 2 === 0;
          const baseDate = new Date();
          baseDate.setDate(baseDate.getDate() - (page - 1) * 10 - i);

          messages.push({
            id: `msg-${messageId}`,
            author: isUser ? "user" : "assistant",
            authorName: isUser ? "You" : "Assistant",
            content: `<p><strong>Message ${messageId} on page ${page}</strong><br/>
                     Sample message content with <em>formatting</em> and 
                     <span class="mention" data-type="mention" data-id="1" data-label="John Doe">@John Doe</span>
                     </p>`,
            timestamp: baseDate.toLocaleTimeString([], {
              hour: "2-digit",
              minute: "2-digit",
            }),
            date: baseDate.toISOString(),
            showReplyBadge: messageId % 3 === 0,
            replyText: messageId % 3 === 0 ? "Reply" : null,
            priority:
              messageId % 5 === 0
                ? "high"
                : messageId % 3 === 0
                ? "medium"
                : "low",
            edited: messageId % 7 === 0,
            deleted: messageId % 11 === 0,
            isPinned: messageId % 13 === 0,
            showActions: true,
            otherProps: {
              sender_id: isUser ? 89 : 27,
              created_at: baseDate.toISOString(),
              sender_name: isUser ? "You" : "Assistant",
            },
          });
        }

        return messages;
      };

      // Simulate pagination - return empty after page 5
      if (page > 5) {
        return new Promise((resolve) => {
          setTimeout(() => resolve([]), 500);
        });
      }

      const messages = generateMessages(page, 10);

      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(messages);
        }, 800);
      });
    },

    loadOlderMessages: async (channelId) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve([
            {
              id: `old-${Date.now()}`,
              author: "assistant",
              content: "Older historical message",
              timestamp: new Date().toLocaleTimeString([], {
                hour: "2-digit",
                minute: "2-digit",
              }),
              date: new Date().toISOString(),
            },
          ]);
        }, 1000);
      });
    },
  },
});

// Component wrapper for stories
const TableChatComponent = (args) => {
  const [isChatOpen, setIsChatOpen] = useState(args.isChatOpen || false);

  const handleChatClick = useCallback(() => {
    console.log("Chat clicked");
    setIsChatOpen(!isChatOpen);
    args.handleChatClick?.();
  }, [isChatOpen, args]);

  const handleChatClose = useCallback(() => {
    console.log("Chat closed");
    setIsChatOpen(false);
    args.handleChatClose?.();
  }, [args]);

  return (
    <Table
      {...args}
      isChatOpen={isChatOpen}
      handleChatClick={handleChatClick}
      handleChatClose={handleChatClose}
    />
  );
};

/**
 * ## Basic Chat Feature
 *
 * This story demonstrates the basic chat functionality integrated with a table component.
 * The chat feature includes:
 *
 * - Channel and chat list management
 * - Real-time messaging capabilities
 * - Rich text editor with formatting
 * - Message actions (pin, reply, bookmark, etc.)
 * - File and image sharing
 * - Participant management
 */
export const BasicChatFeature = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    tableHeader: "Table with Chat Feature",
    cardContainer: true,
    rowData: mockRowData,
    columnDefs: mockColumnDefs,
    isChatEnabled: true,
    isChatOpen: false,
    chatConfiguration: createBaseChatConfiguration(),
    topRightOptions: (
      <>
        <Button>Export Data</Button>
        <Button variant="primary">Add New</Button>
      </>
    ),
  },
};

/**
 * ## Chat with Direct Messages
 *
 * This story shows the chat feature configured for direct messaging,
 * bypassing the channel selection and going straight to a chat list.
 */
export const DirectMessaging = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Direct Messaging Chat",
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      leftPanel: {
        ...createBaseChatConfiguration().leftPanel,
        hasDirectChatList: true,
        directChatList: [
          {
            id: 1,
            user: "John Doe",
            text: "Hey, can we discuss the project?",
            time: "10:30",
            title: "Project Discussion",
            subtitle: "Hey, can we discuss the project...",
            isChecked: false,
            isPinned: false,
            otherProps: {
              object_ids: [1],
              object_type: "deal",
            },
          },
          {
            id: 2,
            user: "Jane Smith",
            text: "The design looks great!",
            time: "09:15",
            title: "Design Review",
            subtitle: "The design looks great! I have some...",
            isChecked: false,
            isPinned: true,
            otherProps: {
              object_ids: [1],
              object_type: "deal",
            },
          },
        ],
      },
    },
  },
};

/**
 * ## Chat with Real-time Updates
 *
 * This story demonstrates the real-time messaging capabilities with
 * WebSocket connection simulation and live message updates.
 */
export const RealTimeChat = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Real-time Chat",
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      messageChatConfig: {
        ...createBaseChatConfiguration().messageChatConfig,
        isWebSocketConnected: true,
        currentTopicId: 1,
        realTimeMessages: [
          {
            id: "rt-1",
            author: "assistant",
            authorName: "Assistant",
            content: "<p>This is a real-time message update!</p>",
            timestamp: "10:45 AM",
            date: new Date().toISOString(),
            showActions: true,
            priority: "high",
          },
        ],
      },
    },
  },
};

/**
 * ## Chat with Rich Text Features
 *
 * This story showcases the rich text editor capabilities including:
 * - Text formatting (bold, italic, links)
 * - @mentions with autocomplete
 * - Emoji picker
 * - File and image upload
 * - Priority and quick actions
 */
export const RichTextChat = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Rich Text Chat",
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      inputChatConfig: {
        ...createBaseChatConfiguration().inputChatConfig,
        inputConfig: {
          placeholder:
            "Type your message with @mentions, formatting, and emojis...",
          maxLength: 5000,
          showFormatting: true,
          showEmojiPicker: true,
          showAttachments: true,
          showQuickAction: true,
          quickActionLabel: "Quick",
          allowedFileTypes: ["image/*", "application/pdf", ".doc", ".docx"],
          quickActions: [
            { label: "Request Review", action: "request_review" },
            { label: "Schedule Meeting", action: "schedule_meeting" },
            { label: "Share Update", action: "share_update" },
          ],
        },
      },
    },
  },
};

/**
 * ## Chat with Advanced Search
 *
 * This story demonstrates the search capabilities including:
 * - Message search across conversations
 * - Participant search and filtering
 * - Search results highlighting
 * - Advanced search filters
 */
export const SearchEnabledChat = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Search-Enabled Chat",
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      headerChatConfig: {
        ...createBaseChatConfiguration().headerChatConfig,
        headerConfig: {
          ...createBaseChatConfiguration().headerChatConfig.headerConfig,
          showSearch: true,
          searchConfig: {
            placeholder: "Search messages and participants...",
            debounceMs: 300,
            minChars: 1,
            showAdvancedSearch: true,
          },
        },
      },
      messageChatConfig: {
        ...createBaseChatConfiguration()?.messageChatConfig,
        onSearchMessage: async (value, chatId) => {
          console.log("Advanced search:", value, chatId);
          // Simulate advanced search with multiple result types
          return new Promise((resolve) => {
            setTimeout(() => {
              resolve([
                {
                  id: "search-msg-1",
                  author: "user",
                  authorName: "John Doe",
                  content: `<p>Found message containing "<mark>${value}</mark>" in conversation</p>`,
                  timestamp: "Yesterday, 2:30 PM",
                  date: new Date(Date.now() - 86400000).toISOString(),
                  showActions: true,
                  searchHighlight: true,
                },
                {
                  id: "search-msg-2",
                  author: "assistant",
                  authorName: "Assistant",
                  content: `<p>Another result with <mark>${value}</mark> highlighted</p>`,
                  timestamp: "2 days ago, 10:15 AM",
                  date: new Date(Date.now() - 172800000).toISOString(),
                  showActions: true,
                  searchHighlight: true,
                },
              ]);
            }, 800);
          });
        },
      },
    },
  },
};

/**
 * ## Chat with Custom Message Types
 *
 * This story shows different message types and priority levels:
 * - High priority messages
 * - System messages
 * - Deleted messages
 * - Pinned messages
 * - Thread conversations
 */
export const CustomMessageTypes = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Custom Message Types",
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      rightPanel: {
        ...createBaseChatConfiguration().rightPanel,
        loadMessages: async (chatId, page = 1) => {
          if (page > 1) return [];

          const customMessages = [
            {
              id: "msg-high-priority",
              author: "user",
              authorName: "Project Manager",
              content:
                "<p><strong>🚨 High Priority:</strong> Please review the urgent requirements document</p>",
              timestamp: "10:30 AM",
              date: new Date().toISOString(),
              priority: "high",
              showActions: true,
              isPinned: true,
            },
            {
              id: "msg-system",
              author: "system",
              authorName: "System",
              content: "<p><em>John Doe joined the conversation</em></p>",
              timestamp: "10:25 AM",
              date: new Date().toISOString(),
              type: "system",
              showActions: false,
            },
            {
              id: "msg-deleted",
              author: "user",
              authorName: "You",
              content: "<p>This message was deleted</p>",
              timestamp: "10:20 AM",
              date: new Date().toISOString(),
              deleted: true,
              showActions: true,
            },
            {
              id: "msg-thread-parent",
              author: "assistant",
              authorName: "Designer",
              content:
                "<p>Here's the latest design mockup. What do you think?</p>",
              timestamp: "10:15 AM",
              date: new Date().toISOString(),
              showActions: true,
              showReplyBadge: true,
              replyText: "3 replies",
            },
            {
              id: "msg-with-mention",
              author: "user",
              authorName: "Developer",
              content: `<p>Thanks <span class="mention" data-type="mention" data-id="1" data-label="John Doe">@John Doe</span> for the feedback!</p>`,
              timestamp: "10:10 AM",
              date: new Date().toISOString(),
              showActions: true,
              priority: "medium",
            },
          ];

          return new Promise((resolve) => {
            setTimeout(() => resolve(customMessages), 500);
          });
        },
      },
    },
  },
};

/**
 * ## Empty State Chat
 *
 * This story demonstrates the empty states of the chat feature:
 * - No channels selected
 * - No chats in channel
 * - No messages in chat
 * - Create new chat flow
 */
export const EmptyStateChat = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Empty State Chat",
    isChatOpen: true,
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      leftPanel: {
        ...createBaseChatConfiguration().leftPanel,
        hasDirectChatList: true,
        directChatList: [], // Empty list to show create new chat state
        loadChannelsList: async () => {
          return new Promise((resolve) => {
            setTimeout(() => resolve([]), 1000);
          });
        },
        loadChatList: async () => {
          return new Promise((resolve) => {
            setTimeout(() => resolve([]), 1000);
          });
        },
      },
      rightPanel: {
        ...createBaseChatConfiguration().rightPanel,
        loadMessages: async () => {
          return new Promise((resolve) => {
            setTimeout(() => resolve([]), 500);
          });
        },
      },
    },
  },
};

/**
 * ## Message Highlighting - Page 1
 *
 * This story demonstrates automatic message highlighting when a message
 * is already loaded on the first page. Features:
 *
 * - **Config-based highlighting**: Set `selectedMessageId` in configuration
 * - **Instant highlight**: Message is already loaded, no API call needed
 * - **One-time highlight**: Highlights only once per chat session
 * - **Visual feedback**: 1.5s scale animation with pulsing border
 * - **Auto-scroll**: Smoothly scrolls to the highlighted message
 *
 * **How to test:**
 * 1. Click the chat button to open the chat panel
 * 2. Select a chat from the list
 * 3. Watch as message "msg-5" automatically highlights with animation
 * 4. Notice the message is scrolled into center view
 * 5. The highlight stays for 3 seconds (configurable)
 */
export const MessageHighlightingPage1 = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Message Highlighting - Page 1",
    isChatOpen: false,
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      messageChatConfig: {
        ...createBaseChatConfiguration().messageChatConfig,

        // ========== Message Highlighting Configuration ==========
        // Highlight message that exists on page 1 (no API call needed)
        selectedMessageId: "msg-5", // Message on first page

        // Highlight behavior configuration
        maxSearchPages: 3, // Max pages to search if not found
        highlightDuration: 3000, // Duration before highlight clears (3 seconds)
        scrollBehavior: "smooth", // Smooth scroll animation
        scrollBlock: "center", // Scroll to center of viewport
        highlightColor: null, // Use default primary color
      },
      leftPanel: {
        ...createBaseChatConfiguration().leftPanel,
        hasDirectChatList: true,
        directChatList: [
          {
            id: 1,
            user: "John Doe",
            text: "Check out message #5 for important info",
            time: "10:30",
            title: "Project Discussion",
            subtitle: "Check out message #5 for important...",
            isChecked: false,
            isPinned: false,
            otherProps: {
              object_ids: [1],
              object_type: "deal",
            },
          },
        ],
      },
    },
  },
};

/**
 * ## Message Highlighting - Page 2 with Auto-Load
 *
 * This story demonstrates intelligent message highlighting when the message
 * is on a different page. Features:
 *
 * - **Smart page loading**: Automatically searches pages 2-3 for the message
 * - **Efficient API calls**: Only calls necessary pages (stops when found)
 * - **Page state tracking**: Updates infinite scroll to correct page
 * - **Same visual feedback**: Same animation and scroll behavior
 *
 * **How it works:**
 * 1. System checks page 1 - message not found
 * 2. Automatically loads page 2 via API call
 * 3. Message found! Stops searching (no page 3 call)
 * 4. Updates infinite scroll state to page 2
 * 5. Scrolls to message and applies highlight animation
 *
 * **How to test:**
 * 1. Click the chat button to open the chat panel
 * 2. Select a chat from the list
 * 3. Watch as page 2 loads automatically
 * 4. Message "msg-15" (on page 2) is highlighted
 * 5. Scroll up to see more page 1 messages are still there
 */
export const MessageHighlightingPage2 = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Message Highlighting - Page 2 (Auto-Load)",
    isChatOpen: false,
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      messageChatConfig: {
        ...createBaseChatConfiguration().messageChatConfig,

        // ========== Message Highlighting Configuration ==========
        // Highlight message on page 2 (requires automatic API call)
        selectedMessageId: "msg-15", // Message on second page

        // Configuration
        maxSearchPages: 3, // Will search up to page 3 if needed
        highlightDuration: 4000, // Slightly longer duration (4 seconds)
        scrollBehavior: "smooth",
        scrollBlock: "center",
      },
      leftPanel: {
        ...createBaseChatConfiguration().leftPanel,
        hasDirectChatList: true,
        directChatList: [
          {
            id: 1,
            user: "Jane Smith",
            text: "See my message on page 2 for details",
            time: "09:15",
            title: "Design Review",
            subtitle: "See my message on page 2 for details...",
            isChecked: false,
            isPinned: false,
            otherProps: {
              object_ids: [1],
              object_type: "deal",
            },
          },
        ],
      },
    },
  },
};

/**
 * ## Pinned Message Highlighting
 *
 * This story demonstrates pinned message highlighting with re-highlight capability.
 * Features:
 *
 * - **Interactive highlighting**: Click any pinned message to highlight it
 * - **Re-highlight support**: Click the same message multiple times
 * - **Panel stays open**: Pinned panel remains open for easy navigation
 * - **Visual feedback**: Same animation as config-based highlighting
 * - **Smart loading**: Automatically loads pages if message not in view
 *
 * **How to test:**
 * 1. Click the chat button to open the chat panel
 * 2. Select a chat from the list
 * 3. Click the "Pinned" icon in the header to open pinned messages
 * 4. Click any pinned message in the list
 * 5. Watch as the message highlights in the main chat area
 * 6. Panel stays open - click the same message again to re-highlight
 * 7. Try clicking different pinned messages
 *
 * **Key differences from config highlighting:**
 * - Config: Highlights once per chat session
 * - Pinned: Can re-highlight same message unlimited times
 */
export const PinnedMessageHighlighting = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Pinned Message Highlighting",
    isChatOpen: false,
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      messageChatConfig: {
        ...createBaseChatConfiguration().messageChatConfig,

        // Pinned message highlighting uses same configuration
        maxSearchPages: 3,
        highlightDuration: 3000,
        scrollBehavior: "smooth",
        scrollBlock: "center",
      },
      headerChatConfig: {
        ...createBaseChatConfiguration().headerChatConfig,

        // Load pinned messages (includes messages from multiple pages)
        onPinnedClick: async (chatId) => {
          console.log("Loading pinned messages for:", chatId);

          // Simulate pinned messages from different pages
          const pinnedMessages = [
            {
              id: "msg-3", // From page 1
              user: "Project Manager",
              userInitials: "PM",
              timestamp: "Today, 10:30 AM",
              content:
                "<p><strong>📌 Pinned:</strong> Important project deadline is Friday!</p>",
              senderName: "Project Manager",
            },
            {
              id: "msg-13", // From page 2
              user: "Designer",
              userInitials: "DS",
              timestamp: "Yesterday, 2:15 PM",
              content:
                "<p><strong>📌 Pinned:</strong> Final design mockups are ready for review.</p>",
              senderName: "Designer",
            },
            {
              id: "msg-7", // From page 1
              user: "Developer",
              userInitials: "DV",
              timestamp: "Today, 9:00 AM",
              content:
                "<p><strong>📌 Pinned:</strong> Code review required before merging PR #123.</p>",
              senderName: "Developer",
            },
          ];

          return new Promise((resolve) => {
            setTimeout(() => resolve(pinnedMessages), 800);
          });
        },
      },
      leftPanel: {
        ...createBaseChatConfiguration().leftPanel,
        hasDirectChatList: true,
        directChatList: [
          {
            id: 1,
            user: "Team Chat",
            text: "We have 3 pinned messages for reference",
            time: "10:30",
            title: "Team Discussion",
            subtitle: "We have 3 pinned messages for reference...",
            isChecked: false,
            isPinned: true,
            otherProps: {
              object_ids: [1],
              object_type: "deal",
            },
          },
        ],
      },
    },
  },
};

/**
 * ## Combined: Config + Pinned Highlighting
 *
 * This story demonstrates both highlighting methods working together seamlessly.
 * Shows the complete highlighting system in action.
 *
 * **Features demonstrated:**
 *
 * 1. **Initial config highlight**:
 *    - Message "msg-10" highlights automatically on page load
 *    - Uses config `selectedMessageId`
 *    - Highlights only once (won't re-highlight on state changes)
 *
 * 2. **Interactive pinned highlighting**:
 *    - Click pinned messages to highlight them
 *    - Can re-highlight same message multiple times
 *    - Independent from config highlighting
 *
 * 3. **Smart coordination**:
 *    - Config highlight happens first
 *    - Pinned clicks override config highlight
 *    - Both use same visual animation
 *    - No conflicts or duplicate API calls
 *
 * **Test scenario:**
 * 1. Click the chat button to open the chat panel
 * 2. Select a chat - watch msg-10 highlight automatically (config)
 * 3. Click the "Pinned" icon to open pinned panel
 * 4. Click msg-3 (different message) - highlights
 * 5. Click msg-10 again (same as config) - re-highlights successfully
 * 6. Config highlight won't re-trigger even if state changes
 * 7. Pinned highlights work unlimited times
 *
 * **Configuration:**
 * ```javascript
 * {
 *   selectedMessageId: "msg-10",  // Config: one-time highlight
 *   maxSearchPages: 3,
 *   highlightDuration: 3000,
 *   scrollBehavior: "smooth",
 *   scrollBlock: "center",
 * }
 * ```
 */
export const CombinedHighlighting = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Combined: Config + Pinned Highlighting",
    isChatOpen: false,
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      messageChatConfig: {
        ...createBaseChatConfiguration().messageChatConfig,

        // ========== Config-based highlighting ==========
        // This highlights automatically on page load (once per session)
        selectedMessageId: "msg-10", // On page 1

        // ========== Highlight configuration ==========
        maxSearchPages: 3, // Search up to 3 pages if needed
        highlightDuration: 3000, // 3 seconds
        scrollBehavior: "smooth", // Smooth scroll animation
        scrollBlock: "center", // Center in viewport
        highlightColor: null, // Use primary color
      },
      headerChatConfig: {
        ...createBaseChatConfiguration().headerChatConfig,

        onPinnedClick: async (chatId) => {
          // Pinned messages from various pages
          const pinnedMessages = [
            {
              id: "msg-3",
              user: "Sarah Johnson",
              userInitials: "SJ",
              timestamp: "Today, 11:45 AM",
              content:
                "<p>📌 <strong>Budget Approved:</strong> $50K allocated for Q4 initiatives</p>",
              senderName: "Sarah Johnson",
            },
            {
              id: "msg-10", // Same as config selectedMessageId
              user: "Mike Chen",
              userInitials: "MC",
              timestamp: "Today, 10:15 AM",
              content:
                "<p>📌 <strong>Action Required:</strong> Review and sign off on the proposal by EOD</p>",
              senderName: "Mike Chen",
            },
            {
              id: "msg-18", // On page 2
              user: "Alex Rivera",
              userInitials: "AR",
              timestamp: "Yesterday, 3:30 PM",
              content:
                "<p>📌 <strong>Meeting Notes:</strong> Key decisions from strategy session</p>",
              senderName: "Alex Rivera",
            },
          ];

          return new Promise((resolve) => {
            setTimeout(() => resolve(pinnedMessages), 700);
          });
        },
      },
      leftPanel: {
        ...createBaseChatConfiguration().leftPanel,
        hasDirectChatList: true,
        directChatList: [
          {
            id: 1,
            user: "Project Team",
            text: "Message #10 is auto-highlighted + 3 pinned messages",
            time: "11:45",
            title: "Project Updates",
            subtitle: "Message #10 is auto-highlighted + 3 pinned...",
            isChecked: false,
            isPinned: true,
            otherProps: {
              object_ids: [1],
              object_type: "project",
            },
          },
        ],
      },
    },
  },
};

/**
 * ## Custom Highlight Configuration
 *
 * This story demonstrates advanced configuration options for message highlighting:
 *
 * - **Custom colors**: Use brand-specific highlight color
 * - **Extended duration**: Longer highlight time (5 seconds)
 * - **Instant scroll**: No scroll animation for immediate focus
 * - **Top alignment**: Message appears at top of viewport
 * - **Extended search**: Search up to 5 pages
 *
 * **Custom Configuration:**
 * ```javascript
 * {
 *   selectedMessageId: "msg-25",    // On page 3
 *   maxSearchPages: 5,               // Search up to page 5
 *   highlightDuration: 5000,         // 5 seconds
 *   scrollBehavior: "auto",          // Instant scroll
 *   scrollBlock: "start",            // Top of viewport
 *   highlightColor: "#FF6B35",       // Custom orange color
 * }
 * ```
 */
export const CustomHighlightConfiguration = {
  render: (args) => <TableChatComponent {...args} />,
  args: {
    ...BasicChatFeature.args,
    tableHeader: "Custom Highlight Configuration",
    isChatOpen: false,
    chatConfiguration: {
      ...createBaseChatConfiguration(),
      messageChatConfig: {
        ...createBaseChatConfiguration().messageChatConfig,

        // ========== Custom Highlight Configuration ==========
        selectedMessageId: "msg-25", // Message on page 3
        maxSearchPages: 5, // Extended search range
        highlightDuration: 5000, // Extended duration (5 seconds)
        scrollBehavior: "auto", // Instant scroll (no animation)
        scrollBlock: "start", // Position at top of viewport
        highlightColor: "#FF6B35", // Custom orange highlight color
      },
      leftPanel: {
        ...createBaseChatConfiguration().leftPanel,
        hasDirectChatList: true,
        directChatList: [
          {
            id: 1,
            user: "System",
            text: "Custom highlight config: Orange color, 5s duration",
            time: "12:00",
            title: "Custom Highlighting Demo",
            subtitle: "Custom highlight config: Orange color...",
            isChecked: false,
            isPinned: false,
            otherProps: {
              object_ids: [1],
              object_type: "demo",
            },
          },
        ],
      },
    },
  },
};
