import { PermissionKindEnum } from "@openchat/types"
import {
  useAccountCommunityBy,
  useAccountId,
  useBanBy,
  useChannelCategoriesBy,
  useChannelsBy,
  useChannelsFilter,
  useCommunity,
  useDeviceSettings,
  useJoinRequestsBy,
  useJoinRequestsFilter,
  useMemberBy,
  useMembersBy,
  useMembersFilter,
} from "@openchat/ui"
import React, { useEffect, useState } from "react"
import {
  Image,
  ScrollView,
  TouchableOpacity,
  useWindowDimensions,
  View,
} from "react-native"
import { AppAssets } from "../../../../app/app.assets"
import { AppController } from "../../../../app/app.globals"
import { NavigationRef } from "../../../../navigation/navigation.hooks"
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 { StyledText } from "../../../../ui-components/styled-text/styled-text"
import { CommunityMenu } from "../../../community/community-menu/community-menu.component"
import { useStyles } from "./dashboard-community.style"
import { Spinner } from "../../../../ui-components/spinner/spinner.component"
import { DashboardCommunityLargeStatusPanel } from "../dashboard-community-large-status-panel/dashboard-community-large-status-panel.component"
import { ObjectUtils } from "@openchat/core"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import { ChannelCategoryUtils } from "@openchat/models"
import { Input } from "../../../../ui-components/input/input"
import { EmptyState } from "../../../../ui-components/empty-state/empty-state.component"
import { EmptyStateLink } from "../../../../ui-components/empty-state/empty-state-link.component"
import { DashboardCommunityChannelItem } from "../dashboard-community-channel-item/dashboard-community-channel-item.component"
import { CommunityGuard } from "../../../guards/community-guard.component"
import { JoinMemberItem } from "../../../member/join-member-item/join-member-item.component"
import { MemberItem } from "../../../member/member-item/member-item.component"
import { DashboardCommunitySmallStatusPanel } from "../dashboard-community-small-status-panel/dashboard-community-small-status-panel.component"
import { ConfirmationModalize } from "../../../../ui-components/confirmation-modalize/confirmation-modalize.component"
import { useModal } from "../../../../ui-components/modal/modal.hook"

// @reviewed
export function DashboardCommunity({ communityId }: { communityId: string }) {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------

  const { styles } = useStyles()
  const dimensions = useWindowDimensions()
  const safeAreaInsets = useSafeAreaInsets()
  const accountId = useAccountId()
  const deviceSettings = useDeviceSettings()

  const modal = useModal()
  const community = useCommunity(communityId)
  const accountCommunity = useAccountCommunityBy({ communityId })
  const communityJoinRequests = useJoinRequestsBy({ communityId })
  const channels = useChannelsBy({ communityId })
  const channelCategories = useChannelCategoriesBy({ communityId })
  const members = useMembersBy({ communityId })
  const isMember = members.some((member) => member.identityId === accountId)
  const currentUserBan = useBanBy({
    communityId: communityId,
    identityId: accountId,
  })

  const [isLoading, setLoading] = useState(false)
  const [keyword, setKeyword] = useState("")

  const filteredMembers = useMembersFilter(members, {
    keyword,
    sortCurrentMemberFirst: true,
  })

  const filteredCommunityJoinRequests = useJoinRequestsFilter(
    communityJoinRequests,
    {
      keyword,
    },
  )
  const filteredChannels = useChannelsFilter(channels, {
    keyword,
    isArchived: false,
    sortByOrder: true,
  })
  const archivedChannels = useChannelsFilter(channels, {
    keyword,
    isArchived: true,
    sortByOrder: true,
  })
  const uncategorizedChannels = useChannelsFilter(channels, {
    keyword,
    isArchived: false,
    isUncategorized: true,
    sortByOrder: true,
  })

  const isArchivedChannelsShowed =
    deviceSettings.showArchivedInCommunities[communityId] === true

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

  useEffect(() => {
    async function importCommunity() {
      if (!accountCommunity || !communityId) return
      if (accountCommunity.isDeleted === true) return
      if (community) return

      setLoading(true)
      await AppController.community.import(accountCommunity.communityId)
      setLoading(false)
    }

    importCommunity()
  }, [accountCommunity, communityId, community])

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

  async function hideArchivedChannels() {
    await AppController.deviceSettings.update({
      showArchivedInCommunities: ObjectUtils.omit(
        deviceSettings.showArchivedInCommunities,
        communityId,
      ),
    })
  }

  function openLeaveCommunityModal() {
    if (!community) return
    modal.open({
      background: "pattern",
      scrollEnabled: false,
      footer: "rgb",
      component: (
        <ConfirmationModalize
          title="Leave Community"
          description={
            <>
              <StyledText>
                Are you sure you want to leave from community{" "}
              </StyledText>
              <StyledText style={{ color: "red" }}>{community.name}</StyledText>
            </>
          }
          mainActionText="Leave"
          onConfirm={async () => {
            await AppController.community.leave(communityId)
          }}
        />
      ),
      height: 250,
    })
  }

  console.log("================archivedChannels====================")
  console.log(archivedChannels)
  console.log("==================endarchivedChannels==================")

  // ---------------------------------------------------------------------------
  if (!accountCommunity) return null
  return (
    <View style={[styles.communityInfoWrapper]}>
      {/* --------------------------------------------------------------------------- */}
      {/* HEADER */}
      {/* --------------------------------------------------------------------------- */}

      <View style={[styles.communityNameWrapper]}>
        {/* --------------------------------------------------------------------------- */}
        {/* COMMUNITY NAME */}
        {/* --------------------------------------------------------------------------- */}

        <StyledText
          numberOfLines={1}
          ellipsizeMode="tail"
          style={styles.communityName}
        >
          {accountCommunity.name}
        </StyledText>

        {/* --------------------------------------------------------------------------- */}
        {/* COMMUNITY MENU BUTTON */}
        {/* --------------------------------------------------------------------------- */}

        <MenuOpener
          position="bottom-left"
          touchOpacity={0.7}
          key={accountCommunity.communityId}
          content={<CommunityMenu communityId={accountCommunity.communityId} />}
        >
          <Icon name="far fa-ellipsis-vertical" height={18} width={5} />
        </MenuOpener>
      </View>

      {/* --------------------------------------------------------------------------- */}
      {/* BAN MEMBER */}
      {/* --------------------------------------------------------------------------- */}

      {currentUserBan && (
        <ScrollView>
          <StyledText style={styles.banText}>
            You have been banned in this community. You cannot perform any
            actions until you’ll be unbanned by this community administrators.
          </StyledText>
          <View style={styles.banSubWrap}>
            <Image
              source={AppAssets.images.dashboardEmptyPhoto.uri}
              style={styles.banImage}
            />

            <Button
              type="danger"
              containerStyle={styles.banBtn}
              onPress={openLeaveCommunityModal}
            >
              Leave community
            </Button>
          </View>
        </ScrollView>
      )}

      {/* --------------------------------------------------------------------------- */}
      {/* COMMUNITY LOADING SPINNER IF COMMUNITY IS BEING IMPORTED */}
      {/* --------------------------------------------------------------------------- */}

      {!community && (accountCommunity.isPrivate === false || isMember) && (
        <Spinner
          title={"Community is loading..."}
          isEnabled={isLoading}
          height={4}
          indeterminate
          backgroundColor="#1B9FFC"
        />
      )}

      {/* --------------------------------------------------------------------------- */}
      {/* LARGE STATUS BAR */}
      {/* --------------------------------------------------------------------------- */}

      <DashboardCommunityLargeStatusPanel communityId={communityId} />

      {/* --------------------------------------------------------------------------- */}
      {/* IF COMMUNITY EXISTS AND LOADED AND USER CAN READ IT'S CONTENT */}
      {/* --------------------------------------------------------------------------- */}

      {!currentUserBan &&
        !accountCommunity.isDeleted &&
        community &&
        (accountCommunity.isPrivate === false || isMember) && (
          <>
            {/* --------------------------------------------------------------------------- */}
            {/* CHANNELS AND MEMBERS */}
            {/* --------------------------------------------------------------------------- */}

            <ScrollView
              contentOffset={{ x: 0, y: channels.length ? 50 : 0 }}
              contentContainerStyle={{
                minHeight: dimensions.height - safeAreaInsets.top,
              }}
            >
              <View style={{ width: "100%" }}>
                {(channels.length > 0 || channelCategories.length > 0) && (
                  <>
                    {/* --------------------------------------------------------------------------- */}
                    {/* SEARCH INPUT */}
                    {/* --------------------------------------------------------------------------- */}

                    {channels.length > 0 && (
                      <View
                        style={{
                          marginHorizontal: 15,
                          marginBottom: 12,
                        }}
                      >
                        <Input
                          value={keyword}
                          onChangeText={(text) => setKeyword(text.trim())}
                          mode="secondary"
                          placeholder="Search Community"
                          showIcon={true}
                          type={keyword ? "clear" : "search"}
                          onIconPress={() => setKeyword("")}
                        />
                      </View>
                    )}

                    {/* --------------------------------------------------------------------------- */}
                    {/* NO SEARCH RESULTS EMPTY STATE MESSAGE */}
                    {/* --------------------------------------------------------------------------- */}

                    {keyword &&
                      uncategorizedChannels.length === 0 &&
                      filteredChannels.length === 0 &&
                      filteredMembers.length === 0 &&
                      filteredCommunityJoinRequests.length === 0 &&
                      (!isArchivedChannelsShowed ||
                        (isArchivedChannelsShowed &&
                          archivedChannels.length === 0)) && (
                        <EmptyState
                          title="Nothing found"
                          style={styles.noResultWrapper}
                          image={AppAssets.images.dashboardEmptyPhoto}
                          description={
                            <>
                              “{keyword}” did not match any channels or members.{" "}
                              {"\n"}Press to{" "}
                              <EmptyStateLink onPress={() => setKeyword("")}>
                                reset
                              </EmptyStateLink>{" "}
                              search.
                            </>
                          }
                        />
                      )}

                    {/* --------------------------------------------------------------------------- */}
                    {/* UNCATEGORIZED CHANNELS */}
                    {/* --------------------------------------------------------------------------- */}

                    {uncategorizedChannels.length > 0 && (
                      <View
                        style={{
                          marginBottom: channelCategories.length > 0 ? 12 : 0,
                        }}
                      >
                        {uncategorizedChannels.map((channel) => (
                          <DashboardCommunityChannelItem
                            key={channel.id}
                            channel={channel}
                          />
                        ))}
                      </View>
                    )}

                    {/* --------------------------------------------------------------------------- */}
                    {/* CATEGORIES AND CHANNELS */}
                    {/* --------------------------------------------------------------------------- */}

                    {channelCategories
                      .filter((category) => {
                        if (!keyword) return true
                        return (
                          filteredChannels.filter(
                            (channel) => channel.categoryId === category.id,
                          ).length > 0
                        )
                      })
                      .map((category, index, arr) => (
                        <View
                          key={category.id}
                          style={{
                            marginBottom: index === arr.length - 1 ? 8 : 0,
                          }}
                        >
                          <StyledText
                            numberOfLines={1}
                            ellipsizeMode="tail"
                            style={[
                              styles.category,
                              { marginTop: index === 0 ? 0 : 8 },
                            ]}
                          >
                            {category.name}
                          </StyledText>
                          {filteredChannels
                            .filter(
                              (channel) =>
                                channel.categoryId === category.id &&
                                (channel.isPrivate === false ||
                                  channel.privateMemberIds.includes(
                                    accountId || "",
                                  )),
                            )
                            .map((channel) => (
                              <DashboardCommunityChannelItem
                                key={channel.id}
                                channel={channel}
                              />
                            ))}

                          {filteredChannels.filter(
                            (channel) =>
                              channel.categoryId === category.id &&
                              (channel.isPrivate === false ||
                                channel.privateMemberIds.includes(
                                  accountId || "",
                                )),
                          ).length === 0 && (
                            <StyledText
                              style={[
                                styles.categoryInfo,
                                {
                                  paddingBottom: index === 0 ? 8 : 0,
                                  paddingTop: index === 0 ? 0 : 8,
                                },
                              ]}
                            >
                              No channels in the category yet.
                            </StyledText>
                          )}
                        </View>
                      ))}
                  </>
                )}

                {/* --------------------------------------------------------------------------- */}
                {/* IF THERE ARE NO CHANNELS */}
                {/* IF USER HAS PRIVILEGES TO CREATE NEW CHANNELS SHOW BUTTON */}
                {/* --------------------------------------------------------------------------- */}

                {!keyword &&
                  channels.length === 0 &&
                  channelCategories.length === 0 && (
                    <View style={styles.currentMemberWrapper}>
                      <EmptyState
                        title="No channels"
                        image={AppAssets.images.dashboardEmptyPhoto}
                        description={`Community doesn't have any channels yet.`}
                      />

                      <CommunityGuard
                        communityId={accountCommunity.communityId}
                        permissions={[
                          PermissionKindEnum.createChannelsToCommunity,
                        ]}
                      >
                        <Button
                          testID="addChannelButton"
                          onPress={() => {
                            NavigationRef.navigate("CommunityCreateChannel", {
                              communityId: communityId,
                            })
                          }}
                        >
                          Add Channel
                        </Button>
                      </CommunityGuard>
                    </View>
                  )}

                {/* --------------------------------------------------------------------------- */}
                {/* ARCHIVED CHANNELS (WHEN NOT SEARCHING) */}
                {/* --------------------------------------------------------------------------- */}

                {isArchivedChannelsShowed &&
                  !keyword &&
                  channels.length > 0 && (
                    <View style={{ marginVertical: 12 }}>
                      <View style={styles.archivedWrap}>
                        <StyledText style={styles.archivedTitle}>
                          Archived
                        </StyledText>
                        <TouchableOpacity
                          onPress={() => hideArchivedChannels()}
                          style={styles.bgBtn}
                        >
                          <Icon name="fal fa-xmark" size={16} />
                        </TouchableOpacity>
                      </View>

                      {archivedChannels.length > 0 &&
                        archivedChannels.map((channel, index) => (
                          <DashboardCommunityChannelItem
                            key={index}
                            channel={channel}
                          />
                        ))}

                      {archivedChannels.length === 0 && (
                        <StyledText
                          style={[styles.archiveInfo, { marginTop: 8 }]}
                        >
                          No archived channels yet.
                        </StyledText>
                      )}
                    </View>
                  )}

                {/* --------------------------------------------------------------------------- */}
                {/* ARCHIVED CHANNELS (WHEN SEARCHING) */}
                {/* --------------------------------------------------------------------------- */}

                {isArchivedChannelsShowed &&
                  keyword &&
                  archivedChannels.length > 0 && (
                    <View style={{ marginBottom: 12 }}>
                      <View style={styles.archivedWrap}>
                        <StyledText style={styles.archivedTitle}>
                          Archived
                        </StyledText>
                        <TouchableOpacity
                          onPress={() => hideArchivedChannels()}
                          style={styles.bgBtn}
                        >
                          <Icon name="fal fa-xmark" size={16} />
                        </TouchableOpacity>
                      </View>

                      {archivedChannels.length > 0 &&
                        archivedChannels.map((channel, index) => (
                          <DashboardCommunityChannelItem
                            key={index}
                            channel={channel}
                          />
                        ))}

                      {archivedChannels.length === 0 && (
                        <StyledText style={styles.archiveInfo}>
                          No archived channels yet.
                        </StyledText>
                      )}
                    </View>
                  )}

                {/* --------------------------------------------------------------------------- */}
                {/* JOIN REQUESTS (SHOWN TO COMMUNITY ADMINISTRATORS) */}
                {/* --------------------------------------------------------------------------- */}

                <View style={{ paddingLeft: 0 }}>
                  {filteredCommunityJoinRequests.length > 0 && (
                    <>
                      <StyledText
                        style={[styles.memberText, { marginLeft: 15 }]}
                      >
                        Join Requests
                      </StyledText>
                      {filteredCommunityJoinRequests.map((joinRequest) => (
                        <JoinMemberItem
                          key={joinRequest.id}
                          joinRequest={joinRequest}
                          onSave={(joinRequestId) => {}}
                        />
                      ))}
                    </>
                  )}
                </View>

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

                {filteredMembers.length > 0 && (
                  <View>
                    <StyledText style={[styles.memberText]}>Members</StyledText>

                    {filteredMembers.map((member) => (
                      <MemberItem
                        key={member.id}
                        userId={member.identityId}
                        communityId={accountCommunity.communityId}
                      />
                    ))}
                  </View>
                )}
              </View>
            </ScrollView>

            {/* --------------------------------------------------------------------------- */}
            {/* SMALL STATUS BAR */}
            {/* --------------------------------------------------------------------------- */}

            <DashboardCommunitySmallStatusPanel communityId={communityId} />
          </>
        )}
    </View>
  )
}
how to check that all channels are archived ?