import { UserStatusKind } from "@openchat/types"
import { DateUtils } from "@openchat/core"
import {
  CurrentRoomUISettingsModel,
  useCurrentRoomUISettings,
  useMembersBy,
  useTagsBy,
} from "@openchat/ui"
import React, { useEffect, useMemo, useState } from "react"
import {
  Pressable,
  SafeAreaView,
  ScrollView,
  TouchableOpacity,
  View,
} from "react-native"
import { SvgXml } from "react-native-svg"
import { AppController, AppStore } from "../../../app/app.globals"
import { Checkbox } from "../../../ui-components/checkbox/checkbox.component"
import { CustomCalendar } from "../../../ui-components/custom-calendar/custom-calendar.component"
import { Input } from "../../../ui-components/input/input"
import { useModal } from "../../../ui-components/modal/modal.hook"
import { Radio } from "../../../ui-components/radio/radio.component"
import { XIcon } from "../../../ui-components/svgIcons/svgIcons"
import { UserPhoto } from "../../user/user-photo/user-photo.component"
import { useStyles } from "./message-board-keyword.style"
import { StyledText } from "../../../ui-components/styled-text/styled-text"
import { AppColors } from "../../../app/app.colors"
import { RoomUtils } from "@openchat/models"

export const MessageBoardKeyword = ({ roomId }: { roomId: string }) => {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------

  const styles = useStyles()
  const modal = useModal()
  const currentRoomUISettings = useCurrentRoomUISettings(roomId)
  const { communityId } = RoomUtils.extractIds(roomId)
  const members = useMembersBy({ communityId })
  const tags = useTagsBy({ communityId })
  const [messageBoard, setMessageBoard] = useState<{
    userIds: string[]
    tagIds: string[]
  }>()
  const [fromDateCustom, setFromDateCustom] = useState<Date>()
  const [toDateCustom, setToDateCustom] = useState<Date>()

  const [boardFiltered, setBoardFiltered] = useState<{
    keyword: string
    userIds: string[]
    tagIds: string[]
    date: { id: number; name: string; value: Date | null | undefined }
  }>({
    keyword: "",
    userIds: [],
    tagIds: [],
    date: { id: 0, name: "", value: null },
  })

  const [reset, setReset] = useState({
    isUser: false,
    isTag: false,
    isDate: false,
  })
  const [showMore, setShowMore] = useState({
    isUser: false,
    isTag: false,
  })
  const today = new Date()

  const dueDates = [
    {
      id: 1,
      name: "Today",
      value: new Date(),
    },
    {
      id: 2,
      name: "Yesterday",
      value: new Date(today.getFullYear(), today.getMonth(), today.getDate()),
    },
    {
      id: 3,
      name: "Last week",
      value: new Date(
        new Date().getFullYear(),
        new Date().getMonth(),
        new Date().getDate() - 7,
      ),
    },
    {
      id: 4,
      name: "Last Month",
      value: new Date(
        today.getFullYear(),
        today.getMonth() - 1,
        today.getDate(),
      ),
    },
    {
      id: 5,
      name: "Custom date",
      value: new Date(),
    },
  ]

  console.log("==================boardFiltered==================")
  console.log(boardFiltered)
  console.log("==================end==================")

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

  const attachmentMembers = members.filter(
    (member) => messageBoard && messageBoard.userIds.includes(member.id),
  )

  const attachmentTags = useMemo(() => {
    return tags.filter(
      (tag) => messageBoard && messageBoard.tagIds.includes(tag.id),
    )
  }, [members, messageBoard && messageBoard.tagIds])

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

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

  useEffect(() => {
    console.log("=================currentRoomUISettings===================")
    console.log(currentRoomUISettings)
    console.log("=================end currentRoomUISettings===================")
    AppStore.for(CurrentRoomUISettingsModel).add({
      ...currentRoomUISettings,
      boardFilter: {
        keyword: boardFiltered.keyword,
        userIds: boardFiltered.userIds,
        tagIds: boardFiltered.tagIds,
        date: boardFiltered.date.value || null,
      },
    })
  }, [boardFiltered, roomId])

  useEffect(() => {
    setBoardFiltered((prev) => ({
      ...prev,
      date: {
        ...prev.date,
        ...{ id: 5, name: "Next date", value: fromDateCustom },
      },
    }))
  }, [fromDateCustom, toDateCustom])

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

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

    let localMessages = localMessageBundles.map(
      (localMessage) => localMessage.message,
    )
    let tempBoard = localMessages.map((message) => {
      return {
        useIds: message.board ? message.board.attachedUserIds : [],
        tagIds: message.board ? message.board.tagIds : [],
      }
    })

    let userIds = tempBoard.map((it) => it.useIds).flat()
    let tagIds = tempBoard.map((it) => it.tagIds).flat()

    setMessageBoard({ tagIds, userIds })
  }

  const handleDateChange = async (date: Date, selected: string) => {
    if (selected === "from") {
      setFromDateCustom(date)
    } else if (selected === "to") {
      setToDateCustom(date)
    }
    setBoardFiltered((prev) => ({
      ...prev,
      date: {
        ...prev.date,
        ...{ id: 5, name: "Custom date", value: date },
      },
    }))
    setReset((prev) => ({ ...prev, isDate: false }))
  }

  function handleCheckDate() {
    setReset((prev) => ({ ...prev, isDate: !reset.isDate }))
    setBoardFiltered((prev) => ({
      ...prev,
      date: { id: 0, name: "", value: null },
    }))
  }

  function handleCheckCustomDate(item: {
    id: number
    name: string
    value: Date
  }) {
    if (boardFiltered.date.id === item.id) {
      setBoardFiltered((prev) => ({
        ...prev,
        date: { id: 0, name: "", value: null },
      }))
    } else {
      setBoardFiltered((prev) => ({
        ...prev,
        date: { ...prev.date, ...item },
      }))
      setReset((prev) => ({ ...prev, isDate: false }))
    }
  }

  // ---------------------------------------------------------------------------
  return (
    <SafeAreaView style={{ flexShrink: 1 }}>
      <ScrollView contentContainerStyle={styles.container}>
        {/* --------------------------------------------------------------------------- */}
        {/* TITLE */}
        {/* --------------------------------------------------------------------------- */}

        <StyledText style={styles.title}>Keyword</StyledText>

        <View>
          <Input
            testID="searchKeywordInput"
            type="search"
            placeholder="Search"
            wrapperStyle={{ backgroundColor: AppColors.backgroundLight }}
            onChangeText={(value) =>
              setBoardFiltered((prev) => ({ ...prev, keyword: value }))
            }
          />
        </View>

        {/* --------------------------------------------------------------------------- */}
        {/* MEMBERS */}
        {/* --------------------------------------------------------------------------- */}

        <View style={styles.members}>
          <View style={styles.memberTitleContainer}>
            <StyledText style={styles.membersTitle}>Members</StyledText>
            <TouchableOpacity
              testID="membersRepeat"
              activeOpacity={0.5}
              onPress={() => {
                setBoardFiltered((prev) => ({ ...prev, userIds: [] }))
                setReset((prev) => ({ ...prev, isUser: false }))
              }}
              style={styles.repeatIconBox}
            >
              <StyledText style={styles.reset}>Reset</StyledText>
            </TouchableOpacity>
          </View>
          <View style={styles.memberList}>
            <Pressable
              onPress={() => {
                setReset((prev) => ({ ...prev, isUser: !reset.isUser }))
                setBoardFiltered((prev) => ({ ...prev, userIds: [] }))
              }}
              style={styles.withoutMemberBox}
            >
              <Checkbox
                size={18}
                checked={reset.isUser}
                onClick={() => {
                  setReset((prev) => ({ ...prev, isUser: !reset.isUser }))
                  setBoardFiltered((prev) => ({ ...prev, userIds: [] }))
                }}
              />
              <StyledText style={styles.withoutMember}>
                Without members
              </StyledText>
            </Pressable>
            <View style={styles.memberList}>
              {attachmentMembers.map((attachedMember) => (
                <View key={attachedMember.id} style={styles.memberlistItem}>
                  <Pressable
                    style={styles.memberNameWrapper}
                    onPress={() => {
                      if (
                        boardFiltered.userIds.some(
                          (userId) => attachedMember.id.indexOf(userId) !== -1,
                        )
                      ) {
                        setBoardFiltered((prev) => ({
                          ...prev,
                          userIds: prev.userIds.filter(
                            (userId) => attachedMember.id !== userId,
                          ),
                        }))
                      } else {
                        setBoardFiltered((prev) => ({
                          ...prev,
                          userIds: [...prev.userIds, attachedMember.id],
                        }))
                        setReset((prev) => ({ ...prev, isUser: false }))
                      }
                    }}
                  >
                    <View style={{ marginRight: 5 }}>
                      <Checkbox
                        size={18}
                        checked={boardFiltered.userIds.some(
                          (userId) => attachedMember.id.indexOf(userId) !== -1,
                        )}
                        onClick={() => {}}
                      />
                    </View>
                    <UserPhoto
                      user={{
                        ...attachedMember,
                        status: {
                          status: UserStatusKind.online,
                          text: null,
                          emoji: null,
                        },
                      }}
                      size={25}
                    />
                    <StyledText style={styles.memberName}>
                      {attachedMember.name}
                    </StyledText>
                  </Pressable>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* --------------------------------------------------------------------------- */}
        {/* DUE DATE */}
        {/* --------------------------------------------------------------------------- */}

        <View>
          <View style={styles.memberTitleContainer}>
            <StyledText style={styles.membersTitle}>Due date</StyledText>
            <TouchableOpacity
              activeOpacity={0.5}
              onPress={() => {
                setBoardFiltered((prev) => ({
                  ...prev,
                  date: { id: 0, name: "", value: null },
                }))
                setReset((prev) => ({ ...prev, isDate: false }))
              }}
              style={styles.repeatIconBox}
            >
              <StyledText style={styles.reset}>Reset</StyledText>
            </TouchableOpacity>
          </View>
          <View style={styles.dueDatsBox}>
            <Pressable
              pointerEvents="box-only"
              onPress={handleCheckDate}
              style={styles.dueDateItem}
            >
              <Radio checked={reset.isDate} />
              <StyledText style={styles.dueDateItemText}>
                Without date
              </StyledText>
            </Pressable>
            {dueDates.map((item) => (
              <Pressable
                pointerEvents="box-only"
                key={item.id}
                style={styles.dueDateItem}
                onPress={(checked) => {
                  if (checked) {
                    setBoardFiltered((prev) => ({
                      ...prev,
                      date: { ...prev.date, ...item },
                    }))
                    setReset((prev) => ({ ...prev, isDate: false }))
                  } else {
                    setBoardFiltered((prev) => ({
                      ...prev,
                      date: { id: 0, name: "", value: null },
                    }))
                  }
                }}
              >
                <Radio
                  testID={`${item.name}`}
                  key={item.id}
                  checked={boardFiltered.date.id === item.id}
                  onClick={(checked) => {
                    if (checked) {
                      setBoardFiltered((prev) => ({
                        ...prev,
                        date: { ...prev.date, ...item },
                      }))
                      setReset((prev) => ({ ...prev, isDate: false }))
                    } else {
                      setBoardFiltered((prev) => ({
                        ...prev,
                        date: { id: 0, name: "", value: null },
                      }))
                    }
                  }}
                />
                <StyledText style={styles.dueDateItemText}>
                  {item.name}
                </StyledText>
              </Pressable>
            ))}

            {boardFiltered.date.id === 5 && (
              <View>
                <View style={styles.calenderWrap}>
                  <Pressable
                    onPress={() => {
                      modal.open({
                        component: (
                          <CustomCalendar
                            handleDateChange={(date) => {
                              handleDateChange(date, "from")
                            }}
                          />
                        ),
                        handleStyle: { display: "none" },
                      })
                    }}
                    style={styles.fromDateWrap}
                  >
                    <StyledText
                      style={[
                        styles.fromDate,
                        {
                          color: fromDateCustom
                            ? AppColors.headerText
                            : AppColors.placeholderText,
                        },
                      ]}
                    >
                      {fromDateCustom
                        ? DateUtils.dayMonthYear(fromDateCustom)
                        : "DD.MM.YYYY"}
                    </StyledText>
                  </Pressable>
                  <View style={styles.fromDateIcon}>
                    <Pressable
                      onPress={() => {
                        setFromDateCustom(undefined)
                      }}
                    >
                      <SvgXml
                        xml={XIcon(
                          fromDateCustom ? "#000" : AppColors.placeholderText,
                        )}
                      />
                    </Pressable>
                  </View>
                </View>
                <View style={styles.toDateWrap}>
                  <Pressable
                    onPress={() => {
                      modal.open({
                        component: (
                          <CustomCalendar
                            handleDateChange={(date) =>
                              handleDateChange(date, "to")
                            }
                          />
                        ),
                        handleStyle: { display: "none" },
                      })
                    }}
                    style={styles.toDate}
                  >
                    <StyledText
                      style={{
                        color: toDateCustom
                          ? "#000"
                          : AppColors.placeholderText,
                        fontSize: 16,
                        fontStyle: "normal",
                      }}
                    >
                      {toDateCustom
                        ? DateUtils.dayMonthYear(toDateCustom)
                        : "DD.MM.YYYY"}
                    </StyledText>
                  </Pressable>
                  <View style={styles.fromDateIcon}>
                    <Pressable
                      onPress={() => {
                        setToDateCustom(undefined)
                      }}
                    >
                      <SvgXml
                        xml={XIcon(
                          toDateCustom ? "#000" : AppColors.placeholderText,
                        )}
                      />
                    </Pressable>
                  </View>
                </View>
              </View>
            )}
          </View>
        </View>

        {/* --------------------------------------------------------------------------- */}
        {/* TAGS */}
        {/* --------------------------------------------------------------------------- */}

        <View style={styles.tagBox}>
          <View style={styles.memberTitleContainer}>
            <StyledText style={styles.membersTitle}>Tags</StyledText>
            <TouchableOpacity
              onPress={() => {
                setBoardFiltered((prev) => ({ ...prev, tagIds: [] }))
                setReset((prev) => ({ ...prev, isTag: false }))
              }}
              style={styles.repeatIconBox}
            >
              <StyledText style={styles.reset}>Reset</StyledText>
            </TouchableOpacity>
          </View>
          <View>
            <Pressable
              pointerEvents="box-only"
              onPress={() => {
                setReset((prev) => ({ ...prev, isTag: !reset.isTag }))
                setBoardFiltered((prev) => ({ ...prev, tagIds: [] }))
              }}
              style={styles.withoutTagsBox}
            >
              <Checkbox size={18} checked={reset.isTag} onClick={() => {}} />
              <StyledText style={styles.dueDateItemText}>
                Without tags
              </StyledText>
            </Pressable>

            {attachmentTags.map((attachmentTag) => (
              <Pressable
                pointerEvents="box-only"
                style={styles.tagName}
                key={attachmentTag.id}
                onPress={() => {
                  if (boardFiltered.tagIds.includes(attachmentTag.id)) {
                    setBoardFiltered((prev) => ({
                      ...prev,
                      tagIds: [
                        ...prev.tagIds.filter(
                          (tagId) => attachmentTag.id !== tagId,
                        ),
                      ],
                    }))
                  } else {
                    setBoardFiltered((prev) => ({
                      ...prev,
                      tagIds: [...prev.tagIds, attachmentTag.id],
                    }))
                    setReset((prev) => ({ ...prev, isTag: false }))
                  }
                }}
              >
                <Checkbox
                  size={18}
                  key={attachmentTag.id}
                  checked={boardFiltered.tagIds.includes(attachmentTag.id)}
                  onClick={() => {}}
                />

                <View
                  style={[
                    styles.tagNameWrap,
                    { backgroundColor: attachmentTag.color ?? "silver" },
                  ]}
                >
                  <StyledText
                    style={[
                      styles.attachmentTagName,
                      {
                        color: attachmentTag.color ? AppColors.light : "#000",
                      },
                    ]}
                  >
                    {attachmentTag.name}
                  </StyledText>
                </View>
              </Pressable>
            ))}
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  )
}
when I select tag then I check currentRoomUISettings it shows  {"boardFilter": {"date": null, "keyword": "", "tagIds": [], "userIds": []}, "editMessage": undefined, "id": "{\"kind\":\"board\",\"communityId\":\"ec601356-37e1-47e7-b2ff-2467d59f9fc2\",\"channelId\":\"9d2213e1-9ab3-4f9a-983e-eb0cacaa0cc5\"}", "issueFilter": undefined, "messageInputHeight": 0, "quotedMessage": undefined} tagIds is empty array but  boardFiltered  {"date": {"id": 5, "name": "Next date", "value": undefined}, "keyword": "", "tagIds": ["eb8c1e25-8489-4d06-9274-0613455e84e6"], "userIds": []} tagIds rendered selected tag. How to fix it ?