import { CommunityPolicyEnum, AccountCommunityType } from "@openchat/types"
import { Models } from "@openchat/models"
import {
  useBanByCommunityAndIdentity,
  useCommunity,
  useCurrentIdentityId,
  useAccountCommunityBy,
} from "@openchat/ui"
import { useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import { AppController, AppStore } from "../../../app/app.globals"
import { useDashboardSettings } from "../../../hook/use-dashboard-settings.hook.js"
import { Button } from "../../../ui-component/button/button.component"
import { memoComponent } from "@openchat/ui"
import { CommunityInfo } from "./community-info.component"
import styles from "./community-panel.styles.module.css"

export const CommunityPanel = memoComponent("CommunityPanel", () => {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------

  const { selectedTab } = useDashboardSettings()
  const navigate = useNavigate()
  const communityId =
    selectedTab.type === "community" ? selectedTab.communityId : null
  const accountCommunity = useAccountCommunityBy({
    communityId,
  })
  const [isLoaded, setLoading] = useState(false)
  const [hasMembership, setMembership] = useState(false)
  const [hasJoinRequest, setJoinRequest] = useState(false)
  const [isDeleted, setDeleted] = useState(false)
  const [isDisabled, setIsDisabled] = useState(false)

  const currentIdentityId = useCurrentIdentityId()
  const currentUserBan = useBanByCommunityAndIdentity(
    communityId,
    currentIdentityId,
  )
  const isBanned = !!currentUserBan
  const community = useCommunity(communityId)

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

  useEffect(() => {
    loadCommunity()
  }, [accountCommunity, communityId])

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

  async function loadCommunity() {
    if (!accountCommunity || !communityId) return
    if (accountCommunity.isDeleted === true) {
      setDeleted(true)
      return
    }

    // if we already have community, we don't need to check an access
    if (AppStore.for(Models.Changeset).has(communityId)) {
      setLoading(true)
      return
    }

    // for private communities we need to check if current user is a community member
    // todo: re-implement
    // if (accountCommunity.policy === CommunityPolicyEnum.private) {
    //   // if user doesn't have a membership - he will be asked to send a petition,
    //   // in the case if petition was not sent yet
    //   const hasJoinRequest = await AppController.joinRequest.checkIfSent(
    //     accountCommunity.communityId,
    //   )
    //   setJoinRequest(hasJoinRequest)
    // }
    if (accountCommunity && !community) {
      await AppController.community.import(accountCommunity.communityId)
    }
    setLoading(true)
  }

  async function sendJoinRequest(accountCommunity: AccountCommunityType) {
    await AppController.joinRequest.join(accountCommunity)
    setIsDisabled(true)
    setJoinRequest(true)
  }

  async function deleteCommunityPublic(id: string) {
    await AppController.accountCommunity.delete(id)
    setIsDisabled(true)
    navigate("/messages")
  }

  const handleImage = () => {
    return (
      <div className={styles.imgSearchWrapper}>
        <img
          src={"/public/images/login-svg/image87.svg"}
          alt="Image panel"
          style={{ width: "16.4rem", height: "14.8rem" }}
        />
      </div>
    )
  }

  if (!accountCommunity) return <></>
  // ---------------------------------------------------------------------------
  return (
    <>
      {isDeleted ? (
        <>
          <div className={styles.heading}>
            <h2>{accountCommunity.name}</h2>
          </div>
          <div className={styles.communityPanelContainer}>
            {/* --------------------------------------------------------------------------- */}
            {/* DELETE COMMUNITY */}
            {/* --------------------------------------------------------------------------- */}

            <div>
              This community was removed by its administrators, thus you cannot
              use it anymore. Press the button to remove it from your
              communities.
            </div>
            {handleImage()}
            <div className={styles.btnCommunity}>
              <Button
                mode="danger"
                onClick={() =>
                  deleteCommunityPublic(accountCommunity.communityId)
                }
                disabled={isDisabled}
              >
                Delete community
              </Button>
            </div>
          </div>
        </>
      ) : (
        <>
          {/* --------------------------------------------------------------------------- */}
          {/* COMMUNITY INFO */}
          {/* --------------------------------------------------------------------------- */}

          {isLoaded && !isBanned && <CommunityInfo />}

          {/* --------------------------------------------------------------------------- */}
          {/* been banned in this community */}
          {/* --------------------------------------------------------------------------- */}
          {isLoaded && isBanned && (
            <>
              <div className={styles.heading}>
                <h2>{accountCommunity.name}</h2>
              </div>
              <div className={styles.communityPanelContainer}>
                <div className={styles.communityPanelText}>
                  You have been banned in this community. You cannot perform any
                  actions until you’ll be unbanned by this community
                  administrators.
                </div>
                {handleImage()}
                <div className={styles.btnCommunity}>
                  <Button onClick={() => {}} disabled={isDisabled}>
                    Leave community
                  </Button>
                </div>
              </div>
            </>
          )}

          {/* --------------------------------------------------------------------------- */}
          {/* LOADING */}
          {/* --------------------------------------------------------------------------- */}

          {!isLoaded &&
            (accountCommunity.policy !== CommunityPolicyEnum.private ||
              hasMembership) && (
              <>
                <div className={styles.heading}>
                  <h2>{accountCommunity.name}</h2>
                </div>
                <div className={styles.loadingContainer}>
                  <div
                    style={{
                      position: "relative",
                      width: "4rem",
                      height: "4rem",
                    }}
                  >
                    <div className={styles.communityLoadingSpinner} />
                  </div>
                  <p className={styles.communityLoadingText}>
                    Community is loading...
                  </p>
                </div>
              </>
            )}

          {/* --------------------------------------------------------------------------- */}
          {/* SEND REQUEST */}
          {/* --------------------------------------------------------------------------- */}

          {!isLoaded &&
            hasMembership === false &&
            hasJoinRequest === false &&
            accountCommunity.policy === CommunityPolicyEnum.private && (
              <>
                <div className={styles.communityPrivate}>
                  <div className={styles.heading}>
                    <h2>{accountCommunity.name}</h2>
                  </div>
                  <p className={styles.communityPanelText}>
                    This is a private community and you’ll be able to access its
                    content only if you’ll have a membership.
                  </p>
                  <br />
                  <p className={styles.communityPanelText}>
                    If you want to ask community administrators to give you a
                    membership, press “send the request” button below.
                  </p>
                  {handleImage()}
                  <div className={styles.btnWrap}>
                    <Button
                      onClick={() => sendJoinRequest(accountCommunity)}
                      disabled={isDisabled}
                    >
                      Send the request
                    </Button>
                  </div>
                </div>
              </>
            )}

          {/* --------------------------------------------------------------------------- */}
          {/*  SENT THE MEMBERSHIP REQUEST */}
          {/* --------------------------------------------------------------------------- */}

          {hasMembership === false && hasJoinRequest && (
            <>
              <div className={styles.heading}>
                <h2>{accountCommunity.name}</h2>
              </div>
              <div>
                <p className={styles.communityPanelPetitionText}>
                  This is a private community and you’ll be able to access its
                  content only if you’ll have a membership.
                </p>
                <p className={styles.communityPanelPetitionText}>
                  You’ve already sent the membership request to access this
                  community contents.{" "}
                </p>
                {handleImage()}
                <div className={styles.textUnderline}>
                  {/* <span className={styles.petitionUnderlineText}>
                    Please wait for the administrator <br />
                    <span className={styles.petitionSubUnderlineText}>
                      approval of your request
                    </span> */}
                  <span className={styles.communityPanelUnderlineText}>
                    Please wait for the administrator approval of your request
                  </span>
                </div>
              </div>
            </>
          )}
        </>
      )}
    </>
  )
})
the issue here when community is private it should displays this part of code `{!isLoaded &&
            hasMembership === false &&
            hasJoinRequest === false &&
            accountCommunity.policy === CommunityPolicyEnum.private && (
              <>
                <div className={styles.communityPrivate}>
                  <div className={styles.heading}>
                    <h2>{accountCommunity.name}</h2>
                  </div>
                  <p className={styles.communityPanelText}>
                    This is a private community and you’ll be able to access its
                    content only if you’ll have a membership.
                  </p>
                  <br />
                  <p className={styles.communityPanelText}>
                    If you want to ask community administrators to give you a
                    membership, press “send the request” button below.
                  </p>
                  {handleImage()}
                  <div className={styles.btnWrap}>
                    <Button
                      onClick={() => sendJoinRequest(accountCommunity)}
                      disabled={isDisabled}
                    >
                      Send the request
                    </Button>
                  </div>
                </div>
              </>
            )}` but it shows everytime this part of code `{isLoaded && !isBanned && <CommunityInfo />}` this part shows when community is public but in private it shows send request first. How to fix it ?