import { Image, TouchableOpacity, View } from "react-native"
import React, { useEffect, useMemo, useState } from "react"
import {
  AttachmentType,
  FileType,
  MessageBundleType,
  MessageLoadStrategyType,
  MessageType,
  PollType,
  RoomKindEnum,
} from "@openchat/types"
import { DateUtils } from "@openchat/core"
import { useModal } from "../../../ui-components/modal/modal.hook"
import { useAlert } from "../../../ui-components/alert"
import {
  useAccountId,
  useMemberBy,
  useMembersBy,
  useMessageBundle,
  useRoomMetadata,
} from "@openchat/ui"
import { AppController } from "../../../app/app.globals"
import { MessageQuoted } from "../message-quoted/message-quoted.component"
import { MessageItemContent } from "../message-item-content/message-item-content.component"
import { MessageListModal } from "../message-list-item-modal/message-list-item.modal"
import { MessageReactions } from "../message-reactions/message-reactions.component"
import { MessageSender } from "../message-sender/message-sender.component"
import { NavigationRef } from "../../../navigation/navigation.hooks"
import { AppAssets } from "../../../app/app.assets"
import { useStyles } from "./message-regular-list-item.style"
import { RoomUtils } from "@openchat/models"
import { StackActions } from "@react-navigation/native"
import { PressableModalOpener } from "../../../ui-components/pressable-modal-opener/pressable-modal-opener.component"
import { MessageAttachmentPreview } from "../message-attachment-preview/message-attachment-preview.component"
import { MessageLinkPreview } from "../message-link-preview/message-link-preview.component"
import { StyledText } from "../../../ui-components/styled-text/styled-text"
import { UserCollagePhoto } from "../../user/user-collage-photo/user-collage-photo.component"

export const MessageRegularListItem = ({
  roomId,
  messageBundle,
  mode = "regular",
  onMessageUpdate,
  onQuoteClick,
  onMessageView,
  isHighlighted,
  senderShow,
  ...actionBarProps
}: {
  roomId: string
  messageBundle: MessageBundleType
  mode?: "regular" | "starred"
  onMessageDelete: (deletedMessageId: string) => void
  onMessageView?: (message: MessageType) => void
  onQuoteClick: (messageId: string) => void
  onMessageUpdate: (
    editedMessage: MessageType,
    attachments: AttachmentType[],
    files: FileType[],
    poll?: PollType,
  ) => void
  isHighlighted: boolean
  senderShow: boolean
}) => {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------

  const styles = useStyles()
  const modal = useModal()
  const { communityId, messageId } = RoomUtils.extractIds(roomId)
  const { channel, kind } = useRoomMetadata(roomId)
  const [isEditing, setEditing] = useState(false)
  const [messageBundles, setMessageBundles] = useState<MessageBundleType[]>([])
  const alert = useAlert()
  const accountId = useAccountId()
  const sender = useMemberBy({
    communityId: communityId,
    identityId: messageBundle.message.senderId,
  })
  const currentMember = useMemberBy({
    communityId: communityId,
    identityId: accountId,
  })
  const [files, setFiles] = useState<FileType[]>([])
  const isCover =
    channel && channel.coverImageKey !== "no-cover" && !!channel.coverImageKey

  const replySenderIds = useMemo(
    () => messageBundles.map((message) => message.message.senderId),
    [messageBundles],
  )
  const communityMembers = useMembersBy({ communityId: communityId })
  const replyUsers = communityMembers.filter((member) =>
    replySenderIds.some((id) => id === member.identityId),
  )
  const parentMessage = useMessageBundle(messageId)
  console.log("===============parentMessage=====================")
  console.log("parentMessage", parentMessage)
  console.log("====================================")

  const messageReplyRoomId = channel
    ? RoomUtils.createId({
        kind: RoomKindEnum.CHANNEL_REGULAR_REPLY,
        channelId: channel.id,
        communityId: channel.communityId,
        messageId: messageBundle.message.id,
      })
    : null

  // ---------------------------------------------------------------------------
  // effects
  // ---------------------------------------------------------------------------

  useEffect(() => {
    getFiles()
    if (!onMessageView) return
    onMessageView(messageBundle.message)
  }, [messageBundle])

  useEffect(() => {
    if (messageBundle.metadata.replyCount > 0) loadMessages(null, "end", null)
  }, [messageBundle.metadata.replyCount])

  // ---------------------------------------------------------------------------
  // functions
  // ---------------------------------------------------------------------------

  async function loadMessages(
    directionDate: number | null,
    direction: MessageLoadStrategyType,
    searchId: string | null,
  ) {
    if (!messageReplyRoomId || messageBundle.metadata.replyCount === 0) return

    const localMessageBundles = await AppController.message.getFromLocal({
      roomId: messageReplyRoomId,
      directionDate,
      direction,
      searchId,
    })
    setMessageBundles(localMessageBundles)

    const remoteMessageBundles = await AppController.message.getFromHost({
      localMessageBundles: localMessageBundles,
      roomId: messageReplyRoomId,
      directionDate,
      direction,
      searchId,
    })

    setMessageBundles(remoteMessageBundles)
  }

  async function getFiles() {
    const fileIds = messageBundle.attachments.map(
      (attachment) => attachment.fileId,
    )

    if (!fileIds.length) return
    const files = await AppController.file.getByIds({
      ids: fileIds,
      roomId: messageBundle.message.roomId,
    })

    setFiles(files)
  }

  function onPopupReplyClick(message: MessageType) {
    if (!channel || !communityId) return

    const replyRoomId = RoomUtils.createId({
      messageId: message.id,
      channelId: channel.id,
      communityId: communityId,
      kind: RoomKindEnum.CHANNEL_REGULAR_REPLY,
    })

    NavigationRef.dispatch(
      StackActions.push("MessageRoom", {
        roomId: replyRoomId,
      }),
    )
  }

  function onPollUpdate(poll: PollType) {
    onMessageUpdate(
      messageBundle.message,
      messageBundle.attachments,
      files,
      poll,
    )
  }

  function onAddEmojiPress() {
    modal.open({
      component: (
        <MessageListModal
          roomId={roomId}
          type={RoomKindEnum.CHANNEL_REGULAR}
          mode={mode}
          onPopupMessageEditClick={() =>
            !messageBundle.poll
              ? setEditing((prev) => !prev)
              : editPoll(messageBundle.poll)
          }
          onPopupReplyClick={onPopupReplyClick}
          message={messageBundle.message}
          attachments={messageBundle.attachments}
          popupState="stickers"
          onTextCopied={() => {
            alert.open({
              text: "Message copied",
              mode: "simple",
            })
          }}
          totalVotedUsersCount={
            messageBundle.poll && messageBundle.poll.totalVotedUsersCount
          }
          {...actionBarProps}
        />
      ),
      scrollEnabled: true,
    })
  }

  function editPoll(selectedPoll: PollType) {
    NavigationRef.navigate("PollUpsert", {
      onSend: (poll) => {
        onMessageUpdate(
          messageBundle.message,
          messageBundle.attachments,
          files,
          {
            ...selectedPoll,
            title: poll.title,
            isMultiple: poll.isMultiple,
            pollOptions: poll.options.filter(
              (option: any) => option.name !== "",
            ),
          },
        )
      },
      poll: selectedPoll,
    })
  }

  // ---------------------------------------------------------------------------
  if (!channel) return null
  return (
    <PressableModalOpener
      mode="long"
      onModalOpen={() => ({
        component: (
          <MessageListModal
            roomId={roomId}
            type={kind ? kind : RoomKindEnum.CHANNEL_REGULAR}
            mode={mode}
            onPopupMessageEditClick={() =>
              !messageBundle.poll
                ? setEditing((prev) => !prev)
                : editPoll(messageBundle.poll)
            }
            onPopupReplyClick={onPopupReplyClick}
            message={messageBundle.message}
            attachments={messageBundle.attachments}
            popupState="menu"
            onTextCopied={() => {
              alert.open({
                text: "Message copied",
                mode: "simple",
              })
            }}
            totalVotedUsersCount={
              messageBundle.poll && messageBundle.poll.totalVotedUsersCount
            }
            {...actionBarProps}
          />
        ),
        scrollEnabled: true,
      })}
      style={[
        styles.messageContainer,
        isHighlighted
          ? {
              backgroundColor: "#E9F4FF",
            }
          : {},
      ]}
    >
      <View>
        {isHighlighted && <View style={styles.blueLine} />}
        <View style={[isCover ? styles.coverContainer : styles.subContainer]}>
          <View>
            {/* ---------------------- */}
            {sender && senderShow && (
              <MessageSender
                sender={{ ...sender, id: sender.identityId, status: null }}
                createdAt={DateUtils.createDate(
                  messageBundle.message.createdAt,
                )}
                type={"regular"}
                isEdited={messageBundle.message.isEdited}
              />
            )}

            <View style={[!isCover ? { marginLeft: 35 } : { marginLeft: 25 }]}>
              {/* --------- quoted message --------- */}
              {/* todo: fix it */}
              <MessageQuoted
                roomId={roomId}
                message={messageBundle.message}
                onPress={() => {
                  if (
                    !onQuoteClick ||
                    !messageBundle.message.regular ||
                    !messageBundle.message.regular.quote
                  ) {
                    return
                  }
                  onQuoteClick(messageBundle.message.regular.quote.id)
                }}
              />

              {/* --------- message --------- */}
              <MessageItemContent
                roomId={roomId}
                parentMessage={parentMessage}
                message={messageBundle.message}
                poll={messageBundle.poll}
                onEditingFinished={(editedMessage) => {
                  setEditing(false)
                  onMessageUpdate(
                    editedMessage,
                    messageBundle.attachments,
                    files,
                  )
                }}
                onPollUpdate={onPollUpdate}
                onEditingCanceled={() => {
                  setEditing(false)
                }}
                isEditing={isEditing}
              />

              {/* --------- reactions --------- */}
              {messageBundle.message.reactions.length > 0 && (
                <View style={styles.msgReaction}>
                  <MessageReactions
                    reactions={messageBundle.message.reactions}
                    message={messageBundle.message}
                    disabled={!currentMember}
                  />
                  <TouchableOpacity
                    onPress={onAddEmojiPress}
                    style={styles.stickerPlusImageWrap}
                  >
                    <Image
                      style={styles.stickerPlusImage}
                      source={AppAssets.images.stickerIconPlus.uri}
                    />
                  </TouchableOpacity>
                </View>
              )}

              {/* todo: fix it */}
              {messageBundle.attachments.length > 0 && (
                <View>
                  <MessageAttachmentPreview
                    attachments={messageBundle.attachments}
                    // sender={
                    //   community
                    //     ? userPresentation.communities[community.id]
                    //     : userPresentation.lastSeenAs
                    // }
                    // date={DateUtils.createDate(message.createdAt)}
                  />
                </View>
              )}

              {messageBundle.metadata.replyCount > 0 && (
                <View style={styles.repliesCountHolder}>
                  <UserCollagePhoto
                    members={replyUsers.slice(0, 3)}
                    size={25}
                  />

                  <StyledText
                    style={styles.repliesCount}
                    onPress={() => {
                      onPopupReplyClick(messageBundle.message)
                    }}
                  >{`${messageBundle.metadata.replyCount} reply`}</StyledText>
                  {/*<StyledText style={styles.lastReplyTime}></StyledText>*/}
                </View>
              )}

              {messageBundle.links.length !== 0 && (
                <>
                  {messageBundle.links.map((link) => (
                    <MessageLinkPreview key={link.id} link={link} />
                  ))}
                </>
              )}
            </View>
          </View>
        </View>
      </View>
    </PressableModalOpener>
  )
}
I am using this   function onPopupReplyClick(message: MessageType) {
    if (!channel || !communityId) return

    const replyRoomId = RoomUtils.createId({
      messageId: message.id,
      channelId: channel.id,
      communityId: communityId,
      kind: RoomKindEnum.CHANNEL_REGULAR_REPLY,
    })

    NavigationRef.dispatch(
      StackActions.push("MessageRoom", {
        roomId: replyRoomId,
      }),
    )
  }, when I click    <StyledText
                    style={styles.repliesCount}
                    onPress={() => {
                      onPopupReplyClick(messageBundle.message)
                    }}
                  >{`${messageBundle.metadata.replyCount} reply`}</StyledText> it navigates me to new room of reply specific message, I want navigate to new room with parent message of replies. How to implement it ?