import React, { useEffect, useMemo, useRef, useState } from "react"
import {
  Animated,
  FlatList,
  Image,
  Pressable,
  ScrollView,
  View,
  useWindowDimensions,
} from "react-native"

import { DateUtils, Mutator } from "@openchat/core"
import { RoomUtils } from "@openchat/models"
import {
  ChannelSectionType,
  MessageBoardFilterType,
  MessageBundleType,
  RoomType,
} from "@openchat/types"
import {
  useAccountId,
  useChannelSections,
  useCurrentRoomUISettings,
  useMembers,
} from "@openchat/ui"
import DraggableFlatList from "react-native-draggable-flatlist"
import { useSharedValue } from "react-native-reanimated"
import { AppAssets } from "../../../app/app.assets"
import { AppColors } from "../../../app/app.colors"
import { AppConfig } from "../../../app/app.config"
import { AppController } from "../../../app/app.globals"
import { useOrientation } from "../../../hook/use-orientation.hook"
import { Button } from "../../../ui-components/button/button.component"
import { Icon } from "../../../ui-components/icon/icon.component"
import { MenuOpener } from "../../../ui-components/menu/menu-opener.provider"
import { useModal } from "../../../ui-components/modal/modal.hook"
import { StyledText } from "../../../ui-components/styled-text/styled-text"
import { ChannelSectionAddEdit } from "../../channel/channel-section-create/channel-section-create.component"
import { MessageBoardCard } from "../message-board-card/message-board-card.component"
import { MessageBoardAddAndEditCard } from "../message-board-create-card/message-board-create-card.component"
import { MessageBoardEdit } from "../message-board-edit/message-board-edit.component"
import { useStyles } from "./message-board.style.module"

export const MessageBoard = ({ room }: { room: RoomType }) => {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------
  const styles = useStyles()
  const orientation = useOrientation()
  const [allMessageBundles, setAllMessageBundles] = useState<
    MessageBundleType[]
  >([])
  const [sections, setSections] = useState<
    (ChannelSectionType & {
      messageBundles: MessageBundleType[]
    })[]
  >([])
  const [isActived, setIsActived] = useState(false)
  const [searchBoard, setSearchBoard] = useState<MessageBoardFilterType>({
    keyword: "",
    userIds: [],
    tagIds: [],
    date: null,
  })
  const [isDraggable, setIsDraggable] = useState(false)
  const [updatePosition, setUpdatePosition] = useState<{
    [key: string]: number
  }>()

  const channelSections = useChannelSections()
  // const currentRoomUISettings = useCurrentRoomUISettings(room.id)
  const members = useMembers()
  const accountId = useAccountId()
  const [sectionIdForSectionEdit, setSectionIdForSectionEdit] = useState<
    string | null
  >(null)
  const [isLastItem, setLastItem] = useState(false)

  const modal = useModal()
  const currentRoomUISettings = useCurrentRoomUISettings(room.id)
  const positions = useSharedValue<{ [key: string]: number }>({})
  const scrollX = useRef(new Animated.Value(0)).current
  const [sectionIdForCardEdit, setSectionIdForCardEdit] = useState<
    string | null
  >(null)
  const { width, height } = useWindowDimensions()
  const [messageBundle, setMessageBundle] = useState<MessageBundleType | null>(
    null,
  )
  const [sectionsDataDrag, setSectionsDataDrag] = useState<
    (ChannelSectionType & {
      messageBundles: MessageBundleType[]
    })[]
  >([])
  const { communityId, channelId } = RoomUtils.extractIds(room.id)

  // ---------------------------------------------------------------------------
  // memos
  // ---------------------------------------------------------------------------

  const filteredChannelSections = useMemo(() => {
    return channelSections.filter((channelSection) => {
      if (!channelId) return
      return channelSection.channelId === channelId
    })
  }, [channelSections, channelId])

  const member = useMemo(
    () => members.find((member) => member.identityId === accountId),
    [members, accountId],
  )

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

  useEffect(() => {
    loadMessages()
  }, [room])

  useEffect(() => {
    buildSections()
  }, [
    filteredChannelSections,
    allMessageBundles,
    currentRoomUISettings.filterBoard,
    searchBoard,
  ])

  // useEffect(() => {
  //   onDragEnd()
  // }, [updatePosition])

  useEffect(() => {
    if (!currentRoomUISettings.filterBoard) return

    setSearchBoard((prev) => ({
      ...prev,
      ...currentRoomUISettings.filterBoard,
    }))
  }, [currentRoomUISettings.filterBoard])

  useEffect(() => {
    if (!channelId || !communityId) return
    setSections([
      ...sections,
      {
        channelId: channelId,
        communityId: communityId,
        id: "last",
        messageBundles: [],
        name: "",
        order: sections.length + 1,
      },
    ])

    sections.forEach((section) =>
      setMessageBundles((messageBundles) => [
        ...messageBundles,
        ...section.messageBundles,
      ]),
    )
  }, [channelId, channelId])

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

  async function loadMessages() {
    const localMessageBundles = await AppController.message.getFromLocal({
      roomId: room.id,
      direction: "all",
      directionDate: null,
      searchId: null,
    })

    // TODO: ^^ this reason why it was commented by Umed is because we need to update "edited" messages as well (this requires query to the host)
    // if (localMessages.length) {
    onMessagesLoad("local", localMessageBundles)
    // } else {
    const remoteMessageBundles = await AppController.message.getFromHost({
      localMessageBundles: localMessageBundles,
      roomId: room.id,
      directionDate: null,
      searchId: null,
      direction: "all",
    })

    onMessagesLoad("remote", remoteMessageBundles)
    // }
  }

  function onMessagesLoad(
    source: "local" | "remote",
    messageBundles: MessageBundleType[],
  ) {
    if (!messageBundles.length) return

    if (source === "local") {
      setAllMessageBundles(messageBundles)
    } else {
      setAllMessageBundles(messageBundles)
    }
  }

  function buildSections() {
    let filteredSections: (ChannelSectionType & {
      messageBundles: MessageBundleType[]
    })[] = []

    filteredSections = filteredChannelSections.map((section) => {
      return {
        ...section,
        messageBundles: allMessageBundles
          .filter(
            (messageBundle) =>
              messageBundle.message.board &&
              messageBundle.message.board.sectionId === section.id,
          )
          .sort((a, b) => {
            if (a.message.board && b.message.board) {
              return a.message.board.order - b.message.board.order
            }
            return 0
          }),
      }
    })
    filteredSections.sort((a, b) => a.order - b.order)

    // this conditions for board filter panel
    if (
      searchBoard.keyword ||
      searchBoard.userIds.length ||
      searchBoard.tagIds.length ||
      searchBoard.date
    ) {
      for (let section of filteredSections) {
        const filteredMessages: MessageBundleType[] = []
        for (let messageBundle of section.messageBundles) {
          if (searchBoard.keyword && messageBundle.message.board) {
            if (
              messageBundle.message.board.title &&
              messageBundle.message.board.title
                .toLowerCase()
                .indexOf(searchBoard.keyword.toLowerCase()) !== -1
            ) {
              if (filteredMessages.indexOf(messageBundle) === -1) {
                filteredMessages.push(messageBundle)
              }
            }
          }

          if (searchBoard.userIds.length && messageBundle.message.board) {
            const hasUserId = messageBundle.message.board.attachedUserIds.some(
              (attachedUserId) => searchBoard.userIds.includes(attachedUserId),
            )
            if (hasUserId) {
              if (filteredMessages.indexOf(messageBundle) === -1) {
                filteredMessages.push(messageBundle)
              }
            }
          }

          if (searchBoard.tagIds.length && messageBundle.message.board) {
            const hasTagId = messageBundle.message.board.tagIds.some((tagId) =>
              searchBoard.tagIds.includes(tagId),
            )
            if (hasTagId) {
              if (filteredMessages.indexOf(messageBundle) === -1) {
                filteredMessages.push(messageBundle)
              }
            }
          }

          if (searchBoard.date && messageBundle.message.board) {
            if (messageBundle.message.board.endDate) {
              const hasDate =
                DateUtils.createDate(
                  messageBundle.message.board.endDate,
                ).getDate() <= searchBoard.date.getDate()

              if (hasDate) {
                if (filteredMessages.indexOf(messageBundle) === -1) {
                  filteredMessages.push(messageBundle)
                }
              }
            }
          }
        }

        section.messageBundles = filteredMessages
      }
    }

    setSections(filteredSections)
  }

  async function onDragEnd(
    sections: (ChannelSectionType & {
      messageBundles: MessageBundleType[]
    })[],
  ) {
    if (!communityId) return

    await AppController.channelSection.reorder({
      ids: [...sections].map((section) => section.id),
      communityId: communityId,
    })
    // await AppController.channelSection.cardReorder({
    //   communityId: community!.id,
    //   sections: orderedSections.map((section) => {
    //     return {
    //       sectionId: section.id,
    //       messageIds: section.messageBundles.map(
    //         (messageBundle) => messageBundle.message.id,
    //       ),
    //     }
    //   }),
    // })
  }

  async function removeSection(section: ChannelSectionType) {
    await AppController.channelSection.delete({
      sectionId: section.id,
      channelId: section.channelId,
      communityId: section.communityId,
      messageIds: allMessageBundles
        .filter(
          (messageBundle) =>
            messageBundle.message.board &&
            messageBundle.message.board.sectionId === section.id,
        )
        .map((messageBundle) => messageBundle.message.id),
    })
  }

  // const [sectionsDataDrag, setSectionsDataDrag] = useState<
  //   (ChannelSectionType & {
  //     messageBundles: MessageBundleType[]
  //   })[]
  // >([])

  const [messageBundles, setMessageBundles] = useState<MessageBundleType[]>([])

  const lastItem = sectionsDataDrag.find((item) => item.id === "last")
  let heightOfCarousel =
    orientation === "landscape" && width <= 667
      ? height / 1.2
      : orientation === "landscape" && width <= 852
        ? height / 1.3
        : orientation === "landscape" && width > 900
          ? height / 1.2
          : height <= 667
            ? height / 1.12
            : height / 1.14
  console.log("filteredChannelSections", filteredChannelSections)

  // ---------------------------------------------------------------------------
  return (
    <View>
      <DraggableFlatList
        style={{
          height: height * 0.895,
        }}
        contentContainerStyle={{ flexGrow: 1 }}
        data={sections}
        keyExtractor={(item, index) => `draggable-item-${index}`}
        onDragEnd={({ data }) => {
          onDragEnd(data)
          // setUpdatePosition()
        }}
        pagingEnabled
        dragItemOverflow={true}
        showsHorizontalScrollIndicator={false}
        horizontal={true}
        // onScroll={Animated.event(
        //   [{ nativeEvent: { contentOffset: { x: scrollX } } }],
        //   { useNativeDriver: true },
        // )}
        renderItem={({ item, drag, isActive }) => (
          <>
            {sections.length === 0 ? (
              <ScrollView style={{}} contentContainerStyle={{ flexGrow: 1 }}>
                <View
                  style={{
                    zIndex: 999,
                    position: "relative",
                    flex: 1,
                    justifyContent: "space-between",
                  }}
                >
                  {/* <View
              style={{
                // flex: 1,
                justifyContent: "space-between",
              }}
            > */}
                  <Image
                    source={AppAssets.images.topBoardBg.uri}
                    style={styles.imgBgTopLastItem}
                    resizeMode={"stretch"}
                  />
                  <View
                    style={{
                      // flex: 1,
                      justifyContent: "center",
                      alignItems: "center",
                      gap: 30,
                    }}
                  >
                    <Image
                      source={AppAssets.images.dashboardEmptyPhoto.uri}
                      style={{ width: 180, height: 120 }}
                    />
                    <Button
                      containerStyle={{
                        alignSelf: "center",
                        position: "relative",
                        top: 5,
                        justifyContent: "center",
                      }}
                      type="primary"
                      onPress={() => {
                        setSectionIdForSectionEdit("last")
                        if (!member) return
                        modal.open({
                          component: (
                            <ChannelSectionAddEdit
                              room={room}
                              section={item.id !== "last" ? item : undefined}
                              onClose={() => setSectionIdForSectionEdit(null)}
                            />
                          ),
                          background: "pattern",
                          footer: "rgb",
                          scrollEnabled: false,
                          keyboard: 240,
                        })
                      }}
                    >
                      Add column
                    </Button>
                  </View>
                  <Image
                    source={AppAssets.images.bottomBoardBg.uri}
                    style={styles.imgBgBottomLastItem}
                    resizeMode={"stretch"}
                  />
                  {/* </View> */}
                </View>
              </ScrollView>
            ) : (
              <>
                <Pressable
                  onLongPress={() => {
                    // setIsDraggable((isDraggable) => !isDraggable)
                    // setIsActived(true)
                    drag()
                  }}
                  style={[
                    {
                      flexShrink: 1,
                      alignItems: "flex-start",
                      maxWidth: AppConfig.isTablet ? width * 0.6 : width,
                      flexDirection: "row",
                      borderRadius: 0,
                      padding: 20,
                    },
                  ]}
                >
                  {/* --------------------------------------------------------------------------- */}
                  {/* SECTION NAME */}
                  {/* --------------------------------------------------------------------------- */}

                  <View style={styles.sectionHeaderTitleContainer}>
                    <View
                      style={{
                        flexDirection: "row",
                        width: "100%",
                        justifyContent: "space-between",
                        paddingVertical: 15,
                        // paddingHorizontal: 20,
                      }}
                    >
                      <View
                        style={{
                          width: "70%",
                          flexDirection: "row",
                          gap: 10,
                        }}
                      >
                        <StyledText style={styles.sectionTitle}>
                          {item.name}
                        </StyledText>
                        {item.messageBundles?.length > 0 && (
                          <View
                            style={{
                              width: 25,
                              height: 21,
                              paddingHorizontal: 5,
                              backgroundColor: "#EEF2F6",
                              justifyContent: "center",
                              alignItems: "center",
                              borderRadius: 5,
                              marginTop: 2,
                            }}
                          >
                            <StyledText
                              style={{
                                paddingBottom: 1.5,
                                fontSize: 16,
                                fontWeight: "400",
                                color: AppColors.textSecondary,
                              }}
                            >
                              {item.messageBundles.length}
                            </StyledText>
                          </View>
                        )}
                      </View>
                      <View>
                        {member && (
                          <MenuOpener
                            content={
                              <MessageBoardEdit
                                item={item}
                                member={member}
                                removeSection={removeSection}
                                room={room}
                                setSectionIdForSectionEdit={
                                  setSectionIdForSectionEdit
                                }
                              />
                            }
                            style={{ marginLeft: -20, marginTop: -30 }}
                          >
                            {item.id !== "last" && (
                              <View>
                                <Icon
                                  name="far fa-ellipsis-vertical"
                                  size={18}
                                  style={{
                                    marginRight: -8,
                                    justifyContent: "flex-end",
                                  }}
                                />
                              </View>
                            )}
                          </MenuOpener>
                        )}
                      </View>
                    </View>
                    <View
                      style={{
                        flexShrink: 1,
                      }}
                    >
                      <FlatList
                        style={{ flexShrink: 1 }}
                        data={item.messageBundles}
                        renderItem={({
                          item: messageBundle,
                          index: cardIndex,
                        }) => (
                          <MessageBoardCard
                            testID={`card.${cardIndex}`}
                            room={room}
                            messageBundle={messageBundle}
                            onUpdatedMessageBundle={(updateMessageBundle) => {
                              setAllMessageBundles((prev) =>
                                Mutator.replace(
                                  prev,
                                  messageBundle,
                                  updateMessageBundle,
                                ),
                              )
                            }}
                          />
                        )}
                        keyExtractor={(item) => item.message.id}
                        scrollEnabled={true}
                        showsVerticalScrollIndicator={false}
                        ListFooterComponent={
                          item.id !== "last" ? (
                            <Button
                              onPress={() => {
                                setSectionIdForCardEdit(item.id)
                                modal.open({
                                  component: (
                                    <MessageBoardAddAndEditCard
                                      room={room}
                                      section={item}
                                      onClose={() =>
                                        setSectionIdForCardEdit(null)
                                      }
                                    />
                                  ),
                                  background: "pattern",
                                  footer: "rgb",
                                  keyboard: 750,
                                })
                              }}
                              type="link"
                              containerStyle={{
                                backgroundColor: AppColors.light,
                                justifyContent: "center",
                                paddingVertical: 8,
                                marginBottom: 8,
                                borderRadius: 5,
                                height: 39,
                                shadowOffset: {
                                  width: 0,
                                  height: 2,
                                },
                                shadowRadius: 1,
                                shadowColor: "#0000000D",
                                shadowOpacity: 0.5,
                                elevation: 4,
                              }}
                              icon="plus"
                              styleText={{ fontSize: 18 }}
                            >
                              Add a card
                            </Button>
                          ) : null
                        }
                      />
                    </View>
                  </View>
                </Pressable>
              </>
            )}
          </>
        )}
      />
    </View>
  )
}
I have issue when I pass on DraggableFlatList data={sections} the drag and drop is working but this part  <ScrollView style={{}} contentContainerStyle={{ flexGrow: 1 }}>
                <View
                  style={{
                    zIndex: 999,
                    position: "relative",
                    flex: 1,
                    justifyContent: "space-between",
                  }}
                >
                  {/* <View
              style={{
                // flex: 1,
                justifyContent: "space-between",
              }}
            > */}
                  <Image
                    source={AppAssets.images.topBoardBg.uri}
                    style={styles.imgBgTopLastItem}
                    resizeMode={"stretch"}
                  />
                  <View
                    style={{
                      // flex: 1,
                      justifyContent: "center",
                      alignItems: "center",
                      gap: 30,
                    }}
                  >
                    <Image
                      source={AppAssets.images.dashboardEmptyPhoto.uri}
                      style={{ width: 180, height: 120 }}
                    />
                    <Button
                      containerStyle={{
                        alignSelf: "center",
                        position: "relative",
                        top: 5,
                        justifyContent: "center",
                      }}
                      type="primary"
                      onPress={() => {
                        setSectionIdForSectionEdit("last")
                        if (!member) return
                        modal.open({
                          component: (
                            <ChannelSectionAddEdit
                              room={room}
                              section={item.id !== "last" ? item : undefined}
                              onClose={() => setSectionIdForSectionEdit(null)}
                            />
                          ),
                          background: "pattern",
                          footer: "rgb",
                          scrollEnabled: false,
                          keyboard: 240,
                        })
                      }}
                    >
                      Add column
                    </Button>
                  </View>
                  <Image
                    source={AppAssets.images.bottomBoardBg.uri}
                    style={styles.imgBgBottomLastItem}
                    resizeMode={"stretch"}
                  />
                  {/* </View> */}
                </View>
              </ScrollView> not showing. When I change sections to sectionsDataDrag in data everything is working except drag and drop not working. How to fix it ? Please help me!