import React, { useCallback, useEffect, useRef, useState } from 'react'
import {
  Animated,
  View,
  Image,
  Text,
  TouchableOpacity,
  Vibration,
  FlatList,
  BackHandler,
  Linking,
  InteractionManager,
  Modal,
  ActivityIndicator,
  Alert,
} from 'react-native'
import appColors from '../../../theme/appColors'
import {
  fontSizes,
  windowHeight,
  windowWidth,
} from '../../../theme/appConstant'
import Icons from '../../../utils/icons/icons'
import { useDispatch, useSelector } from 'react-redux'
import Images from '../../../utils/images/images'
import appFonts from '../../../theme/appFonts'
import useSmartLocation from '../../../commonComponents/helper/locationHelper'
import {
  useFocusEffect,
  useIsFocused,
  useNavigation,
} from '@react-navigation/native'
import { Button, LowBalance, notificationHelper } from '../../../commonComponents'
import {
  startLiveLocation,
  stopLiveLocation,
} from '../../../commonComponents/helper/liveLocationHelper'
import {
  currentZone,
  dashBoardData,
  rideDataGets,
  rideRequestDataGet,
  selfDriverData,
  sosAlertGet,
  sosDataGet,
  taxidosettingDataGet,
  vehicleData,
  walletData,
} from '../../../api/store/action'
import Sound from 'react-native-sound'
import { MapScreen } from '../mapScreen'
import BottomSheet, {
  BottomSheetModal,
  BottomSheetView,
  BottomSheetModalProvider,
  BottomSheetFlatList,
} from '@gorhom/bottom-sheet'
import { UpcomingRide } from '../component'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { useValues } from '../../../utils/context'
import { useTourGuideController } from 'rn-tourguide'
import { getValue, setValue } from '../../../utils/localstorage'
import PushNotification from 'react-native-push-notification'
import { initializeApp } from 'firebase/app'
import {
  getFirestore,
  doc,
  onSnapshot,
  getDoc,
  setDoc,
  Timestamp,
} from 'firebase/firestore'
import { firebaseConfig } from '../../../../firebase'
import styles from './styles'
import { AppDispatch } from '../../../api/store'
import { useFilterOptions } from './data'

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

Sound.setCategory('Playback', true)


export function Home() {
  const { currentLatitude, currentLongitude } = useSmartLocation()
  const { selfDriver } = useSelector((state: any) => state.account)
  const char = selfDriver?.name ? selfDriver.name.charAt(0) : ''
  const { zoneValue } = useSelector((state: any) => state.zoneUpdate)
  const driverId = selfDriver?.id
  const [isOnline, setIsOnline] = useState(false)
  const { taxidoSettingData } = useSelector((state: any) => state.setting)
  const { sosData, sosAlert } = useSelector((state: any) => state.sos)
  const upcomingRideRef = useRef(null)
  const [selectedRide, setSelectedRide] = useState(null)
  const [rides, setRides] = useState<any>([])
  const dispatch = useDispatch<AppDispatch>()
  const { navigate } = useNavigation<any>()
  const navigation = useNavigation<any>()
  const [status, setStatus] = useState<'online' | 'offline'>('online')
  const bottomSheetModalRef = useRef<BottomSheetModal>(null)
  const [isBottomSheetOpen, setIsBottomSheetOpen] = useState(false)
  const [totalOnlineSeconds, setTotalOnlineSeconds] = useState(0)
  const bottomSheetOfflineRef = useRef<BottomSheetModal>(null)
  const [isBottomSheetOfflineOpen, setIsBottomSheetOfflineOpen] =
    useState(false)
  const [offlineloading, setOfflineLoading] = useState(false)
  const [isAmountVisible, setIsAmountVisible] = useState(false)
  const [viewMode, setViewMode] = useState<'amount' | 'time'>('amount')
  const bottomSheetSOSRef = useRef<BottomSheetModal>(null)
  const bottomSheetFilterRef = useRef<BottomSheetModal>(null)

  const [isBottomSheetSOSOpen, setIsBottomSheetSOSOpen] = useState(false)
  const [isBottomSheetfilterOpen, setIsBottomSheetfilterOpen] = useState(false)

  const [location, setLocation] = useState<{
    latitude: number
    longitude: number
  } | null>(null)
  const { translateData } = useSelector((state: any) => state.setting)
  const { isDark, viewRtlStyle, rtl, textRtlStyle } = useValues()
  const { dashBoardList } = useSelector((state: any) => state.dashboard)
  const revenue = dashBoardList?.day?.dayRevenues?.revenues?.slice(-1)[0] ?? 0

  const TodayIncome = `${zoneValue?.currency_symbol} ${Number(revenue).toFixed(
    2,
  )}`




  const { start, canStart, stop } = useTourGuideController()
  const [noservice, setNodervice] = useState<boolean>(false)
  const [lowBalance, setLowBalance] = useState<boolean>(false)
  const mapRef = useRef()
  const isFocused = useIsFocused()
  const bottomSheetRef = useRef<any>(null)
  const cancelbottomSheetRef = useRef<BottomSheetModal>(null)
  const filterbottomSheetRef = useRef<BottomSheetModal>(null)

  const [cancel, setCancel] = useState<boolean>(false)
  const snapPoints = ['30%']
  const isRingtonePlayingRef = useRef<boolean>(false)
  const soundInstanceRef = useRef<any>(null)
  const [loading, setLoading] = useState<boolean>(true)
  const [isBottomSheetCancelOpen, setIsBottomSheetCancelOpen] =
    useState<boolean>(false)
  const [on, SetOn] = useState(false)
  const [hasShownTour, setHasShownTour] = useState<boolean>(false)
  const [loadingId, setLoadingId] = useState<null>(null)
  const [showOnline, setShowOnline] = useState<boolean>(true)

  const maskValue = (value: any) => {
    if (value == null || value === 0) {
      return '*.**'
    }
    const strValue = value.toString()
    return strValue
      .split('')
      .map((char: string) => (char === '.' ? '.' : '*'))
      .join('')
  }

  const lastRevenue =
    dashBoardList?.day?.dayRevenues?.revenues?.length > 0
      ? dashBoardList.day.dayRevenues.revenues.slice(-1)[0]
      : null

  const maskedAmount = `${zoneValue?.currency_symbol ?? ''} ${maskValue(
    lastRevenue,
  )}`

  useEffect(() => {
    if (isFocused && !hasShownTour) {
      start()
      setHasShownTour(true)
    } else if (!isFocused) {
      stop()
    }
  }, [isFocused])
  useEffect(() => {
    const fetchZone = async () => {
      if (!currentLatitude || !currentLongitude) {
        return
      }

      try {
        const res: any = await dispatch(
          currentZone({ lat: currentLatitude, lng: currentLongitude }),
        ).unwrap()
        if (res?.id) {
          setNodervice(false)
        } else {
          setNodervice(true)
        }
      } catch (err) {
        setNodervice(true)
      }
    }
    fetchZone()
  }, [currentLatitude, currentLongitude])

  useEffect(() => {
    const showTourIfFirstTime = async () => {
      const hasSeenTour = await getValue('hasSeenTour')
      if (!hasSeenTour && canStart) {
        InteractionManager.runAfterInteractions(() => {
          requestAnimationFrame(() => {
            setTimeout(async () => {
              if (canStart) {
                start()
                await setValue('hasSeenTour', 'true')
              }
            }, 500)
          })
        })
      }
    }
    if (noservice == false) {
      showTourIfFirstTime()
    }
  }, [canStart])

  const fetchStoredLocation = async () => {
    try {
      const lat = await AsyncStorage.getItem('user_latitude')
      const lng = await AsyncStorage.getItem('user_longitude')
      if (lat && lng) {
        setLocation({
          latitude: parseFloat(lat),
          longitude: parseFloat(lng),
        })
      } else {
        setLocation(null)
      }
    } catch (error) { }
  }

  useFocusEffect(
    useCallback(() => {
      fetchStoredLocation()
    }, []),
  )

  useEffect(() => {
    if (!isFocused) return
    const backAction = () => {
      bottomSheetRef.current?.expand()
      return true
    }
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    )
    return () => backHandler.remove()
  }, [isFocused])

  const handleExit = () => {
    bottomSheetRef.current?.close()

    setTimeout(() => {
      BackHandler.exitApp()
    }, 150)
  }

  const handleCloseSheet = () => {
    bottomSheetRef.current?.close()
  }

  const handleCloseSheet1 = () => {
    cancelbottomSheetRef.current?.close()
    setIsBottomSheetCancelOpen(false)
  }

  const handleExit1 = () => {
    bottomSheetRef.current?.close()
    if (upcomingRideRef.current) {
      upcomingRideRef.current.decline()
    }
    setIsBottomSheetCancelOpen(false)
    cancelbottomSheetRef.current?.close()
  }

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

  useEffect(() => {
    const fetchStatus = async () => {
      try {
        if (!driverId) return

        const driverRef = doc(db, 'driverTrack', driverId.toString())
        const driverSnap = await getDoc(driverRef)

        if (driverSnap.exists()) {
          const isOnline = driverSnap.data()?.is_online
          setStatus(isOnline == 1 ? 'online' : 'offline')
        }
      } catch (error) { }
    }

    fetchStatus()
  }, [driverId])

  const handlePresentModalPress = useCallback(() => {
    if (isBottomSheetOpen) {
      bottomSheetModalRef.current?.close()
      setIsBottomSheetOpen(false)
    } else {
      bottomSheetModalRef.current?.present()
      setIsBottomSheetOpen(true)
    }
  }, [isBottomSheetOpen])

  const handleSheetChanges = useCallback(
    (index: number) => {
      if (index === -1) {
        stopNotificationSound()
      }
    },
    [stopNotificationSound],
  )

  const statusColors = {
    online: {
      outer: appColors.primary,
      inner: appColors.primary,
      pulse1: appColors.primaryLight,
      pulse2: appColors.value,
      label: 'Online',
      icon: <Icons.Online />,
    },
    offline: {
      outer: appColors.brightRed,
      inner: appColors.vividRed,
      pulse1: appColors.darkCrimson,
      pulse2: appColors.roseTint,
      label: 'Offline',
      icon: <Icons.Stop />,
    },
  }
  const nextStatus = status === 'online' ? 'offline' : 'online'
  const current = statusColors[nextStatus]

  useEffect(() => {
    if (!taxidoSettingData || Object.keys(taxidoSettingData).length === 0) {
      dispatch(taxidosettingDataGet())
      dispatch(selfDriverData())
    }
  }, [taxidoSettingData])

  useFocusEffect(
    useCallback(() => {
      dispatch(rideDataGets())
      dispatch(vehicleData())
      dispatch(walletData())
      const unit = zoneValue?.distance_type
      const zoneId = zoneValue?.id
      const driver_id = ''
      dispatch(dashBoardData({ unit, zoneId, driver_id }))
    }, []),
  )

  const gotoRide = (ride: any) => {
    stopNotificationSound()
    if (ride?.service_category?.service_category_type === 'rental') {
      navigate('RentalDetails', { ride })
    } else {
      navigation.navigate('Ride', { ride })
    }
    bottomSheetModalRef.current?.close()
    setIsBottomSheetOpen(false)
  }

  const gotoInfo = (ride: any) => {
    if (
      ride?.service_category?.service_category_type === 'schedule' ||
      ride?.service?.service_type === 'freight' ||
      ride?.service?.service_type === 'parcel' ||
      ride?.service_category?.service_category_type === 'package'
    ) {
      navigate('RideInfo', { ride })
    } else if (ride?.service_category?.service_category_type === 'rental') {
      navigate('RentalDetails', { ride })
    }
  }

  useEffect(() => {
    const zone_id = zoneValue?.id
    if (zone_id) {
      const intervalId = setInterval(() => {
        dispatch(rideRequestDataGet(zone_id))
      }, 5000)
      return () => clearInterval(intervalId)
    }
  }, [dispatch, zoneValue])

  const selectDriver = (ride: any) => {
    setSelectedRide(ride)
  }

  const onRideDeclined = () => {
    if (rides?.length <= 1) {
      stopNotificationSound()
      bottomSheetModalRef.current?.close()
    }
  }
  const walletBalance = Number(selfDriver?.wallet_balance ?? 0);
  const minWalletBalance = Number(
    taxidoSettingData?.cabbooking_values?.wallet?.driver_min_wallet_balance ?? 0
  );
  useFocusEffect(
    useCallback(() => {
      const fetchOnlineStatus = async () => {
        if (!selfDriver?.id) {
          setIsOnline(false)
          return
        }

        if (selfDriver?.wallet_balance < 0 && taxidoSettingData?.cabbooking_values?.activation?.allow_negative_balance === 0) {
          setLowBalance(true)
          notificationHelper('', translateData.lowBalance, 'error')
          setIsOnline(false)
          return
        }
        else if (walletBalance < minWalletBalance) {
          setLowBalance(true);
          notificationHelper("", translateData.insufficientWalletBalance, "error");
          setIsOnline(false);
        }

        try {
          const driverRef = doc(db, 'driverTrack', selfDriver.id.toString())
          const snapshot = await getDoc(driverRef)

          if (snapshot.exists()) {
            const online = snapshot.data()?.is_online === '1'
            setIsOnline(online)

            if (online) {
              startLiveLocation(selfDriver.id, selfDriver)
            } else {
              stopLiveLocation()
            }
          } else {
            setIsOnline(false)
            stopLiveLocation()
          }
        } catch (error) {
          setIsOnline(false)
          stopLiveLocation()
        }
      }

      fetchOnlineStatus()
    }, [selfDriver?.id, selfDriver?.wallet_balance, translateData]),
  )
  const getTodayDateStr = () => {
    const today = new Date()
    return today.toISOString().split('T')[0]
  }

  const toggleSwitch = async (targetState: 'online' | 'offline') => {
    Vibration.vibrate(42)
    if (!driverId) return

    if (targetState === status) return

    if (targetState === 'online') {
      notificationHelper('', translateData?.onlineNote, 'success')
      SetOn(true)
      runOnlineAnimation()

      if (selfDriver?.wallet_balance < 0) {
        notificationHelper('', translateData.lowBalance, 'error')
        return
      }

      setIsOnline(true)
      setStatus('online')

      try {
        const driverRef = doc(db, 'driverTrack', driverId.toString())
        const today = getTodayDateStr()
        const snapshot = await getDoc(driverRef)
        const data = snapshot.exists() ? snapshot.data() : {}

        const now = Timestamp.now()

        const updatePayload: any = {
          is_online: '1',
          last_online_at: now,
          lat: currentLatitude?.toString(),
          lng: currentLongitude?.toString(),
          service_id: selfDriver?.service_id,
          service_category_id: selfDriver?.service_category_id,
          vehicle_type_id: selfDriver?.vehicle_info?.vehicle_type_id,
          vehicle_map_icon_url:
            selfDriver?.vehicle_info?.vehicle_type_map_icon_url,
          driver_name: selfDriver?.name,
          review_count: selfDriver?.review_count,
          rating_count: selfDriver?.rating_count,
          model: selfDriver?.vehicle_info?.model,
          plate_number: selfDriver?.vehicle_info?.plate_number,
          profile_image_url: selfDriver?.profile_image_url,
        }

        if (data?.date !== today) {
          updatePayload.total_online_time_today = 0
          updatePayload.date = today
        }

        await setDoc(driverRef, updatePayload, { merge: true })
        await startLiveLocation(driverId, selfDriver)
      } catch (err) {
        setIsOnline(false)
        setStatus('offline')
        stopLiveLocation()
        notificationHelper('', translateData?.failedoonline, 'error')
      }
    } else {
      // ✅ OPEN OFFLINE POPUP
      bottomSheetOfflineRef.current?.present()
      setIsBottomSheetOfflineOpen(true)
      setIsOnline(false)
      setStatus('offline')
    }
  }

  const driverOffline = async () => {
    try {
      if (!driverId) return

      const driverRef = doc(db, 'driverTrack', driverId.toString())
      const snapshot = await getDoc(driverRef)

      if (snapshot.exists()) {
        const data = snapshot.data()
        const rideStatus = data?.is_on_ride
        const onRide =
          typeof rideStatus === 'string'
            ? rideStatus
            : rideStatus != null
              ? String(rideStatus)
              : '0'

        if (onRide == '1') {
          notificationHelper('', translateData?.onlinefailed, 'error')
          bottomSheetOfflineRef.current?.close()

          return
        }
      }

      SetOn(true)
      runOnlineAnimation()
      setOfflineLoading(true)
      setIsOnline(false)
      setStatus('offline')
      closeDriveroffline1()
      stopLiveLocation()

      const data = snapshot.data()
      const now = new Date()
      const lastOnlineAt = data?.last_online_at?.toDate?.()
      let totalTime = data?.total_online_time_today || 0

      if (lastOnlineAt) {
        const seconds = Math.floor(
          (now.getTime() - lastOnlineAt.getTime()) / 1000,
        )
        totalTime += seconds
      }

      await setDoc(
        driverRef,
        {
          is_online: '0',
          total_online_time_today: totalTime,
          lat: currentLatitude?.toString(),
          lng: currentLongitude?.toString(),
        },
        { merge: true },
      )
    } catch (err) {
      setIsOnline(true)
      setStatus('online')

      if (driverId) {
        startLiveLocation(driverId, selfDriver)
      }

      notificationHelper('', translateData?.failedToGoOffline, 'error')
    } finally {
      setOfflineLoading(false)
    }
  }
  const closeDriveroffline = () => {
    bottomSheetOfflineRef.current?.close()
    setIsBottomSheetOfflineOpen(false)
    setStatus('online')
  }
  const closeDriveroffline1 = () => {
    bottomSheetOfflineRef.current?.close()
    setIsBottomSheetOfflineOpen(false)
    setStatus('offline')
  }

  const fetchTime = async () => {
    if (!selfDriver?.id) return
    const snap = await getDoc(doc(db, 'driverTrack', selfDriver.id.toString()))
    const seconds = snap?.data()?.total_online_time_today || 0
    setTotalOnlineSeconds(seconds)
  }
  const formatSecondsToHHMM = (totalSeconds: any) =>
    `${Math.floor(totalSeconds / 3600)
      .toString()
      .padStart(2, '0')}:${Math.floor((totalSeconds % 3600) / 60)
        .toString()
        .padStart(2, '0')}`

  const sosSheet = () => {
    if (isBottomSheetSOSOpen) {
      bottomSheetSOSRef.current?.close()
      setIsBottomSheetSOSOpen(false)
    } else {
      bottomSheetSOSRef.current?.present()
      setIsBottomSheetSOSOpen(true)
    }
  }

  const filterSheet = () => {
    if (isBottomSheetfilterOpen) {
      bottomSheetFilterRef.current?.close()
      setIsBottomSheetfilterOpen(false)
    } else {
      bottomSheetFilterRef.current?.present()
      setIsBottomSheetfilterOpen(true)
    }
  }

  const handelCall = () => {
    bottomSheetModalRef.current?.close()
    bottomSheetOfflineRef.current?.close()
    if (isBottomSheetSOSOpen) {
      cancelbottomSheetRef.current?.close()
      setIsBottomSheetCancelOpen(false)
    } else {
      cancelbottomSheetRef.current?.present()
      setIsBottomSheetCancelOpen(true)
    }
  }

  const toggleHeader = () => {
    Vibration.vibrate(52)
    setViewMode(prev => (prev === 'amount' ? 'time' : 'amount'))
    fetchTime()
  }

  const sosCall = (details: any) => {
    const payload = {
      sos_id: details?.id,
      location_coordinates: { lat: currentLatitude, lng: currentLongitude },
    }

    setLoadingId(details?.id)
    dispatch(sosAlertGet(payload))
      .unwrap()
      .then(async () => {
        Linking.openURL(`tel:${details?.phone}`)
      })
      .catch(err => { })
      .finally(() => {
        setLoadingId(null)
      })
  }

  useEffect(() => {
    if (rides?.length > 0 && !isBottomSheetOpen) {
      bottomSheetModalRef.current?.present()
      setIsBottomSheetOpen(true)
    }
  }, [rides, isBottomSheetOpen])

  const handleFocusPress = () => {
    mapRef.current?.focusToCurrentLocation()
  }

  useEffect(() => {
    PushNotification.createChannel({
      channelId: 'ride-requests',
      channelName: 'Ride Requests',
      soundName: 'default',
      importance: 4,
      vibrate: true,
    })
  }, [])

  const timeoutRef = useRef<NodeJS.Timeout | null>(null)

  const stopNotificationSound: any = useCallback(() => {
    if (timeoutRef.current) clearTimeout(timeoutRef.current)
    timeoutRef.current = null

    if (soundInstanceRef.current) {
      soundInstanceRef.current.stop(() => {
        soundInstanceRef.current?.release()
        soundInstanceRef.current = null
      })
    }

    Vibration.cancel()
    isRingtonePlayingRef.current = false
  }, [])

  const playNotificationSound = useCallback(() => {
    if (isRingtonePlayingRef.current) return

    isRingtonePlayingRef.current = true
    Vibration.vibrate([0, 1000, 500, 1000], true)

    const sound = new Sound(
      'https://res.cloudinary.com/dwsbvqylx/video/upload/v1748766805/mixkit-urgent-simple-tone-loop-2976_ip7rwc.wav',
      null,
      error => {
        if (error) {
          stopNotificationSound()
          return
        }

        soundInstanceRef.current = sound
        sound.setNumberOfLoops(-1)
        sound.play(success => {
          if (!success) stopNotificationSound()
        })

        timeoutRef.current = setTimeout(() => stopNotificationSound(), 5000)
      },
    )
  }, [stopNotificationSound])

  useFocusEffect(
    useCallback(() => {
      if (!driverId) {
        setLoading(false)
        return
      }

      let unsubscribeDriver: (() => void) | null = null
      let rideDocsUnsubscribers: (() => void)[] = []
      let currentRideIds: string[] = []

      const driverDocRef = doc(db, 'driver_ride_requests', driverId.toString())

      unsubscribeDriver = onSnapshot(
        driverDocRef,
        async driverSnapshot => {
          if (!driverSnapshot.exists()) {
            rideDocsUnsubscribers.forEach(unsub => unsub())
            rideDocsUnsubscribers = []
            currentRideIds = []
            setRides([])
            setLoading(false)
            return
          }

          const rideRequestsArray: { id: string }[] =
            driverSnapshot.data()?.ride_requests || []

          const newRideIds = rideRequestsArray
            .map(r => r.id?.toString())
            .filter(Boolean)

          const addedRideIds = newRideIds.filter(
            id => !currentRideIds.includes(id),
          )
          if (addedRideIds.length > 0) {
            playNotificationSound()
          }

          currentRideIds = newRideIds

          if (rideRequestsArray.length === 0) {
            rideDocsUnsubscribers.forEach(unsub => unsub())
            rideDocsUnsubscribers = []
            setRides([])
            setLoading(false)
            return
          }

          rideDocsUnsubscribers.forEach(unsub => unsub())
          rideDocsUnsubscribers = []

          const allRides: any[] = []

          rideRequestsArray.forEach((rideReq: any) => {
            const rideDocRef = doc(db, 'ride_requests', rideReq.id)
            const unsub = onSnapshot(
              rideDocRef,
              rideSnapshot => {
                if (rideSnapshot.exists()) {
                  const rideData = {
                    id: rideSnapshot.id,
                    ...rideSnapshot.data(),
                  }
                  const index = allRides.findIndex(r => r.id === rideData.id)
                  if (index > -1) {
                    allRides[index] = rideData
                  } else {
                    allRides.push(rideData)
                  }
                  setRides([...allRides])
                  setLoading(false)
                }
              },
              error => { },
            )
            rideDocsUnsubscribers.push(unsub)
          })
        },
        error => {
          setLoading(false)
        },
      )

      return () => {
        if (unsubscribeDriver) unsubscribeDriver()
        rideDocsUnsubscribers.forEach(unsub => unsub())
        stopNotificationSound()
      }
    }, [driverId, playNotificationSound, stopNotificationSound]),
  )
  const scaleAnim = useRef(new Animated.Value(1)).current
  const filterOptions = useFilterOptions()

  const runOnlineAnimation = () => {
    setShowOnline(true)
    setTimeout(() => {
      setShowOnline(false)
      SetOn(false)
    }, 2000)
    Animated.loop(
      Animated.sequence([
        Animated.timing(scaleAnim, {
          toValue: 1.2,
          duration: 400,
          useNativeDriver: true,
        }),
        Animated.timing(scaleAnim, {
          toValue: 1,
          duration: 400,
          useNativeDriver: true,
        }),
      ]),
    ).start()
  }
  useEffect(() => {
    return () => stopNotificationSound()
  }, [stopNotificationSound])

  const FallbackImage = ({ uri, style }) => {
    const [imgUri, setImgUri] = React.useState(uri)

    return (
      <Image
        source={imgUri ? { uri: imgUri } : Images.sos}
        style={style}
        onError={() => setImgUri(null)}
        resizeMode="contain"
        tintColor={isDark ? appColors.white : appColors.black}
      />
    )
  }
  const [selectedTypes, setSelectedTypes] = useState<string[]>([])
  const webViewRef = useRef<any>(null)

  const handleApplyFilter = () => {
    ;['petrol', 'ev', 'garage', 'parking', 'carwash'].forEach(type => {
      webViewRef.current?.injectJavaScript(`removeNearbyPlaces('${type}');`)
    })

    if (selectedTypes.length === 0) {
      bottomSheetFilterRef.current?.dismiss()
      return
    }

    selectedTypes.forEach(type => {
      webViewRef.current?.injectJavaScript(`showNearbyPlaces('${type}');`)
    })

    bottomSheetFilterRef.current?.dismiss()
  }


  return (
    <View style={{ flex: 1 }}>
      <MapScreen
        ref={mapRef}
        markerIcon={selfDriver?.vehicle_info?.vehicle_type_map_icon_url}
        selfDriver={selfDriver}
        zoneValue={zoneValue}
        isBottomSheetSOSOpen={isBottomSheetSOSOpen}
        isBottomSheetCancelOpen={isBottomSheetCancelOpen}
        isBottomSheetOpen={isBottomSheetOpen}
        isBottomSheetOfflineOpen={isBottomSheetOfflineOpen}
        isBottomSheetfilterOpen={isBottomSheetfilterOpen}
        filterSheet={filterSheet}
        webViewRef={webViewRef}
        selectedTypes={selectedTypes}
        setSelectedTypes={setSelectedTypes}
        latitude={currentLatitude}
        longitude={currentLongitude}
      />

      <Modal
        visible={noservice}
        transparent
        animationType="fade"
        onRequestClose={() => setNodervice(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <Text style={styles.title}>Service Not Available</Text>
            <Text style={styles.message}>
              Sorry, this area is currently not serviceable.
            </Text>
            <TouchableOpacity
              style={styles.buttonModel}
              onPress={() => BackHandler.exitApp()}
            >
              <Text style={styles.buttonTextModel}>Exit</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>

      <Modal
        visible={lowBalance}
        transparent
        animationType="fade"
      >
        <LowBalance low={walletBalance < minWalletBalance ? false : true} setLowBalance={setLowBalance} />
      </Modal>

      <View
        style={{
          flexDirection: rtl ? 'row-reverse' : 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          height: windowHeight(11),
          backgroundColor: isDark ? appColors.primaryFont : appColors.white,
          borderBottomEndRadius: windowWidth(5),
          borderBottomStartRadius: windowWidth(5),
          paddingHorizontal: windowWidth(4),
        }}
      >
        <View
          style={{
            flexDirection: rtl ? 'row-reverse' : 'row',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor:
              on && status === 'offline' ? appColors.black : appColors.black,
            height: windowHeight(6),
            borderRadius: windowHeight(8.5),
            paddingHorizontal: windowWidth(5.3),
          }}
        >
          <TouchableOpacity
            onPress={() => toggleHeader()}
            activeOpacity={0.9}
            style={{
              flexDirection: rtl ? 'row-reverse' : 'row',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: appColors.black,
              height: windowHeight(5.5),
              borderRadius: windowHeight(8.5),
            }}
          >
            {viewMode === 'time' ? (
              <Icons.Clock color={appColors.white} />
            ) : (
              <TouchableOpacity
                onPress={e => {
                  e.stopPropagation()
                  setIsAmountVisible(prev => !prev)
                }}
              >
                {isAmountVisible ? <Icons.Eye /> : <Icons.WalletEyeClose />}
              </TouchableOpacity>
            )}

            <View
              style={{
                height: windowHeight(1.5),
                width: windowHeight(0.1),
                backgroundColor: appColors.white,
                marginHorizontal: windowWidth(1.5),
              }}
            />

            <Text style={styles.text}>
              {viewMode === 'time'
                ? `${formatSecondsToHHMM(totalOnlineSeconds)} hrs`
                : isAmountVisible
                  ? TodayIncome
                  : maskedAmount}
            </Text>
          </TouchableOpacity>
        </View>

        <View
          style={{
            backgroundColor: isDark ? appColors.bgDark : appColors.lightGray,
            width: windowWidth(28),
            height: windowHeight(6),
            borderRadius: windowWidth(25),
            flexDirection: viewRtlStyle,
            alignItems: 'center',
            paddingHorizontal: windowWidth(2.5),
          }}
        >
          <TouchableOpacity
            onPress={() => navigate('Notification')}
            activeOpacity={0.9}
            style={{
              height: windowHeight(4.5),
              width: windowHeight(4.5),
              backgroundColor: isDark ? appColors.primaryFont : appColors.white,
              borderRadius: windowHeight(15),
              alignItems: 'center',
              justifyContent: 'center',
              borderColor: isDark ? appColors.darkborder : appColors.white,
              borderWidth: 1,
            }}
          >
            <Icons.Notification
              color={isDark ? appColors.white : appColors.primaryFont}
            />
          </TouchableOpacity>
          <View
            style={{
              height: windowHeight(3),
              width: windowWidth(0.45),
              backgroundColor: isDark ? appColors.darkborder : appColors.border,
              marginHorizontal: windowWidth(2),
            }}
          />

          <TouchableOpacity
            activeOpacity={0.9}
            onPress={() => navigate('ProfileSetting')}
          >
            {selfDriver?.profile_image_url ? (
              <Image
                style={{
                  backgroundColor: appColors.primary,
                  height: windowHeight(4.5),
                  width: windowHeight(4.5),
                  borderRadius: windowHeight(5),
                }}
                source={{
                  uri: selfDriver?.profile_image_url,
                }}
              />
            ) : (
              <View
                style={{
                  alignItems: 'center',
                  justifyContent: 'center',
                  width: windowHeight(4.5),
                  height: windowHeight(4.5),
                  backgroundColor: isDark ? appColors.white : appColors.black,
                  borderRadius: windowHeight(74),
                }}
              >
                <Text
                  style={{
                    color: isDark ? appColors.black : appColors.white,
                    fontFamily: appFonts.bold,
                    fontSize: fontSizes.FONT5,
                  }}
                >
                  {char}
                </Text>
              </View>
            )}
          </TouchableOpacity>
        </View>
      </View>

      <View
        style={[
          styles.box,
          {
            flexDirection: viewRtlStyle,
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
          },
        ]}
      >
        <TouchableOpacity
          style={[
            rtl ? styles.smallBox1 : styles.smallBox,
            {
              backgroundColor:
                status === 'online'
                  ? appColors.online
                  : isDark
                    ? appColors.primaryFont
                    : appColors.white,
            },
          ]}
          onPress={() => toggleSwitch('online')}
          activeOpacity={0.7}
        >
          <Text
            style={[
              styles.status,
              {
                color:
                  status === 'online' ? appColors.white : appColors.iconColor,
              },
            ]}
          >
            {translateData?.online}
          </Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={[
            rtl ? styles.smallBox : styles.smallBox1,
            {
              backgroundColor:
                status === 'offline'
                  ? appColors.offline
                  : isDark
                    ? appColors.primaryFont
                    : appColors.white,
            },
          ]}
          onPress={() => toggleSwitch('offline')}
          activeOpacity={0.7}
        >
          <Text
            style={[
              styles.status,
              {
                color:
                  status === 'offline' ? appColors.white : appColors.iconColor,
              },
            ]}
          >
            {translateData?.homeOflineText}
          </Text>
        </TouchableOpacity>
      </View>

      {!isBottomSheetOpen &&
        !isBottomSheetOfflineOpen &&
        !isBottomSheetSOSOpen &&
        !isBottomSheetCancelOpen &&
        !isBottomSheetfilterOpen && (
          <View
            style={{
              position: 'absolute',
              left: windowHeight(2),
              height: windowHeight(7),
              bottom: windowHeight(10),
              [rtl ? 'right' : 'left']: windowWidth(4),
              zIndex: 1,
              justifyContent: 'center',
            }}
          >
            <TouchableOpacity
              activeOpacity={0.9}
              style={{
                height: windowHeight(6.5),
                width: windowHeight(6.5),
                borderRadius: windowHeight(6.5),
                backgroundColor: isDark
                  ? appColors.primaryFont
                  : appColors.white,
                borderColor: isDark ? appColors.darkborder : appColors.loader,
                justifyContent: 'center',
                alignItems: 'center',
                borderWidth: windowHeight(0.25),
                alignSelf: 'flex-end',
              }}
              onPress={handlePresentModalPress}
            >
              <Icons.FillcarIcon
                color={isDark ? appColors.white : appColors.primaryFont}
              />
              {rides?.length > 0 && (
                <View
                  style={{
                    position: 'absolute',
                    top: windowHeight(1),
                    right: windowHeight(1),
                    height: windowHeight(1),
                    width: windowHeight(1),
                    backgroundColor: appColors.primaryFont,
                    borderRadius: 5,
                  }}
                />
              )}
            </TouchableOpacity>
          </View>
        )}

      <>
        {!isBottomSheetOpen &&
          !isBottomSheetOfflineOpen &&
          !isBottomSheetSOSOpen &&
          !isBottomSheetCancelOpen &&
          !isBottomSheetfilterOpen && (
            <View
              style={{
                position: 'absolute',
                left: windowHeight(2),
                height: windowHeight(7),
                bottom: rtl ? windowHeight(18) : windowHeight(17.5),
                [rtl ? 'left' : 'right']: windowWidth(4),
                zIndex: 1,
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <TouchableOpacity
                onPress={sosSheet}
                style={{
                  height: windowHeight(6.5),
                  width: windowHeight(6.5),
                  borderRadius: windowHeight(6.5),
                  backgroundColor: isDark
                    ? appColors.primaryFont
                    : appColors.white,
                  borderColor: isDark ? appColors.darkborder : appColors.loader,
                  justifyContent: 'center',
                  alignItems: 'center',
                  borderWidth: windowHeight(0.25),
                  alignSelf: 'flex-end',
                }}
              >
                <Icons.SOS />
              </TouchableOpacity>
            </View>
          )}
      </>
      <TouchableOpacity
        onPress={handleFocusPress}
        style={{
          position: 'absolute',
          bottom: rtl ? windowHeight(18) : windowHeight(10.5),
          height: windowHeight(6.5),
          width: windowHeight(6.5),
          borderRadius: windowHeight(6.5),
          borderWidth: windowHeight(0.25),
          borderColor: isDark ? appColors.darkborder : appColors.border,
          backgroundColor: isDark ? appColors.primaryFont : appColors.white,
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 0,
          marginLeft: windowWidth(82),
        }}
      >
        <Icons.LocationIcon
          color={isDark ? appColors.white : appColors.primaryFont}
        />
      </TouchableOpacity>

      {!isBottomSheetCancelOpen && !isBottomSheetOfflineOpen && (
        <BottomSheetModalProvider>
          <BottomSheetModal
            ref={bottomSheetModalRef}
            index={0}
            snapPoints={rides?.length >= 2 ? ['50%', '75%'] : ['58%']}
            onChange={handleSheetChanges}
            onDismiss={() => setIsBottomSheetOpen(false)}
            handleIndicatorStyle={{
              backgroundColor: appColors.primary,
              height: windowHeight(0.6),
              width: windowWidth(10),
              marginTop: windowHeight(0.2),
            }}
            containerStyle={{ borderRadius: windowWidth(5), paddingBottom: 88 }}
            backgroundStyle={{
              backgroundColor: isDark ? appColors.bgDark : appColors.white,
            }}
          >
            <BottomSheetView style={styles.contentContainer}>
              {rides?.length > 0 ? (
                <BottomSheetFlatList
                  data={[...rides]
                    .filter(
                      (ride: any) =>
                        ride?.rider_id && ride?.location_coordinates,
                    )
                    .sort((a: any, b: any) => {
                      const timeA = a.created_at?._seconds ?? 0
                      const timeB = b.created_at?._seconds ?? 0
                      return timeB - timeA
                    })}
                  keyExtractor={(item: any, index) =>
                    item?.id?.toString() || index.toString()
                  }
                  extraData={rides}
                  renderItem={({ item }) => {
                    return (
                      <UpcomingRide
                        ride={item}
                        ref={upcomingRideRef}
                        gotoRide={gotoRide}
                        gotoInfo={gotoInfo}
                        selectDriver={selectDriver}
                        onRideDeclined={onRideDeclined}
                        cancelbottomSheetRef={cancelbottomSheetRef}
                        cancel={cancel}
                        handelCall={handelCall}
                        bottomSheetRef={bottomSheetRef}
                      />
                    )
                  }}
                  ListEmptyComponent={
                    <Text style={styles.noRideText}>
                      {translateData.noUpcomingrides}
                    </Text>
                  }
                />
              ) : (
                <View style={styles.noRideContainer}>
                  <Image
                    source={isDark ? Images.noRideDark : Images.noRide}
                    style={styles.noRideImg}
                    resizeMode="contain"
                  />
                  <Text style={styles.noRideText}>
                    {translateData.waitNewRide}
                  </Text>
                </View>
              )}
            </BottomSheetView>
          </BottomSheetModal>
        </BottomSheetModalProvider>
      )}
      <BottomSheetModalProvider>
        <BottomSheetModal
          ref={bottomSheetOfflineRef}
          index={0}
          snapPoints={['30%']}
          onChange={handleSheetChanges}
          onDismiss={() => setIsBottomSheetOfflineOpen(false)}
          style={{ zIndex: 2 }}
          handleIndicatorStyle={{
            backgroundColor: appColors.primary,
            height: windowHeight(0.6),
            width: windowWidth(10),
            marginTop: windowHeight(0.2),
          }}
          containerStyle={{ borderRadius: windowWidth(5) }}
          backgroundStyle={{
            backgroundColor: isDark ? appColors.bgDark : appColors.white,
          }}
        >
          <BottomSheetView style={styles.contentContainer}>
            <View>
              <Text
                style={{
                  color: isDark ? appColors.white : appColors.primaryFont,
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT4HALF,
                  textAlign: 'center',
                  marginBottom: windowHeight(5),
                }}
              >
                {translateData.offlineMsg}
              </Text>
              <View
                style={{
                  flexDirection: 'row',
                  justifyContent: 'space-between',
                }}
              >
                <View style={{ width: windowWidth(46) }}>
                  <Button
                    title={translateData.cancel}
                    backgroundColor={
                      isDark ? appColors.darkThemeSub : appColors.graybackground
                    }
                    onPress={closeDriveroffline}
                    color={isDark ? appColors.white : appColors.black}
                  />
                </View>
                <View style={{ width: windowWidth(46) }}>
                  <Button
                    title={translateData.confirm}
                    backgroundColor={appColors.red}
                    color={appColors.white}
                    onPress={driverOffline}
                    loading={offlineloading}
                  />
                </View>
              </View>
            </View>
          </BottomSheetView>
        </BottomSheetModal>
      </BottomSheetModalProvider>

      <BottomSheetModalProvider>
        <BottomSheetModal
          ref={bottomSheetSOSRef}
          index={0}
          snapPoints={['62%']}
          onChange={handleSheetChanges}
          onDismiss={() => setIsBottomSheetSOSOpen(false)}
          style={{ zIndex: 2 }}
          handleIndicatorStyle={{
            backgroundColor: appColors.primary,
            height: windowHeight(0.6),
            width: windowWidth(10),
            marginTop: windowHeight(0.2),
          }}
          containerStyle={{ borderRadius: windowWidth(5) }}
          backgroundStyle={{
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
          }}
        >
          <BottomSheetView style={styles.contentContainer}>
            <View
              style={{
                backgroundColor: isDark
                  ? appColors.darkborder
                  : appColors.white,
                marginTop: windowHeight(2),
                borderRadius: windowWidth(5),
                borderWidth: windowWidth(0.45),
                borderColor: isDark ? appColors.darkborder : appColors.loader,
              }}
            >
              <Text
                style={{
                  color: isDark ? appColors.white : appColors.primaryFont,
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT4HALF,
                  textAlign: textRtlStyle,
                  marginBottom: windowHeight(1.5),
                  marginTop: windowHeight(2.3),
                  marginHorizontal: windowWidth(4),
                }}
              >
                {translateData.keepSafe}
              </Text>
              <FlatList
                data={sosData?.data}
                keyExtractor={(item, index) => index.toString()}
                contentContainerStyle={{ paddingBottom: windowHeight(2) }}
                renderItem={({ item, index }) => {
                  const isLastItem = index === sosData?.data?.length - 1

                  return (
                    <View>
                      <TouchableOpacity
                        style={{
                          paddingTop: windowHeight(1.5),
                          paddingBottom: isLastItem ? 0 : windowHeight(1.5),
                          paddingHorizontal: windowWidth(4),
                        }}
                        onPress={() => sosCall(item)}
                      >
                        <View
                          style={{
                            flexDirection: viewRtlStyle,
                            alignItems: 'center',
                          }}
                        >
                          <View
                            style={{
                              height: windowHeight(5.5),
                              width: windowHeight(5.5),
                              borderRadius: windowHeight(5.5),
                              borderWidth: windowWidth(0.45),
                              borderColor: isDark
                                ? appColors.primaryFont
                                : appColors.lightGray,
                              alignItems: 'center',
                              justifyContent: 'center',
                            }}
                          >
                            <FallbackImage
                              uri={item?.sos_image_url}
                              style={styles.sosImage}
                            />
                          </View>
                          <Text
                            style={{
                              color: isDark ? appColors.white : appColors.black,
                              fontFamily: appFonts.regular,
                              fontSize: fontSizes.FONT4HALF,
                              width: windowWidth(68),
                              marginHorizontal: windowWidth(4),
                            }}
                          >
                            {item?.title ?? 'No Title'}
                          </Text>
                          {loadingId === item?.id && (
                            <ActivityIndicator
                              size={'small'}
                              color={appColors.primary}
                            />
                          )}
                        </View>
                      </TouchableOpacity>
                      {!isLastItem && (
                        <View
                          style={{
                            height: windowHeight(0.6),
                            width: '100%',
                            backgroundColor: isDark
                              ? appColors.primaryFont
                              : appColors.lightGray,
                          }}
                        />
                      )}
                    </View>
                  )
                }}
              />
            </View>
          </BottomSheetView>
        </BottomSheetModal>
      </BottomSheetModalProvider>

      <BottomSheetModalProvider>
        <BottomSheet
          ref={bottomSheetRef}
          index={-1}
          snapPoints={snapPoints}
          enablePanDownToClose
          handleIndicatorStyle={{
            backgroundColor: appColors.primary,
            width: '13%',
          }}
          backgroundStyle={{
            backgroundColor: isDark ? appColors.bgDark : appColors.white,
          }}
        >
          <View style={{ padding: 20 }}>
            <Text style={{ fontSize: 18, fontWeight: '600', marginBottom: 10 }}>
              {translateData.exitMsg}
            </Text>
            <TouchableOpacity
              onPress={handleExit}
              style={{ marginVertical: 10 }}
            >
              <Text style={{ color: 'red', fontSize: 16 }}>
                {translateData.exit}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={handleCloseSheet}
              style={{ marginVertical: 10 }}
            >
              <Text style={{ fontSize: 16 }}>{translateData.cancel}</Text>
            </TouchableOpacity>
          </View>
        </BottomSheet>
      </BottomSheetModalProvider>

      <BottomSheetModalProvider>
        <BottomSheetModal
          ref={cancelbottomSheetRef}
          index={0}
          snapPoints={['32%']}
          onChange={handleSheetChanges}
          onDismiss={() => setIsBottomSheetOpen(false)}
          handleIndicatorStyle={{
            backgroundColor: appColors.primary,
            width: '13%',
          }}
          backgroundStyle={{
            backgroundColor: isDark ? appColors.bgDark : appColors.white,
          }}
          style={{ zIndex: 2 }}
        >
          <BottomSheetView
            style={[
              styles.contentContainer1,
              { borderColor: isDark ? appColors.darkborder : appColors.border },
            ]}
          >
            <View style={{ padding: 20, paddingTop: windowHeight(2) }}>
              <Text
                style={{
                  fontSize: 16,
                  fontFamily: appFonts.semiBold,
                  marginBottom: 15,
                  textAlign: 'center',
                  color: isDark ? appColors.white : appColors.black,
                }}
              >
                {translateData?.areyousure}
              </Text>
              <View
                style={{
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  flexDirection: rtl ? 'row-reverse' : 'row',
                }}
              >
                <TouchableOpacity
                  onPress={handleCloseSheet1}
                  style={{
                    height: windowHeight(5.5),
                    width: windowWidth(35),
                    backgroundColor: isDark
                      ? appColors.primaryFont
                      : appColors.lightGray,
                    alignItems: 'center',
                    justifyContent: 'center',
                    borderRadius: windowWidth(95),
                  }}
                >
                  <Text
                    style={{
                      color: isDark ? appColors.white : appColors.black,
                      fontSize: 16,
                    }}
                  >
                    {translateData.cancel}
                  </Text>
                </TouchableOpacity>

                <TouchableOpacity
                  onPress={handleExit1}
                  style={{
                    height: windowHeight(5.5),
                    width: windowWidth(35),
                    backgroundColor: isDark ? appColors.white : appColors.black,
                    alignItems: 'center',
                    justifyContent: 'center',
                    borderRadius: windowWidth(55),
                  }}
                >
                  <Text
                    style={{
                      color: isDark ? appColors.black : appColors.white,
                      fontSize: 16,
                    }}
                  >
                    {translateData?.confirm}
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
          </BottomSheetView>
        </BottomSheetModal>
      </BottomSheetModalProvider>

      <BottomSheetModalProvider>
        <BottomSheetModal
          ref={filterbottomSheetRef}
          index={0}
          snapPoints={['32%']}
          onChange={handleSheetChanges}
          onDismiss={() => setIsBottomSheetOpen(false)}
          handleIndicatorStyle={{
            backgroundColor: appColors.primary,
            width: '13%',
          }}
          backgroundStyle={{
            backgroundColor: isDark ? appColors.bgDark : appColors.white,
          }}
          style={{ zIndex: 2 }}
        >
          <BottomSheetView style={styles.contentContainer}>
            <View style={{ padding: 20, paddingTop: windowHeight(2) }}>
              <Text
                style={{
                  fontSize: 16,
                  fontFamily: appFonts.medium,
                  marginBottom: 15,
                }}
              >
                {translateData?.areyousure}
              </Text>
            </View>
          </BottomSheetView>
        </BottomSheetModal>
      </BottomSheetModalProvider>

      <BottomSheetModalProvider>
        <BottomSheetModal
          ref={bottomSheetFilterRef}
          index={0}
          snapPoints={['40%']}
          onChange={handleSheetChanges}
          onDismiss={() => setIsBottomSheetfilterOpen(false)}
          style={{ zIndex: 2 }}
          handleIndicatorStyle={{
            backgroundColor: appColors.primary,
            height: windowHeight(0.6),
            width: windowWidth(10),
            marginTop: windowHeight(0.2),
          }}
          containerStyle={{ borderRadius: windowWidth(5) }}
          backgroundStyle={{
            backgroundColor: isDark ? appColors.primaryFont : appColors.white,
          }}
        >
          <BottomSheetView style={styles.contentContainer}>
            <View
              style={[
                styles.con,
                {
                  backgroundColor: isDark
                    ? appColors.darkborder
                    : appColors.white,
                  borderColor: isDark ? appColors.darkborder : appColors.loader,
                },
              ]}
            >
              <FlatList
                data={filterOptions}
                keyExtractor={(item, index) => index.toString()}
                style={{ paddingHorizontal: windowWidth(1.2) }}
                renderItem={({ item }) => {
                  return (
                    <TouchableOpacity
                      onPress={() => {
                        if (selectedTypes.includes(item.id)) {
                          setSelectedTypes(prev =>
                            prev.filter(t => t !== item.id),
                          )
                        } else {
                          setSelectedTypes(prev => [...prev, item.id])
                        }
                      }}
                      style={{
                        height: windowHeight(5),
                        marginVertical: windowHeight(0.7),
                        backgroundColor: isDark
                          ? appColors.primaryFont
                          : appColors.lightGray,
                        borderRadius: windowWidth(25),
                        width:
                          item.id === 'ev' ? windowWidth(35) : windowWidth(28),
                        marginHorizontal: windowWidth(0.6),
                        flexDirection: viewRtlStyle,
                        alignItems: 'center',
                        paddingHorizontal: windowWidth(3),
                      }}
                    >
                      <View
                        style={{
                          flexDirection: viewRtlStyle,
                          alignItems: 'center',
                          justifyContent: 'center',
                          height: windowHeight(2.5),
                          width: windowHeight(2.5),
                          backgroundColor: selectedTypes.includes(item.id)
                            ? appColors.black
                            : isDark
                              ? appColors.primaryFont
                              : appColors.white,
                          borderWidth: windowWidth(0.35),
                          borderRadius: windowWidth(1.3),
                          paddingTop: windowHeight(0.2),
                          borderColor: selectedTypes.includes(item.id)
                            ? appColors.black
                            : isDark
                              ? appColors.darkborder
                              : appColors.loader,
                        }}
                      >
                        {selectedTypes.includes(item.id) && (
                          <Icons.Check
                            color={isDark ? appColors.white : appColors.white}
                          />
                        )}
                      </View>
                      <Text
                        style={[
                          styles.label,
                          {
                            color: isDark ? appColors.white : appColors.black,
                            textAlign: textRtlStyle,
                          },
                        ]}
                      >
                        {item.label}
                      </Text>
                    </TouchableOpacity>
                  )
                }}
                numColumns={3}
              />
              <View
                style={{
                  width: '100%',
                  marginVertical: windowHeight(2),
                  marginBottom: windowHeight(1),
                }}
              >
                <Button
                  title={translateData?.apply}
                  backgroundColor={isDark ? appColors.white : appColors.black}
                  color={isDark ? appColors.black : appColors.white}
                  onPress={handleApplyFilter}
                />
              </View>
            </View>
          </BottomSheetView>
        </BottomSheetModal>
      </BottomSheetModalProvider>
    </View>
  )
}
