import {
  Image,
  Keyboard,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
} from 'react-native'
import React, { useState, useRef, useEffect, useCallback } from 'react'
import Swiper from 'react-native-swiper'
import appColors from '../../../theme/appColors'
import { styles, windowHeight, windowWidth } from './styles'
import {
  useFocusEffect,
  useNavigation,
  useTheme,
} from '@react-navigation/native'
import { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { RootStackParamList } from '../../../navigation/main/types'
import DropDownPicker from 'react-native-dropdown-picker'
import { useValues } from '../../../utils/context'
import { fontSizes } from '../../../theme/appConstant'
import { useDispatch, useSelector } from 'react-redux'
import {
  languageDataGet,
  settingDataGet,
  taxidosettingDataGet,
  translateDataGet,
} from '../../../api/store/action'
import { getValue, setValue } from '../../../utils/localstorage'
import FastImage from 'react-native-fast-image'
import { AppDispatch } from '../../../api/store'

type OnboardingProps = NativeStackNavigationProp<RootStackParamList>

export function OnBoarding() {
  const { navigate } = useNavigation<OnboardingProps>()
  const { colors } = useTheme()
  const dispatch = useDispatch<AppDispatch>()
  const swiperRef = useRef<any>(null)

  const { languageData, translateData, taxidoSettingData } = useSelector(
    (state: any) => state.setting,
  )

  const [selectedLanguage, setSelectedLanguage] = useState<string>('en')
  const [items, setItems] = useState<any[]>([])
  const [open, setOpen] = useState(false)

  const { isDark, viewRtlStyle, setRtl } = useValues()

  useFocusEffect(
    useCallback(() => {
      const init = async () => {
        const storedLang = await getValue('selectedLanguage')
        const lang = storedLang ? storedLang.replace(/"/g, '') : 'en'
        setSelectedLanguage(lang)
      }
      init()
    }, []),
  )

  useEffect(() => {
    setRtl(selectedLanguage === 'ar')
    dispatch(languageDataGet())
    dispatch(settingDataGet())
    dispatch(translateDataGet(selectedLanguage))
    dispatch(taxidosettingDataGet())
  }, [selectedLanguage, dispatch, setRtl])

  useEffect(() => {
    if (languageData?.data?.length) {
      const formatted = languageData.data.map((lang: any) => ({
        label: lang.name,
        value: lang.locale,
        icon: () => (
          <Image source={{ uri: lang.flag }} style={styles.flagImage} />
        ),
      }))
      setItems(formatted)
    }
  }, [languageData])

  const onLanguageChange = async (item: any) => {
    if (!item?.value) return
    await setValue('selectedLanguage', item.value)
    setSelectedLanguage(item.value)
    setOpen(false)
  }

  const handleNext = (index: number) => {
    const totalSlides =
      taxidoSettingData?.cabbooking_values?.onboarding?.length || 0
    if (index < totalSlides - 1) {
      swiperRef.current?.scrollBy(1)
    } else {
      navigate('Login')
    }
  }

  const onboardingSlides =
    taxidoSettingData?.cabbooking_values?.onboarding || []

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: isDark ? appColors.bgDark : appColors.lightGray,
      }}
    >
      {onboardingSlides.length > 0 ? (
        <Swiper
          loop={false}
          ref={swiperRef}
          activeDotStyle={styles.activeStyle}
          paginationStyle={styles.paginationStyle}
          dotColor={isDark ? appColors.dotPrimary : appColors.dotDark}
        >
          {onboardingSlides.map((slide: any, index: number) => (
            <TouchableWithoutFeedback
              key={`${index}-${selectedLanguage}`}
              onPress={() => {
                setOpen(false)
                Keyboard.dismiss()
              }}
            >
              <View
                style={[
                  styles.slideContainer,
                  { backgroundColor: colors.background },
                ]}
              >
                <View
                  style={[
                    styles.headerView,
                    {
                      backgroundColor: isDark
                        ? appColors.primaryFont
                        : appColors.white,
                    },
                  ]}
                />

                <View
                  style={[
                    styles.languageContainer,
                    { flexDirection: viewRtlStyle, zIndex: 1000 },
                  ]}
                >
                  <DropDownPicker
                    open={open}
                    value={selectedLanguage}
                    items={items}
                    setOpen={setOpen}
                    setItems={setItems}
                    listMode="SCROLLVIEW"
                    onSelectItem={onLanguageChange}
                    containerStyle={styles.dropdownContainer}
                    style={styles.dropdown}
                    dropDownContainerStyle={[
                      styles.dropdownManu,
                      { backgroundColor: colors.card },
                    ]}
                    labelStyle={[styles.labelStyle, { color: colors.text }]}
                    textStyle={{
                      color: colors.text,
                      fontSize: fontSizes.FONT4,
                    }}
                  />
                </View>

                <FastImage
                  style={styles.imageBackground}
                  source={{ uri: slide?.onboarding_image_url }}
                  resizeMode={FastImage.resizeMode.contain}
                />

                <View
                  style={[
                    styles.imageBgView,
                    { backgroundColor: colors.background },
                  ]}
                >
                  <View
                    style={[
                      styles.img,
                      {
                        backgroundColor: isDark
                          ? appColors.primaryFont
                          : appColors.white,
                        // height:selectedLanguage==='en' || selectedLanguage?windowHeight(213):windowHeight(235)
                      },
                    ]}
                  >
                    <View style={styles.line} />

                    <Text
                      style={[
                        styles.title,
                        {
                          color: isDark
                            ? appColors.white
                            : appColors.primaryFont,
                        },
                      ]}
                    >
                      {slide?.title || ''}
                    </Text>

                    <Text style={styles.description}>
                      {slide?.description || ''}
                    </Text>

                    <View
                      style={{
                        flexDirection: viewRtlStyle,
                        alignItems: 'center',
                        marginHorizontal: windowWidth(15),
                        justifyContent: 'space-between',
                        marginTop: windowHeight(40),
                      }}
                    >
                      <TouchableOpacity
                        style={[
                          styles.backArrow,
                          {
                            backgroundColor: isDark
                              ? appColors.bgDark
                              : appColors.lightGray,
                          },
                        ]}
                        onPress={() => navigate('Login')}
                      >
                        <Text
                          style={[
                            styles.skipText,
                            {
                              color: isDark ? appColors.white : appColors.black,
                            },
                          ]}
                        >
                          {translateData?.skip || 'Skip'}
                        </Text>
                      </TouchableOpacity>

                      <TouchableOpacity
                        style={[
                          styles.backArrow,
                          {
                            backgroundColor: isDark
                              ? appColors.white
                              : appColors.black,
                          },
                        ]}
                        onPress={() => handleNext(index)}
                      >
                        <Text
                          style={[
                            styles.skipText,
                            {
                              color: isDark ? appColors.black : appColors.white,
                            },
                          ]}
                        >
                          {translateData?.next || 'Next'}
                        </Text>
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              </View>
            </TouchableWithoutFeedback>
          ))}
        </Swiper>
      ) : (
        <View style={{ flex: 1 }} />
      )}
    </View>
  )
}
