import {

  Image,

  ScrollView,

  View,

  SafeAreaView,

  useWindowDimensions,

  Text,

  Pressable,

} from "react-native"

import { StyledText } from "../../../ui-components/styled-text/styled-text"

import React, { useEffect, useState } from "react"



import { Header } from "../../../ui-components/header/header.component"

import { Input } from "../../../ui-components/input/input"

import {

  useBansByCommunity,

  useMembersByCommunity,

  useRolesByCommunity,

} from "@openchat/ui"

import { MemberType, RoleType } from "@openchat/types"

import { Mutator } from "@openchat/core"

import { CommunitySettingsMembersItem } from "./community-settings-members-item/community-settings-members-item.component"

import { useNavigationRouteParams } from "../../../navigation/navigation.hooks"

import { AppConfig } from "../../../app/app.config"

import { TEXT } from "emojibase"

import { MenuOpener } from "../../../ui-components/menu/menu-opener.provider"

import { Icon } from "../../../ui-components/icon/icon.component"

import { Button } from "../../../ui-components/button/button.component"

import { MenuButton } from "../../../ui-components/menu-item/menu-button.component"

import { useModal } from "../../../ui-components/modal/modal.hook"

import { Checkbox } from "../../../ui-components/checkbox/checkbox.component"

import { useStyles } from "./community-settings-members.style"

import { CommunitySettingsRoleFilter } from "./community-settings-members-item/community-settings-role-filter.component"

import { MenuItem } from "../../../ui-components/menu"

import { AppAssets } from "../../../app/app.assets"

import { EmptyState } from "../../../ui-components/empty-state/empty-state.component"



export const CommunitySettingsMember = () => {

  // ---------------------------------------------------------------------------

  // variables

  // ---------------------------------------------------------------------------

  const { community, hasPermissionsForCommunities } = useNavigationRouteParams(

    "CommunitySettingsMember",

  )

  const styles = useStyles()

  const members = useMembersByCommunity(community.id)

  const [keyword, setKeyword] = useState("")

  const [roleIds, setRoleIds] = useState<string[]>([])

  const roles = useRolesByCommunity(community.id)

  const bans = useBansByCommunity(community.id)

  const [filteredMembers, setFilteredMembers] = useState<MemberType[]>([])

  const modal = useModal()



  const { width, height } = useWindowDimensions()



  // ---------------------------------------------------------------------------

  // effects

  // ---------------------------------------------------------------------------



  useEffect(() => {

    filterMembers()

  }, [members, roleIds, keyword, community])



  // ---------------------------------------------------------------------------

  // functions

  // ---------------------------------------------------------------------------



  function filterMembers() {

    let filteredMembers = members



    if (roleIds.length) {

      filteredMembers = filteredMembers.filter((member) =>

        roles.some(

          (role) =>

            role.identityIds.includes(member.identityId) &&

            roleIds.includes(role.id),

        ),

      )

    }



    if (keyword) {

      filteredMembers = filteredMembers.filter(

        (member) =>

          member.name &&

          member.name.toLowerCase().indexOf(keyword.toLowerCase()) !== -1,

      )

    }



    setFilteredMembers(filteredMembers)

  }



  function updateMember(member: MemberType) {

    const memberToUpdate = filteredMembers.find(

      (filteredMember) => filteredMember.id === member.id,

    )

    if (!memberToUpdate) return



    const updatedMembers = Mutator.replace(

      filteredMembers,

      member,

      memberToUpdate,

    )

    setFilteredMembers(updatedMembers)

  }



  function filterHandler() {

    console.log("=================roleIds===================")

    console.log(roleIds)

    console.log("====================================")

    modal.open({

      background: "pattern",

      scrollEnabled: false,

      footer: "rgb",

      component: (

        <CommunitySettingsRoleFilter

          roles={roles}

          selectedRoles={roleIds}

          onPress={(roleIds: string[]) => setRoleIds(roleIds)}

        />

      ),

    })

  }



  // ---------------------------------------------------------------------------

  return (

    <View style={styles.container}>

      <Header

        backIcon={true}

        heading="Members"

        animate

        childrenOrList={

          <MenuOpener

            position="bottom-left"

            style={{ marginTop: -10 }}

            content={

              <MenuItem onPress={filterHandler}>

                <View style={styles.iconRow}>

                  <Icon name="fa-light fa-poll-people" size={16} />

                  <StyledText

                    style={{

                      width: "auto",

                      fontSize: 18,

                      fontWeight: "400",

                      color: "black",

                    }}

                  >

                    Filter by role

                  </StyledText>

                </View>

              </MenuItem>

            }

          >

            <Icon name="fa-regular fa-bars-filter" size={18} fill={"#8592AA"} />

          </MenuOpener>

        }

      />



      <SafeAreaView style={styles.filter}>

        <ScrollView

          showsVerticalScrollIndicator={false}

          contentContainerStyle={styles.list}

        >

          <View

            style={{

              marginTop: members.length > 0 ? 20 : height <= 600 ? 50 : null,

              flex: 1,

            }}

          >

            <View style={styles.searchBox}>

              <Input

                testID="searchMembersInput"

                placeholder="Search"

                type={keyword ? "clear" : "search"}

                onChangeText={(text) => setKeyword(text.trim())}

                onIconPress={() => setKeyword("")}

                value={keyword}

                mode="secondary"

              />

            </View>



            <View style={{ marginTop: 15 }}>

              {filteredMembers.length > 0 &&

                filteredMembers.map((member, index) => (

                  <CommunitySettingsMembersItem

                    testID={`member.${index}`}

                    key={member.id}

                    member={member}

                    bans={bans}

                    community={community}

                    updateMember={(member: MemberType) => updateMember(member)}

                    keyword={keyword}

                    hasPermissionsForCommunities={hasPermissionsForCommunities}

                    index={index}

                  />

                ))}



              {filteredMembers.length <= 0 && (

                <View style={styles.notChannel}>

                  <EmptyState

                    title="No members yet..."

                    description="Invite peoples to your community"

                    image={AppAssets.images.chatPhoto}

                  />

                </View>

              )}

            </View>

          </View>

        </ScrollView>

      </SafeAreaView>

    </View>

  )

}

import { useState, useEffect } from "react"

import { View, Pressable, ScrollView } from "react-native"

import { StyledText } from "../../../../ui-components/styled-text/styled-text"

import { Checkbox } from "../../../../ui-components/checkbox/checkbox.component"

import { useStyles } from "../community-settings-members.style"

import { RoleType } from "@openchat/types"

import { Input } from "../../../../ui-components/input/input"

import { StickyFooter } from "../../../../ui-components/sticky-footer/sticky-footer.component"

import { Button } from "../../../../ui-components/button/button.component"

import { useModal } from "../../../../ui-components/modal/modal.hook"

import { Mutator } from "@openchat/core"



export const CommunitySettingsRoleFilter = ({

  roles,

  selectedRoles,

  onPress,

}: {

  roles: RoleType[]

  selectedRoles: string[]

  onPress: (roleIds: string[]) => void

}) => {

  // ---------------------------------------------------------------------------

  // variables

  // ---------------------------------------------------------------------------

  const styles = useStyles()

  const [checkedRoles, setCheckedRoles] = useState<string[]>(selectedRoles)

  const [keyword, setKeyword] = useState("")

  const [filteredRoles, setFilteredRoles] = useState<RoleType[]>(roles)

  const modal = useModal()



  console.log("=================selectedRoles===================")

  console.log(selectedRoles)

  console.log("====================================")



  // ---------------------------------------------------------------------------

  // useEffect

  // ---------------------------------------------------------------------------



  useEffect(() => {

    onChangeKeyword()

  }, [keyword])



  // ---------------------------------------------------------------------------

  // functions

  // ---------------------------------------------------------------------------



  function onChangeKeyword() {

    let filteredRoles = roles

    if (keyword !== "") {

      filteredRoles = filteredRoles.filter(

        (role) =>

          role.name!.toLowerCase().indexOf(keyword.toLowerCase()) !== -1,

      )

    }

    setFilteredRoles(filteredRoles)

  }



  function toggleRole(roleIds: string) {

    const isRoleSelected = checkedRoles.includes(roleIds)

    if (isRoleSelected) {

      setCheckedRoles((prev) => Mutator.remove(prev, roleIds))

    } else {

      setCheckedRoles((prev) => [...prev, roleIds])

    }

  }



  return (

    <View style={styles.modal}>

      <StyledText style={styles.titleFilterRoles}>Filter By Role</StyledText>

      {roles.length > 0 ? (

        <ScrollView

          showsVerticalScrollIndicator={false}

          contentContainerStyle={{ flexGrow: 1 }}

        >

          <View style={styles.input}>

            <Input

              placeholder="Search roles"

              type={keyword ? "clear" : "search"}

              onChangeText={setKeyword}

              onIconPress={() => setKeyword("")}

              mode="secondary"

              value={keyword}

            />

          </View>

          <View style={{}}>

            {filteredRoles.map((role) => (

              <>

                <Pressable

                  key={role.id}

                  style={({ pressed }) => [

                    styles.filterRoleItem,

                    {

                      backgroundColor: pressed ? "#EEF2F6" : "white",

                    },

                  ]}

                  onPress={() => toggleRole(role.id)}

                >

                  <View style={styles.filterNameAndColor}>

                    <View

                      style={[

                        styles.filterRoleColor,

                        { backgroundColor: role.color },

                      ]}

                    />

                    <StyledText

                      ellipsizeMode="tail"

                      numberOfLines={1}

                      style={styles.roleName}

                    >

                      {role.name}

                    </StyledText>

                  </View>

                  <Checkbox

                    size={18}

                    checked={checkedRoles.includes(role.id)}

                    onClick={() => toggleRole(role.id)}

                  />

                </Pressable>

              </>

            ))}

          </View>

        </ScrollView>

      ) : (

        <View style={styles.notContent}>

          <StyledText style={styles.title}>No roles yet...</StyledText>

          <StyledText style={styles.description}>

            Invite peoples to your community

          </StyledText>

        </View>

      )}

      <StickyFooter size="small" withLine={true} noBackground={true}>

        <View style={styles.buttons}>

          <Button type="simple" onPress={() => modal.close()}>

            Cancel

          </Button>

          <Button

            type="primary"

            disabled={checkedRoles.length ? false : true}

            onPress={() => {

              onPress(checkedRoles), modal.close()

            }}

          >

            Save

          </Button>

        </View>

      </StickyFooter>

    </View>

  )

}

the issue here  selectedRoles={roleIds}. Why roleIds come empty when I check roleIds outside of  filterHandler not empty. Why comming empty array ?