import { MESSAGE_CUSTOM_TYPE } from '@linktr.ee/messaging-taxonomy'
import classNames from 'classnames'
import React from 'react'
import {
  ChannelPreviewUIComponentProps,
  useChatContext,
} from 'stream-chat-react'

import { useChannelStar } from '../../hooks/useChannelStar'
import { formatRelativeTime } from '../../utils/formatRelativeTime'
import { getMessageDisplayText } from '../../utils/getMessageDisplayText'
import { resolveConversationParticipant } from '../../utils/resolveConversationParticipant'
import { resolveParticipantDisplayName } from '../../utils/resolveParticipantDisplayName'
import { Avatar } from '../Avatar'
import { isChatbotMessage } from '../CustomMessage/MessageTag'

import { useChannelListContext } from './ChannelListContext'

/**
 * Custom channel preview that handles selection
 */
const CustomChannelPreview = React.memo<ChannelPreviewUIComponentProps>(
  (props) => {
    const { channel, unread } = props
    const {
      selectedChannel,
      onChannelSelect,
      debug,
      channelPreview,
      renderMessagePreview,
      viewerLanguage,
    } = useChannelListContext()
    const { client } = useChatContext()

    const isSelected = selectedChannel?.id === channel?.id
    const isChannelStarred = useChannelStar(channel)

    if (channelPreview) {
      const ChannelPreview = channelPreview

      return (
        <ChannelPreview
          {...props}
          active={isSelected}
          selectedChannel={selectedChannel}
          onChannelSelect={onChannelSelect}
          viewerLanguage={viewerLanguage}
        />
      )
    }

    const handleClick = () => {
      if (channel) {
        onChannelSelect(channel)
      }
    }
    const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
      const isActivationKey = event.key === 'Enter' || event.key === ' '
      const isRepeatedKeydown = event.repeat

      if (!isActivationKey || isRepeatedKeydown) return

      event.preventDefault()
      handleClick()
    }

    // Get participant info
    const participant = resolveConversationParticipant(
      channel?.state?.members,
      client?.userID,
      channel?.type
    )
    const participantName = resolveParticipantDisplayName(participant?.user)
    const participantImage = participant?.user?.image

    // Get last non-system message for preview
    const lastMessage = (() => {
      const messages = channel?.state?.messages
      if (!messages?.length) return undefined
      for (let i = messages.length - 1; i >= 0; i--) {
        if (messages[i].type !== 'system') return messages[i]
      }
      return undefined
    })()

    const getLastMessageText = () => {
      const displayText = getMessageDisplayText({
        message: lastMessage,
        viewerLanguage,
      })

      const { custom_type, attachment_content_type } =
        lastMessage?.metadata || {}

      if (custom_type === MESSAGE_CUSTOM_TYPE.TIP) {
        return displayText ? displayText : 'Sent a tip'
      }
      if (custom_type === MESSAGE_CUSTOM_TYPE.PAID) {
        return displayText ? displayText : 'Sent a message'
      }
      if (custom_type === MESSAGE_CUSTOM_TYPE.ATTACHMENT) {
        if (attachment_content_type === 'text') {
          return '🔒 Sent a locked message'
        }
        if (attachment_content_type === 'media') {
          return '🔒 Sent a locked attachment'
        }
      }

      if (displayText) return displayText

      const attachment = lastMessage?.attachments?.[0]
      if (attachment) {
        // Link previews - show the actual URL
        if (attachment.og_scrape_url) return attachment.og_scrape_url

        // Type-based detection
        if (attachment.type === 'image') return '📷 Sent an image'
        if (attachment.type === 'video') return '🎥 Sent a video'
        if (attachment.type === 'audio') return '🎵 Sent audio'
        if (attachment.type === 'file') return '📎 Sent a file'

        // Fallback
        return '📎 Sent an attachment'
      }

      return 'No messages yet'
    }

    const lastMessageText = getLastMessageText()
    const lastMessageTime = lastMessage?.created_at
      ? formatRelativeTime(new Date(lastMessage.created_at))
      : ''
    const isLastMessageFromChatbot = lastMessage
      ? isChatbotMessage(lastMessage)
      : false

    const messagePreview = renderMessagePreview
      ? renderMessagePreview(lastMessage, lastMessageText)
      : `${isLastMessageFromChatbot ? '✨ ' : ''}${lastMessageText}`

    // Use the unread prop passed by Stream Chat (reactive and updates automatically)
    const unreadCount = unread ?? 0

    if (debug) {
      console.log('📺 [ChannelList] 📋 CHANNEL PREVIEW RENDER', {
        channelId: channel?.id,
        isSelected,
        participantName,
        unreadCount,
        hasTimestamp: !!lastMessageTime,
      })
    }

    return (
      <div
        role="button"
        tabIndex={0}
        onClick={handleClick}
        onKeyDown={handleKeyDown}
        className={classNames(
          'group w-full px-4 py-3 transition-colors text-left max-w-full overflow-hidden focus-ring rounded-[12px] [&+&]:mt-2',
          {
            'bg-black/[0.04]': isSelected,
            'hover:bg-black/[0.02]': !isSelected,
          }
        )}
        data-dd-privacy="mask"
      >
        <div className="flex items-start gap-4">
          {/* Avatar */}
          <Avatar
            id={participant?.user?.id || channel.id || 'unknown'}
            name={participantName}
            image={participantImage}
            size={48}
            starred={isChannelStarred}
          />

          {/* Content column */}
          <div className="flex-1 min-w-0 flex flex-col gap-1">
            {/* Name and timestamp row */}
            <div className="flex items-center justify-between gap-2">
              <h3
                className={classNames(
                  'text-sm font-medium truncate text-[#191918]'
                )}
              >
                {isChannelStarred && (
                  <span className="sr-only">Starred conversation. </span>
                )}
                {participantName}
              </h3>
              {lastMessageTime && (
                <span className="text-xs text-[#717070] flex-shrink-0">
                  {lastMessageTime}
                </span>
              )}
            </div>

            {/* Message and unread badge row */}
            <div className="flex items-center justify-between gap-2 min-w-0">
              <p className="text-sm text-[#717070] flex-1 line-clamp-1">
                {messagePreview}
              </p>
              {unreadCount > 0 && (
                <span className="bg-[#7f22fe] text-white text-[10px] rounded-full h-4 flex items-center justify-center p-1 min-w-4 text-center flex-shrink-0">
                  {unreadCount > 99 ? '99+' : unreadCount}
                </span>
              )}
            </div>
          </div>
        </div>
      </div>
    )
  }
)

export default CustomChannelPreview
CustomChannelPreview.displayName = 'CustomChannelPreview'
