import React, { useEffect, useRef, useState } from 'react'
import {
  TouchableOpacity,
  Text,
  View,
  FlatList,
  LayoutChangeEvent,
} from 'react-native'
import { SvgUri } from 'react-native-svg'
import styles from '../renderVehicleList/styles'
import appColors from '../../../../../../theme/appColors'
import { useTheme } from '@react-navigation/native'
import { useDispatch, useSelector } from 'react-redux'
import { serviceDataGet } from '../../../../../../api/store/action/serviceAction'
import { useValues } from '../../../../../../utils/context'
import { AppDispatch } from '../../../../../../api/store'
import Icons from '../../../../../../utils/icons/icons'
import { windowHeight, windowWidth } from '../../../../../../theme/appConstant'

interface RenderItemsProps {
  selectedItemIndex: number | null
  handleItemPress: (
    index: number,
    slug: string,
    id: number,
    name: string,
  ) => void
  serviceId: number
}

export function RenderServiceList({
  selectedItemIndex: propSelectedItemIndex,
  handleItemPress,
  serviceId,
}: RenderItemsProps | any) {
  const { serviceData } = useSelector((state: any) => state.service)
  const dispatch = useDispatch<AppDispatch>()
  const { viewRtlStyle, isDark, rtl } = useValues()
  const { colors } = useTheme()
  const [selectedItemIndex, setSelectedItemIndex] = useState<number | null>(
    propSelectedItemIndex,
  )
  const initialSelectedSet = useRef<boolean>(false)

  const flatListRef = useRef<FlatList>(null)
  const [canScrollStart, setCanScrollStart] = useState(false)
  const [canScrollEnd, setCanScrollEnd] = useState(false)
  const scrollPosition = useRef(0)
  const containerWidth = useRef(0)
  const contentWidth = useRef(0)

  useEffect(() => {
    dispatch(serviceDataGet())
  }, [])

  useEffect(() => {
    if (!initialSelectedSet.current && serviceData?.data?.length > 0) {
      const index = serviceData.data.findIndex(
        (item: any) => item.id === serviceId,
      )
      if (index !== -1) {
        setSelectedItemIndex(index)
        initialSelectedSet.current = true
      }
    }
  }, [serviceData, serviceId])

  const onItemPress = (
    index: number,
    slug: string,
    id: number,
    name: string,
  ) => {
    setSelectedItemIndex(index)
    handleItemPress(index, slug, id, name)
  }

  const checkScrollAbilities = () => {
    setCanScrollStart(scrollPosition.current > 0)
    setCanScrollEnd(
      scrollPosition.current + containerWidth.current < contentWidth.current,
    )
  }

  const handleScroll = (event: any) => {
    scrollPosition.current = event.nativeEvent.contentOffset.x
    checkScrollAbilities()
  }

  const scrollRight = () => {
    flatListRef.current?.scrollToOffset({
      offset: scrollPosition.current + 200,
      animated: true,
    })
  }

  const scrollLeft = () => {
    flatListRef.current?.scrollToOffset({
      offset: Math.max(scrollPosition.current - 200, 0),
      animated: true,
    })
  }

  const renderItem = ({ item, index }: any) => (
    <TouchableOpacity
      activeOpacity={0.7}
      style={[
        styles.listView,
        {
          borderColor: isDark
            ? appColors.darkborder
            : selectedItemIndex === index
            ? isDark
              ? appColors.white
              : appColors.lightGray
            : appColors.loader,

          backgroundColor: isDark
            ? selectedItemIndex === index
              ? appColors.bgDark
              : colors.card
            : selectedItemIndex === index
            ? appColors.lightGray
            : appColors.white,
          borderWidth: selectedItemIndex === index ? 0 : windowHeight(0.2),
        },
      ]}
      onPress={() => onItemPress(index, item.slug, item.id, item.name)}
    >
      <View
        style={[styles.iconAndTextContainer, { flexDirection: viewRtlStyle }]}
      >
        <SvgUri
          width={34}
          height={34}
          uri={item?.service_icon_url}
          stroke="none"
          fill={isDark ? appColors.white : 'transparent'}
        />
      </View>

      <Text
        style={[
          styles.serviceTitle,
          {
            color:
              selectedItemIndex === index
                ? isDark
                  ? appColors.white
                  : appColors.black
                : colors.text,
          },
        ]}
      >
        {item.name}
      </Text>
    </TouchableOpacity>
  )
  return (
    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
      {canScrollStart && (
        <TouchableOpacity
          onPress={scrollLeft}
          style={{
            position: 'absolute',
            left: -9,
            zIndex: 3,
            height: windowHeight(3.45),
            width: windowHeight(3.45),
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
            borderWidth: windowWidth(0.35),
            borderColor: isDark ? appColors.darkborder : appColors.loader,
            justifyContent: 'center',
            alignItems: 'center',
            borderRadius: windowHeight(1.8),
          }}
        >
          <Icons.Back color={isDark ? appColors.white : appColors.black} />
        </TouchableOpacity>
      )}

      <FlatList
        ref={flatListRef}
        horizontal
        showsHorizontalScrollIndicator={false}
        data={serviceData?.data}
        renderItem={renderItem}
        keyExtractor={(_, index) => index.toString()}
        contentContainerStyle={{ gap: 12 }}
        onScroll={handleScroll}
        scrollEventThrottle={16}
        onContentSizeChange={w => {
          contentWidth.current = w
          checkScrollAbilities()
        }}
        onLayout={(e: LayoutChangeEvent) => {
          containerWidth.current = e.nativeEvent.layout.width
          checkScrollAbilities()
        }}
      />

      {canScrollEnd && (
        <TouchableOpacity
          onPress={scrollRight}
          style={{
            position: 'absolute',
            right: -9,
            zIndex: 3,
            height: windowHeight(3.45),
            width: windowHeight(3.45),
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
            borderWidth: windowWidth(0.35),
            borderColor: isDark ? appColors.darkborder : appColors.loader,
            justifyContent: 'center',
            alignItems: 'center',
            borderRadius: windowHeight(1.8),
            transform: [{ rotate: '270deg' }],
          }}
        >
          <Icons.RightArrow
            color={isDark ? appColors.white : appColors.black}
          />
        </TouchableOpacity>
      )}
    </View>
  )
}
