import {
  View,
  ScrollView,
  Text,
  TouchableOpacity,
  Platform,
} from 'react-native'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './styles'
import {
  General,
  RegistrationDetails,
  Profile,
  SettingHeader,
  AlertZone,
} from './component/'
import { useFocusEffect, useTheme } from '@react-navigation/native'
import DeviceInfo from 'react-native-device-info'
import {
  categoryDataGet,
  currentZone,
  deleteProfile,
  fleetDriverList,
  fleetVehicleList,
  planDataGet,
  rentalVehicleData,
  serviceDataGet,
  settingDataGet,
  ticketDataGet,
  walletData,
} from '../../../api/store/action'
import { useDispatch, useSelector } from 'react-redux'
import {
  BottomSheetBackdrop,
  BottomSheetModal,
  BottomSheetModalProvider,
  BottomSheetView,
} from '@gorhom/bottom-sheet'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import appColors from '../../../theme/appColors'
import Images from '../../../utils/images/images'
import appFonts from '../../../theme/appFonts'
import { Button, notificationHelper } from '../../../commonComponents'
import { clearValue } from '../../../utils/localstorage'
import useSmartLocation from '../../../commonComponents/helper/locationHelper'
import FastImage from 'react-native-fast-image'
import { useValues } from '../../../utils/context'
import {
  windowHeight,
  fontSizes,
  windowWidth,
} from '../../../theme/appConstant'
import { resetState } from '../../../api/store/reducers'
import messaging from '@react-native-firebase/messaging'
import { initializeApp } from 'firebase/app'
import { getFirestore, doc, updateDoc } from 'firebase/firestore'
import { firebaseConfig } from '../../../../firebase'
import { AppDispatch } from '../../../api/store'
import { useAppNavigation } from '../../../utils/navigation'
import { incentivesValue } from '../../../api/store/action/incentiveAction'

const app = initializeApp(firebaseConfig)
const db = getFirestore(app)

export function Settings() {
  const dispatch = useDispatch<AppDispatch>()
  const { translateData } = useSelector((state: any) => state.setting)
  const { colors } = useTheme()
  const [versionCode, setVersionCode] = useState<string>('')
  const { viewRtlStyle } = useValues()
  const { isDark } = useValues()
  const { selfDriver } = useSelector((state: any) => state.account)

  useEffect(() => {
    const fetchVersion = async () => {
      const version = await DeviceInfo.getVersion()
      setVersionCode(version)
    }

    const today = new Date()
    const formattedToday = `${today.getFullYear()}-${
      today.getMonth() + 1
    }-${today.getDate()}`

    dispatch(planDataGet())
    dispatch(ticketDataGet())
    dispatch(rentalVehicleData())
    dispatch(fleetVehicleList())
    dispatch(incentivesValue({ incentivedate: formattedToday }))

    dispatch(serviceDataGet())
    fetchVersion()
  }, [])

  useFocusEffect(
    useCallback(() => {
      dispatch(walletData())
      return () => {}
    }, [dispatch]),
  )

  const bottomSheetRef = useRef<any>(null)
  const snapPoints = useMemo(() => [Platform.OS === 'ios' ? '57%' : '55%'], [])
  const openSheet = () => bottomSheetRef.current?.present()

  const renderBackdrop = useCallback(
    (props: any) => (
      <BottomSheetBackdrop
        {...props}
        pressBehavior="close"
        appearsOnIndex={0}
        disappearsOnIndex={-1}
      />
    ),
    [],
  )
  const navigation = useAppNavigation()
  const { currentLatitude, currentLongitude } = useSmartLocation()

  const deleteAccount = () => {
    messaging().unsubscribeFromTopic(`user_${selfDriver?.id}`)

    notificationHelper('', 'Account Deleted Successfully', 'error')
    navigation.reset({
      index: 0,
      routes: [{ name: 'Login' }],
    })
    dispatch(deleteProfile())
    dispatch(settingDataGet())
    dispatch(currentZone({ lat: currentLatitude, lng: currentLongitude }))
    clearValue()
  }

  const closeLogoutSheet = () => {
    logoutSheetRef.current?.close()
  }

  const renderLogoutBackdrop = useCallback(
    (props: any) => (
      <BottomSheetBackdrop
        {...props}
        pressBehavior="close"
        appearsOnIndex={0}
        disappearsOnIndex={-1}
      />
    ),
    [],
  )

  const gotoLogout = async () => {
    messaging().unsubscribeFromTopic(`user_${selfDriver?.id}`)

    if (selfDriver?.id && selfDriver?.role == 'driver') {
      const driverRef = doc(db, 'driverTrack', selfDriver.id.toString())
      await updateDoc(driverRef, {
        is_online: '0',
      })
    }

    notificationHelper('', 'Logged Out Successfully', 'error')
    closeLogoutSheet()
    clearValue()
    dispatch(resetState())
    dispatch(settingDataGet())
    dispatch(currentZone({ lat: currentLatitude, lng: currentLongitude }))

    navigation.reset({
      index: 0,
      routes: [{ name: 'Login' }],
    })
  }

  const logoutSheetRef = useRef<any>(null)
  const logoutSnapPoints = useMemo(
    () => [Platform.OS === 'ios' ? '49%' : '45%'],
    [],
  )

  const openLogoutSheet = () => {
    logoutSheetRef.current?.present()
  }
  return (
    <GestureHandlerRootView>
      <View
        style={{
          flex: 1,
          backgroundColor: isDark ? appColors.bgDark : appColors.lightGray,
        }}
      >
        <ScrollView
          style={[
            styles.main,
            {
              backgroundColor: isDark ? appColors.bgDark : appColors.lightGray,
            },
          ]}
          showsVerticalScrollIndicator={false}
        >
          <SettingHeader />
          <Profile />
          <View style={styles.container}>
            <General />
            <RegistrationDetails />
            <AlertZone
              openSheet={openSheet}
              openLogoutSheet={openLogoutSheet}
            />
            <Text style={styles.version}>
              {translateData.settingTextVersion}: {versionCode}
            </Text>
          </View>
        </ScrollView>
      </View>

      <BottomSheetModalProvider>
        <BottomSheetModal
          ref={bottomSheetRef}
          index={1}
          snapPoints={snapPoints}
          backdropComponent={renderBackdrop}
          enablePanDownToClose
          handleIndicatorStyle={{
            backgroundColor: appColors.primary,
            height: windowHeight(0.6),
            width: windowWidth(10),
            marginTop: windowHeight(0.2),
            marginBottom: windowHeight(1.5),
          }}
          containerStyle={{ borderRadius: windowWidth(5) }}
          backgroundStyle={{
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
          }}
        >
          <BottomSheetView>
            <View
              style={{
                alignItems: 'center',
                backgroundColor: isDark
                  ? appColors.darkborder
                  : appColors.white,
                height: windowHeight(30),
                width: '90%',
                alignSelf: 'center',
                marginHorizontal: windowWidth(5),
                borderWidth: windowWidth(0.25),
                borderColor: isDark ? appColors.darkborder : appColors.loader,
                borderRadius: windowWidth(5),
              }}
            >
              <FastImage
                source={Images.delete}
                style={{ height: windowHeight(14), width: windowHeight(13) }}
                resizeMode="cover"
              />
              <Text
                style={{
                  color: isDark ? appColors.white : appColors.black,
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT4HALF,
                  top: windowHeight(1),
                }}
              >
                {translateData?.whatyoudeleteaccount}
              </Text>
              <Text
                style={{
                  color: appColors.darkBorderBlack,
                  textAlign: 'center',
                  fontFamily: appFonts.regular,
                  fontSize: fontSizes.FONT3HALF,
                  width: '92%',
                  top: windowHeight(2),
                }}
              >
                {translateData?.deleteNotice}
              </Text>
            </View>
            <View style={{ width: '100%', top: windowHeight(2.5) }}>
              <Button
                title={translateData?.ok}
                backgroundColor={isDark ? appColors.white : appColors.black}
                color={isDark ? appColors.black : appColors.white}
                onPress={deleteAccount}
              />
            </View>
          </BottomSheetView>
        </BottomSheetModal>
      </BottomSheetModalProvider>

      <BottomSheetModalProvider>
        <BottomSheetModal
          ref={logoutSheetRef}
          index={1}
          snapPoints={logoutSnapPoints}
          backdropComponent={renderLogoutBackdrop}
          enablePanDownToClose={true}
          handleIndicatorStyle={{
            backgroundColor: appColors.primary,
            height: windowHeight(0.6),
            width: windowWidth(10),
            marginTop: windowHeight(0.2),
            marginBottom: windowHeight(1.5),
          }}
          backgroundStyle={{
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
          }}
        >
          <BottomSheetView style={{ alignItems: 'center' }}>
            <View
              style={{
                alignItems: 'center',
                backgroundColor: isDark
                  ? appColors.darkborder
                  : appColors.white,
                height: windowHeight(22),
                width: '90%',
                alignSelf: 'center',
                marginHorizontal: windowWidth(5),
                borderWidth: windowWidth(0.25),
                borderColor: isDark ? appColors.darkborder : appColors.loader,
                borderRadius: windowWidth(5),
              }}
            >
              <FastImage
                source={Images.logoutGif}
                style={{ height: windowHeight(10), width: windowHeight(13) }}
                resizeMode="cover"
              />
              <Text
                style={{
                  color: isDark ? appColors.white : appColors.black,
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT4HALF,
                }}
              >
                {translateData?.whatyoulogout}
              </Text>
              <Text
                style={{
                  color: appColors.darkBorderBlack,
                  textAlign: 'center',
                  fontFamily: appFonts.regular,
                  fontSize: fontSizes.FONT3HALF,
                  width: '92%',
                  top: windowHeight(2),
                }}
              >
                {translateData?.logoutnote}
              </Text>
            </View>
            <View style={{ width: '100%', top: windowHeight(2.5) }}>
              <Button
                title={translateData?.ok}
                backgroundColor={isDark ? appColors.white : appColors.black}
                color={isDark ? appColors.black : appColors.white}
                onPress={gotoLogout}
              />
            </View>
          </BottomSheetView>
        </BottomSheetModal>
      </BottomSheetModalProvider>
    </GestureHandlerRootView>
  )
}
