import {
  CurrentRoomUISettingsModel,
  memoComponent,
  useCurrentRoomUISettings,
  useMembersBy,
  useRoomMetadata,
  useTagsBy,
} from "@openchat/ui"
import { RoomType, UserStatusKind } from "@openchat/types"
import { DateUtils } from "@openchat/core"
import { useEffect, useMemo, useState } from "react"
import { AppController, AppStore } from "../../../app/app.globals.js"
import { Checkbox } from "../../../ui-component/checkbox/checkbox.component"
import { DayPickerComponent } from "../../../ui-component/day-picker/day-picker.component.js"
import { Icon } from "../../../ui-component/icon/icon.component"
import { Input } from "../../../ui-component/input/input.component"
import { PopupOpener } from "../../../ui-component/popup/popup-opener.provider"
import { usePopupOpener } from "../../../ui-component/popup/popup.hook"
import { UserPhoto } from "../../user/user-photo/user-photo.component"
import { Header } from "../../../ui-component/header/header.component.js"
import styles from "./message-board-right-panel.styles.module.css"
import { RoomUtils } from "@openchat/models"

export const MessageBoardRightPanel = memoComponent(
  "MessageBoardRightPanel",
  ({ room }: { room: RoomType }) => {
    // ---------------------------------------------------------------------------
    // variables
    // ---------------------------------------------------------------------------

    const popup = usePopupOpener()
    const currentRoomUISettings = useCurrentRoomUISettings(room.id)
    const { communityId } = RoomUtils.extractIds(room.id)
    const { community, channel, group, user } = useRoomMetadata(room.id)
    const members = useMembersBy({ communityId: communityId })
    const tags = useTagsBy({ communityId: communityId })

    const [messageBoard, setMessageBoard] = useState<{
      userIds: string[]
      tagIds: string[]
    }>()

    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 dueDates = [
      {
        id: 1,
        name: "Today",
        value: new Date(),
      },
      {
        id: 2,
        name: "Tomorrow",
        value: new Date(new Date()),
      },
      {
        id: 3,
        name: "Nex week",
        value: new Date(
          new Date().getFullYear(),
          new Date().getMonth(),
          new Date().getDate() + 7,
        ),
      },
    ]

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

    const attachmentMembers = useMemo(() => {
      return members.filter(
        (member) => messageBoard && messageBoard.userIds.includes(member.id),
      )
    }, [members, messageBoard && messageBoard.userIds])

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

    console.log("================messageBoard.userIds====================")
    console.log(messageBoard?.userIds)
    console.log("====================================")
    console.log("================members====================")
    console.log(members)
    console.log("====================================")

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

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

    useEffect(() => {
      AppStore.for(CurrentRoomUISettingsModel).add({
        ...currentRoomUISettings,
        filterBoard: {
          keyword: boardFiltered.keyword,
          userIds: boardFiltered.userIds,
          tagIds: boardFiltered.tagIds,
          date: boardFiltered.date.value || null,
        },
      })
      return () => {}
    }, [boardFiltered, room])

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

    async function loadMessages() {
      const localMessageBundles = await AppController.message.getFromLocal({
        roomId: room.id,
        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 })
    }

    // ---------------------------------------------------------------------------
    if (!community) return <></>
    return (
      <div className={styles.wrapper}>
        <div className={styles.container}>
          <div className={styles.keywordContainer}>
            <Header
              className={styles.header}
              titleStyle={{ textTransform: "uppercase", fontSize: "1.8rem" }}
              title="Keyword"
            />

            <Input
              style={{ marginLeft: "-3px" }}
              placeholder="Search"
              mode="secondary"
              icon="fal fa-search"
              value={boardFiltered.keyword}
              onValueChange={(value) =>
                setBoardFiltered((prev) => ({ ...prev, keyword: value }))
              }
            />
          </div>
          {/* --------------------------------------------------------------------------- */}
          {/* FILTER BY MEMBERS */}
          {/* --------------------------------------------------------------------------- */}
          <div>
            <Header
              className={styles.header}
              titleStyle={{ textTransform: "uppercase", fontSize: "1.8rem" }}
              title="Members"
              link={
                <div
                  className={styles.revert}
                  onClick={() => {
                    setBoardFiltered((prev) => ({ ...prev, userIds: [] }))
                    setReset((prev) => ({ ...prev, isUser: false }))
                  }}
                >
                  <Icon name="fa-light fa-arrows-retweet" />
                </div>
              }
            />

            <div
              className={styles.listContainer}
              style={{
                maxHeight: showMore.isUser ? "40rem" : "20rem",
                overflow: showMore.isTag ? "scroll" : "",
              }}
            >
              <Checkbox
                style={{ marginTop: 0 }}
                label="Without members"
                checked={reset.isUser}
                onClick={() => {
                  setReset((prev) => ({ ...prev, isUser: !reset.isUser }))
                  setBoardFiltered((prev) => ({ ...prev, userIds: [] }))
                }}
              />
              {attachmentMembers.map((attachmentMember) => (
                <Checkbox
                  className={styles.listItem}
                  key={attachmentMember.id}
                  checked={boardFiltered.userIds.some(
                    (userId) => attachmentMember.id.indexOf(userId) !== -1,
                  )}
                  onClick={(checked) => {
                    if (checked) {
                      setBoardFiltered((prev) => ({
                        ...prev,
                        userIds: [...prev.userIds, attachmentMember.id],
                      }))
                      setReset((prev) => ({ ...prev, isUser: false }))
                    } else {
                      setBoardFiltered((prev) => ({
                        ...prev,
                        userIds: prev.userIds.filter(
                          (userId) => attachmentMember.id !== userId,
                        ),
                      }))
                    }
                  }}
                >
                  <UserPhoto
                    className={styles.membersPhoto}
                    user={{
                      ...attachmentMember,
                      status: {
                        status: UserStatusKind.online,
                        text: null,
                        emoji: null,
                      },
                    }}
                    size={"2.5"}
                  />
                  <span className={styles.memberName}>
                    {attachmentMember.name}
                  </span>
                </Checkbox>
              ))}
            </div>

            {attachmentMembers.length > 6 && (
              <p
                className={styles.subTitle}
                style={{ paddingTop: "0" }}
                onClick={() => {
                  setShowMore((prev) => ({ ...prev, isUser: !prev.isUser }))
                }}
              >
                {!showMore.isUser ? "Show more" : "Hide"}
              </p>
            )}
          </div>
          {/* --------------------------------------------------------------------------- */}
          {/* FILTER BY DATE */}
          {/* --------------------------------------------------------------------------- */}

          <div className={styles.dateContainer}>
            <Header
              className={styles.header}
              titleStyle={{ textTransform: "uppercase", fontSize: "1.8rem" }}
              title="Due Date"
              link={
                <div
                  className={styles.revert}
                  onClick={() => {
                    setBoardFiltered((prev) => ({
                      ...prev,
                      date: { id: 0, name: "", value: null },
                    }))
                    setReset((prev) => ({ ...prev, isDate: false }))
                  }}
                >
                  <Icon name="fa-light fa-arrows-retweet" />
                </div>
              }
            />

            <div className={styles.listContainer}>
              <Checkbox
                style={{ marginTop: 0 }}
                mode="radio-button"
                checked={reset.isDate}
                label="Without date"
                onClick={() => {
                  setReset((prev) => ({ ...prev, isDate: !reset.isDate }))
                  setBoardFiltered((prev) => ({
                    ...prev,
                    date: { id: 0, name: "", value: null },
                  }))
                }}
              />
              {dueDates.map((item) => (
                <Checkbox
                  mode="radio-button"
                  key={item.id}
                  className={styles.listItem}
                  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 },
                      }))
                    }
                  }}
                >
                  <span className={styles.dateText}>{item.name}</span>
                </Checkbox>
              ))}

              {boardFiltered.date.id === 4 && (
                <div className={styles.getAttachDateWrap}>
                  <PopupOpener
                    mode="click"
                    placement="auto"
                    content={
                      <DayPickerComponent
                        value={
                          boardFiltered.date.value
                            ? boardFiltered.date.value
                            : undefined
                        }
                        onChange={(value) => {
                          setBoardFiltered((prev) => ({
                            ...prev,
                            date: {
                              ...prev.date,
                              ...{ id: 4, name: "Next date", value },
                            },
                          }))
                          setReset((prev) => ({ ...prev, isDate: false }))
                          popup.close()
                        }}
                      />
                    }
                  >
                    <p>
                      {DateUtils.getDateTime(
                        boardFiltered.date.value
                          ? boardFiltered.date.value
                          : new Date(),
                      )}
                    </p>
                  </PopupOpener>
                </div>
              )}

              {boardFiltered.date.id !== 4 && (
                <PopupOpener
                  mode="click"
                  placement="auto"
                  content={
                    <DayPickerComponent
                      value={
                        boardFiltered.date.value
                          ? boardFiltered.date.value
                          : undefined
                      }
                      onChange={(value) => {
                        setBoardFiltered((prev) => ({
                          ...prev,
                          date: {
                            ...prev.date,
                            ...{ id: 4, name: "Next date", value },
                          },
                        }))
                        setReset((prev) => ({ ...prev, isDate: false }))
                        popup.close()
                      }}
                    />
                  }
                >
                  <div className={styles.setBtnWrapp}>
                    <Icon name="fal fa-calendar" size="medium" />
                    <span className={styles.dateText}>Set date</span>
                  </div>
                </PopupOpener>
              )}
            </div>
          </div>

          {/* --------------------------------------------------------------------------- */}
          {/* FILTER BY TAGS */}
          {/* --------------------------------------------------------------------------- */}

          <div className={styles.tagsContainer}>
            <Header
              className={styles.header}
              titleStyle={{ textTransform: "uppercase", fontSize: "1.8rem" }}
              title="Tags"
              link={
                <div
                  className={styles.revert}
                  onClick={() => {
                    setBoardFiltered((prev) => ({ ...prev, tagIds: [] }))
                    setReset((prev) => ({ ...prev, isTag: false }))
                  }}
                >
                  <Icon name="fa-light fa-arrows-retweet" />
                </div>
              }
            />
            <div
              className={styles.listContainer}
              style={{
                maxHeight: showMore.isTag ? "60rem" : "20rem",
                overflow: showMore.isTag ? "scroll" : "",
              }}
            >
              <Checkbox
                style={{ marginTop: 0 }}
                label="Without tags"
                checked={reset.isTag}
                onClick={() => {
                  setReset((prev) => ({ ...prev, isTag: !reset.isTag }))
                  setBoardFiltered((prev) => ({ ...prev, tagIds: [] }))
                }}
              />

              {attachmentTags.map((attachmentTag) => (
                <Checkbox
                  key={attachmentTag.id}
                  className={styles.listItem}
                  checked={boardFiltered.tagIds.includes(attachmentTag.id)}
                  onClick={(checked) => {
                    if (checked) {
                      setBoardFiltered((prev) => ({
                        ...prev,
                        tagIds: [...prev.tagIds, attachmentTag.id],
                      }))
                      setReset((prev) => ({ ...prev, isTag: false }))
                    } else {
                      setBoardFiltered((prev) => ({
                        ...prev,
                        tagIds: [
                          ...prev.tagIds.filter(
                            (tagId) => attachmentTag.id !== tagId,
                          ),
                        ],
                      }))
                    }
                  }}
                >
                  <div
                    key={attachmentTag.id}
                    className={styles.tags}
                    style={{
                      background: attachmentTag.color ?? "",
                      color: attachmentTag.color ? "white" : "black",
                    }}
                  >
                    {attachmentTag.name}
                  </div>
                </Checkbox>
              ))}
            </div>

            {attachmentTags.length > 6 && (
              <p
                className={styles.subTitle}
                style={{ paddingTop: !showMore.isTag ? "" : "0" }}
                onClick={() => {
                  setShowMore((prev) => ({ ...prev, isTag: !prev.isTag }))
                }}
              >
                {!showMore.isTag ? "Show more" : "Hide"}
              </p>
            )}
          </div>
        </div>
      </div>
    )
  },
)
when I press on checkbox of Without tags, it should shows the cards  that not have tags. But currently not working. How to fix it ?