import React from 'react'
import { Chat } from 'stream-chat-react'

import { createMockStreamChatClient } from '../testing/createMockStreamChatClient'

// Mock Stream Chat client for Storybook
const mockUser = {
  id: 'storybook-user',
  name: 'Storybook User',
  image: 'https://i.pravatar.cc/150?img=1',
}

const createMockClient = () =>
  createMockStreamChatClient(mockUser, { stubConnection: true })

// Create a mock chat provider with pre-populated channels
export const MockChatProviderWithChannels: React.FC<{
  children: React.ReactNode
  channelCount?: number
}> = ({ children, channelCount = 3 }) => {
  const [client] = React.useState(() => {
    const mockClient = createMockClient()

    // Create mock channels
    const mockChannels = Array.from({ length: channelCount }, (_, i) => {
      const participant = mockParticipants[i % mockParticipants.length]
      const eventListeners = new Map<
        string,
        Set<(...args: unknown[]) => void>
      >()

      const latestMessage = {
        id: `msg-${i}-1`,
        text: `Hey! This is message ${i + 1}`,
        created_at: new Date(Date.now() - 1000 * 60 * (i + 1)),
        user: participant,
      }

      const mockChannel = {
        id: `channel-${i + 1}`,
        cid: `messaging:channel-${i + 1}`,
        type: 'messaging',
        _client: mockClient,
        state: {
          members: {
            [mockUser.id]: {
              user: mockUser,
              user_id: mockUser.id,
            },
            [participant.id]: {
              user: participant,
              user_id: participant.id,
            },
          },
          latestMessages: [latestMessage],
          messages: [latestMessage],
          messageSets: [
            {
              isCurrent: true,
              isLatest: true,
              messages: [latestMessage],
            },
          ],
          unreadCount: i === 0 ? 2 : 0,
          read: {},
        },
        // Mock channel methods
        countUnread: () => (i === 0 ? 2 : 0),
        muteStatus: () => false,
        on: (eventName: string, listener: (...args: unknown[]) => void) => {
          if (!eventListeners.has(eventName)) {
            eventListeners.set(eventName, new Set())
          }
          eventListeners.get(eventName)?.add(listener)
          return {
            unsubscribe: () => {
              eventListeners.get(eventName)?.delete(listener)
            },
          }
        },
        off: (eventName: string, listener: (...args: unknown[]) => void) => {
          eventListeners.get(eventName)?.delete(listener)
        },
        query: async () => ({ messages: [] }),
        watch: async () => ({ messages: [] }),
      }

      return mockChannel
    })

    // @ts-expect-error - Mock queryChannels method
    mockClient.queryChannels = async () => mockChannels

    return mockClient
  })

  React.useEffect(() => {
    return () => {
      client.disconnectUser().catch(console.error)
    }
  }, [client])

  return <Chat client={client}>{children}</Chat>
}

// Mock participants for testing
export const mockParticipants = [
  {
    id: 'participant-1',
    name: 'Alice Johnson',
    image: 'https://i.pravatar.cc/150?img=2',
  },
  {
    id: 'participant-2',
    name: 'Bob Smith',
    image: 'https://i.pravatar.cc/150?img=3',
  },
  {
    id: 'participant-3',
    name: 'Carol Williams',
    image: 'https://i.pravatar.cc/150?img=4',
  },
  {
    id: 'participant-4',
    name: 'David Brown',
    image: 'https://i.pravatar.cc/150?img=5',
  },
  {
    id: 'participant-5',
    name: 'Emma Davis',
    image: 'https://i.pravatar.cc/150?img=6',
  },
]
