import { AccountCommunityType } from "@openchat/types"
import { useAccountCommunities } from "@openchat/ui"
import React, { useEffect, useState } from "react"
import {
  NestableDraggableFlatList,
  NestableScrollContainer,
  RenderItemParams,
} from "react-native-draggable-flatlist"
import { AppController } from "../../../../app/app.globals"
import { DashboardTabsCommunityTabButton } from "../dashboard-tabs-community-tab-button/dashboard-tabs-community-tab-button.component"
import { useDashboardSettings } from "../../../../hook/use-dashboard-settings.hook"
import { ArrayUtils } from "@openchat/core"

// @reviewed
export function DashboardTabsCommunityButtons() {
  // ---------------------------------------------------------------------------
  // variables
  // ---------------------------------------------------------------------------

  const { setSelectedTab } = useDashboardSettings()
  const allAccountCommunities = useAccountCommunities()
  const [orderedAccountCommunities, setOrderedAccountCommunities] = useState(
    () => ArrayUtils.sortAsc(allAccountCommunities, "dashboardTabOrder"),
  )
  const [draggableIndex, setDraggableIndex] = useState<string | null>(null)

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

  useEffect(() => {
    setOrderedAccountCommunities(
      ArrayUtils.sortAsc(allAccountCommunities, "dashboardTabOrder"),
    )
  }, [allAccountCommunities])

  // ---------------------------------------------------------------------------
  return (
    <NestableScrollContainer
      nestedScrollEnabled
      showsVerticalScrollIndicator={false}
      style={{
        flexShrink: 1,
        flexGrow: 0,
        width: "100%",
        paddingVertical: orderedAccountCommunities.length > 0 ? 8 : 0,
      }}
    >
      <NestableDraggableFlatList
        data={orderedAccountCommunities}
        keyExtractor={(accountCommunity) => accountCommunity.id}
        renderItem={({
          item: accountCommunity,
          drag,
        }: RenderItemParams<AccountCommunityType>) => (
          <DashboardTabsCommunityTabButton
            accountCommunity={accountCommunity}
            drag={drag}
            communityDraggableIndex={draggableIndex}
            onCommunityIconClick={(communityId) => {
              setSelectedTab({
                type: "community",
                communityId: communityId,
                roomId: null,
              })
            }}
          />
        )}
        onDragBegin={(index) => {
          setDraggableIndex(orderedAccountCommunities[index].id)
        }}
        onDragEnd={async (result) => {
          const draggedAccountCommunities: AccountCommunityType[] = result.data
          setDraggableIndex(null)
          setOrderedAccountCommunities(draggedAccountCommunities)
          await AppController.accountCommunity.reorderInDashboardTabs({
            accountCommunityIds: draggedAccountCommunities.map(
              (accountCommunity) => accountCommunity.id,
            ),
          })
        }}
      />
    </NestableScrollContainer>
  )
}
auto scrolling to new accountCommunity active item