import { ChannelKind } from "@openchat/types"

import { useEffect, useState } from "react"

import {

  Image,

  SafeAreaView,

  TouchableOpacity,

  useWindowDimensions,

  View,

  Animated as AnimatedNative,

} from "react-native"

import Animated, {

  useAnimatedStyle,

  useSharedValue,

} from "react-native-reanimated"

import { AppController } from "../../../app/app.globals"

import { ChannelCoverImagesDictionary } from "./channel-cover-modal.dictionary"

import Carousel from "react-native-reanimated-carousel"

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

import {

  NavigationRef,

  useNavigationRouteParams,

} from "../../../navigation/navigation.hooks"

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

import { useStyles } from "./channel-cover-modal.styles"

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

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

import { TouchableNativeFeedback } from "react-native-gesture-handler"

import { ChannelModalPagination } from "./channel-cover-pagination"

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

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

import React from "react"



export const ChannelCoverModal = () => {

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

  // variables

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

  const styles = useStyles()

  const { width, height } = useWindowDimensions()

  const { channel, community } = useNavigationRouteParams("ChannelCoverModal")

  const scrollX = React.useRef(new AnimatedNative.Value(0)).current

  const [currentIndex, setCurrentIndex] = useState(0)

  const [channelInput, setChannelInput] = useState<{

    name: string

    description: string

    slowMode: number

    isPrivate: boolean

    type: ChannelKind

    coverImageKey: string

  }>({

    name: "",

    description: "",

    slowMode: 0,

    isPrivate: false,

    type: ChannelKind.regular,

    coverImageKey: "",

  })

  const [isVertical, setIsVertical] = useState(false)

  const [autoPlay, setAutoPlay] = useState(false)

  const [pagingEnabled, setPagingEnabled] = useState<boolean>(true)

  const [snapEnabled, setSnapEnabled] = useState<boolean>(true)

  const progressValue = useSharedValue<number>(0)

  const baseOptions = isVertical

    ? ({

        vertical: true,

        width: width * 0.86,

        height: width * 0.6,

      } as const)

    : ({

        vertical: false,

        width: AppConfig.isTablet

          ? 575

          : height < width

          ? width * 0.85

          : height <= 667

          ? 320

          : height <= 667

          ? 300

          : 370,

        height: AppConfig.isTablet

          ? 510

          : height < width

          ? height / 2

          : height <= 667

          ? height / 1.9

          : height / 1.75,

      } as const)



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

  // effects

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



  useEffect(() => {

    if (!channel) return



    setChannelInput({

      ...channel,

    })

  }, [channel])



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

  // functions

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



  async function saveChannel() {

    if (!channel) return

    await AppController.channel.update({

      ...channel,

      coverImageKey: channelInput.coverImageKey,

    })

    NavigationRef.goBack()

  }



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

  // inner components

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

  let parallaxOffset = AppConfig.isTablet

    ? 80

    : height < width && width <= 667

    ? 90

    : height < width

    ? 110

    : 61

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

  return (

    <View

      style={AppConfig.isTablet ? styles.tabletContainer : styles.mobContainer}

    >

      <StickyHeader

        goBack={true}

        background="pattern"

        type="modal"

        title="Cover"

        onPress={() => NavigationRef.goBack()}

        header={<StyledText style={styles.title}>Cover</StyledText>}

      >

        <View style={styles.subContainer}>

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

          {/* TITLE & DESC */}

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



          <View style={styles.titleAndDescWrap}>

            <StyledText style={styles.description}>

              Create folders for different groups of chats and quickly switch

              between them

            </StyledText>

          </View>



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

          {/* CAROUSEL */}

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



          {/* <View style={styles.carouselWrapper}> */}

          <Carousel

            {...baseOptions}

            style={{

              flex: 1,

              width: AppConfig.isTablet ? 600 : width,

              alignItems: "center",

              justifyContent: "center",

            }}

            loop

            onSnapToItem={(index: number) => setCurrentIndex(index)}

            pagingEnabled={true}

            snapEnabled={snapEnabled}

            autoPlay={autoPlay}

            autoPlayInterval={1500}

            onScrollEnd={() => {

              const newIndex = Math.round(progressValue.value)

              setCurrentIndex(newIndex)

            }}

            onProgressChange={(_, absoluteProgress) =>

              (progressValue.value = absoluteProgress)

            }

            mode="parallax"

            modeConfig={{

              parallaxScrollingScale: 0.88,

              parallaxScrollingOffset: parallaxOffset,

              parallaxAdjacentItemScale: 0.82,

            }}

            data={ChannelCoverImagesDictionary}

            // onScrollEnd={AnimatedNative.event(

            //   [{ nativeEvent: { contentOffset: { x: scrollX } } }],

            //   {

            //     useNativeDriver: true,

            //   },

            // )}

            renderItem={({ item, index }) => {

              const isSelected = channelInput.coverImageKey === item.key

              const isNoCoverOption = item.key === "no-cover"

              return (

                <>

                  <View style={styles.imageTitleWrapper}>

                    <View style={styles.titleAndIconWrapper}>

                      <Icon

                        name="fa-light fa-palette"

                        fill="#8592aa"

                        size={14}

                        style={{ marginRight: 5 }}

                      />

                      <StyledText

                        style={{

                          color: "#262626",

                          fontSize: 14,

                          fontWeight: "600",

                          marginLeft: 5,

                        }}

                      >

                        {item.title}

                      </StyledText>

                    </View>

                    {isSelected && (

                      <View style={styles.selectedWrapper}>

                        <Icon

                          name="fal fa-circle-check"

                          fill="#fff"

                          size={14}

                          style={{ alignSelf: "center" }}

                        />

                        <StyledText style={styles.selectedText}>

                          Selected

                        </StyledText>

                      </View>

                    )}

                  </View>

                  <TouchableNativeFeedback

                    onPress={() =>

                      setChannelInput({

                        ...channelInput,

                        coverImageKey: item.key,

                      })

                    }

                  >

                    <Animated.View

                      key={index}

                      style={[

                        styles.container,

                        useAnimatedStyle(() => ({

                          borderRadius: 10,

                        })),

                      ]}

                    >

                      {isNoCoverOption ? (

                        <View style={styles.itemNoCoverContainer}>

                          <Icon

                            name="fa-light fa-image-slash"

                            fill="#8592AA"

                            size={38}

                          />

                        </View>

                      ) : (

                        <Image

                          key={index}

                          style={[styles.image]}

                          source={item.path}

                        />

                      )}

                    </Animated.View>

                  </TouchableNativeFeedback>

                </>

              )

            }}

          />



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

          {/* PAGINATION */}

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



          <View style={styles.pagination}>

            {ChannelCoverImagesDictionary.map((_, index) => (

              // <ChannelModalPagination

              //   backgroundColor={index === currentIndex ? "#1B9FFC" : "#eef2f6"}

              //   animValue={progressValue}

              //   index={index}

              //   key={index}

              //   isRotate={isVertical}

              //   length={ChannelCoverImagesDictionary.length}

              // />

              <View

                key={index}

                style={{

                  backgroundColor:

                    index === currentIndex ? "#1B9FFC" : "#eef2f6",

                  width: 7,

                  height: 7,

                  borderRadius: 50,

                  overflow: "hidden",

                }}

              />

            ))}

          </View>



          {/* </View> */}

        </View>

      </StickyHeader>

      <StickyFooter size="small">

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

        {/* BUTTON */}

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



        <View style={{ flex: 1 }}>

          <Button

            type="primary"

            containerStyle={styles.btn}

            styleText={styles.btnText}

            disabled={channelInput.name === ""}

            onPress={saveChannel}

          >

            Save

          </Button>

        </View>

      </StickyFooter>

    </View>

  )

}

I am  facing an issue where the pagination doesn't sync up properly with the sliding images in  carousel