import {
  FlatList,
  Image,
  Text,
  TouchableOpacity,
  View,
  ActivityIndicator,
  Linking,
} from 'react-native'
import React, { useState } from 'react'
import Images from '../../../utils/images/images'
import { styles } from './style'
import {
  Button,
  LineContainer,
  LocationDetails,
} from '../../../commonComponents'
import { useValues } from '../../../utils/context'
import Icons from '../../../utils/icons/icons'
import { useSelector } from 'react-redux'
import { useNavigation, useTheme } from '@react-navigation/native'
import appColors from '../../../theme/appColors'
import appFonts from '../../../theme/appFonts'
import { LoaderRide } from './loaderRide'
import {
  fontSizes,
  windowHeight,
  windowWidth,
} from '../../../theme/appConstant'
import { apiformatDates } from '../../../utils/functions'
import { useAppNavigation } from '../../../utils/navigation'

export default function RideContainer({ status }) {
  const { navigate } = useNavigation<any>()
  const { viewRtlStyle, textRtlStyle, isDark } = useValues()
  const { colors } = useTheme()
  const { rideGets } = useSelector(state => state.ride)
  const { allVehicle } = useSelector(state => state.vehicleType)
  const { translateData } = useSelector(state => state.setting)
  const [page, setPage] = useState(1)
  const [loading, setLoading] = useState(false)
  const [hasMoreData, setHasMoreData] = useState(true)
  const { zoneValue } = useSelector(state => state.zoneUpdate)
  const acceptedRides = rideGets?.data?.filter(ride => {
    const rideStatus = ride?.ride_status?.slug?.toLowerCase()
    const categorySlug = ride?.service_category?.name?.toLowerCase()

    if (!rideStatus) return false

    if (Array.isArray(status)) {
      return status.includes(rideStatus)
    }

    const currentStatus = status?.toLowerCase()?.trim()

    if (currentStatus === 'schedule') {
      return categorySlug === 'schedule' && rideStatus !== 'cancelled'
    }

    if (currentStatus === 'accepted') {
      return (
        categorySlug !== 'schedule' &&
        rideStatus !== 'completed' &&
        rideStatus !== 'cancelled'
      )
    }

    return rideStatus === currentStatus
  })

  const statusMapping = {
    accepted: {
      text: 'Pending',
      color: appColors.completeColor,
    },
    started: {
      text: 'Active',
      color: appColors.activeColor,
    },
    schedule: {
      text: 'Scheduled',
      color: appColors.scheduleColor,
    },
    cancelled: {
      text: 'Cancel',
      color: appColors.alertRed,
    },
    completed: {
      text: 'Completed',
      color: appColors.primary,
    },
    arrived: {
      text: 'Pending',
      color: appColors.completeColor,
    },
  }
  const paginatedData = acceptedRides?.slice(0, page * 5) || []

  const gotoMessage = item => {
    navigate('Chat', {
      driverId: item?.driver?.id,
      riderId: item?.rider?.id,
      rideId: item?.id,
      riderName: item?.rider?.name,
      riderImage: item?.rider?.profile_image?.original_url,
    })
  }

  const gotoCall = item => {
    const phoneNumber = item?.driver?.phone
    Linking.openURL(`tel:${phoneNumber}`)
  }

  const loadMoreData = () => {
    if (!loading && hasMoreData) {
      setLoading(true)
      if (paginatedData.length < acceptedRides?.length) {
        setPage(prevPage => prevPage + 1)
      } else {
        setHasMoreData(false)
      }
      setLoading(false)
    }
  }

  const handlePress = (selectedItem, vehicleData) => {
    let rideStatus = statusMapping[selectedItem.ride_status.slug]?.text

    navigate('PendingDetails', {
      item: selectedItem,
      vehicleDetail: vehicleData,
      rideStatus: rideStatus,
    })
  }

  const renderItem = ({ item }) => {
    const { vehicle_type_id } = item.vehicle_type_id || {}

    const vehicleData = Array.isArray(allVehicle)
      ? allVehicle.find(vehicle => vehicle?.id == vehicle_type_id)
      : undefined

    const formattedDate = apiformatDates(item.created_at)
    const hasProfileImage = !!item?.rider?.driver_profile_image_url

    return (
      <TouchableOpacity
        style={[
          styles.rideInfoContainer,
          {
            backgroundColor: colors.card,
            borderColor: colors.border,
          },
        ]}
        onPress={() => handlePress(item, vehicleData)}
      >
        <View>
          <View>
            <View
              style={{
                justifyContent: 'space-between',
                alignItems: 'center',
                flexDirection: viewRtlStyle,
                marginHorizontal: windowWidth(4),
              }}
            >
              <View
                style={[
                  styles.tripTextContainer,
                  { backgroundColor: colors.background },
                ]}
              >
                <Text
                  style={[
                    styles.tripIDText,
                    {
                      color: isDark ? appColors.white : appColors.primaryFont,
                      textAlign: textRtlStyle,
                    },
                  ]}
                >
                  #{item?.ride_number}
                </Text>
              </View>
              <View
                style={[styles.iconContainer1, { flexDirection: viewRtlStyle }]}
              >
                <View
                  style={[
                    styles.containerIcon,
                    { flexDirection: viewRtlStyle },
                  ]}
                >
                  <View style={styles.calanderSmall}>
                    <Icons.CalanderSmall />
                  </View>
                  <Text style={styles.tripDateText}>{formattedDate.date}</Text>
                </View>
                <View
                  style={[
                    styles.smallLine,
                    {
                      backgroundColor: isDark
                        ? appColors.darkThemeSub
                        : appColors.loader,
                    },
                  ]}
                />
                <View
                  style={[
                    styles.containerIcon,
                    { flexDirection: viewRtlStyle },
                  ]}
                >
                  <View style={styles.clock}>
                    <Icons.Clock />
                  </View>
                  <Text
                    style={[
                      styles.tripDateText,
                      { marginHorizontal: windowWidth(0.8) },
                    ]}
                  >
                    {formattedDate.time}
                  </Text>
                </View>
              </View>
            </View>

            <View
              style={[styles.line, { backgroundColor: colors.background }]}
            />
            <View
              style={{
                justifyContent: 'space-between',
                alignItems: 'center',
                flexDirection: viewRtlStyle,
                marginHorizontal: windowWidth(4),
              }}
            >
              <View
                style={[
                  styles.profileInfoContainer,
                  { flexDirection: viewRtlStyle },
                ]}
              >
                {hasProfileImage ? (
                  <Image
                    style={styles.profileImage}
                    source={{ uri: item.rider.driver_profile_image_url }}
                  />
                ) : (
                  <View
                    style={{
                      width: windowWidth(13.5),
                      height: windowWidth(13.5),
                      borderRadius: windowHeight(13.5),
                      backgroundColor: colors.text,
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}
                  >
                    <Text
                      style={{
                        fontSize: fontSizes.FONT5,
                        fontFamily: appFonts.bold,
                        color: isDark ? appColors.black : appColors.white,
                      }}
                    >
                      {item?.rider?.name?.charAt(0)?.toUpperCase() || 'D'}
                    </Text>
                  </View>
                )}

                <View
                  style={{
                    marginHorizontal: windowWidth(3),
                    width: '55%',
                    flexWrap: 'wrap',
                  }}
                >
                  <View
                    style={[
                      styles.profileTextContainer,
                      { flexDirection: viewRtlStyle, alignItems: 'center' },
                    ]}
                  >
                    <Text
                      style={[
                        styles.profileName,
                        {
                          color: isDark
                            ? appColors.white
                            : appColors.primaryFont,
                        },
                        { textAlign: textRtlStyle },
                      ]}
                    >
                      {item?.rider?.name}
                    </Text>
                    <View style={{ marginHorizontal: windowWidth(1) }}>
                      <Icons.Name />
                    </View>
                  </View>

                  <View
                    style={[
                      styles.carInfoContainer,
                      { flexDirection: viewRtlStyle },
                    ]}
                  >
                    <View style={{ flexDirection: 'row' }}>
                      {Array.from({ length: 5 }).map((_, index) => {
                        const fullStarThreshold = index + 1
                        const halfStarThreshold = index + 0.5
                        if (item?.driver?.rating_count >= fullStarThreshold) {
                          return <Icons.RatingStar key={index} />
                        } else if (
                          item?.rider?.rating_count >= halfStarThreshold
                        ) {
                          return <Icons.RatingHalfStar key={index} />
                        } else {
                          return <Icons.RatingEmptyStar key={index} />
                        }
                      })}
                    </View>
                    <View
                      style={[
                        {
                          flexDirection: viewRtlStyle,
                          marginHorizontal: windowWidth(3),
                        },
                      ]}
                    >
                      <Text
                        style={[
                          styles.rating_count,
                          {
                            color: isDark
                              ? appColors.white
                              : appColors.primaryFont,
                          },
                        ]}
                      >
                        {Number(item?.driver?.rating_count).toFixed(1)}
                      </Text>
                      <Text style={styles.reviews_count}>
                        ({item?.driver?.review_count})
                      </Text>
                    </View>
                  </View>
                </View>
              </View>

              <Text
                style={[
                  styles.tripCostText,
                  { textAlign: textRtlStyle, color: colors.text },
                ]}
              >
                {zoneValue?.currency_symbol}
                {item.total}
              </Text>
            </View>

            {item?.ride_status?.slug !== 'completed' &&
              item?.ride_status?.slug !== 'cancelled' && (
                <View
                  style={[
                    styles.acceptedContainer,
                    {
                      flexDirection: viewRtlStyle,
                      marginTop: windowHeight(1),
                      width: '90%',
                      marginHorizontal: windowWidth(5),
                    },
                  ]}
                >
                  <TouchableOpacity
                    activeOpacity={0.7}
                    style={[
                      styles.callContainer,
                      {
                        width: windowWidth(65),
                        alignItems: 'flex-start',
                        backgroundColor: isDark
                          ? appColors.black
                          : appColors.lightGray,
                      },
                    ]}
                    onPress={() => gotoMessage(item)}
                  >
                    <Text
                      style={{
                        fontFamily: appFonts.regular,
                        marginHorizontal: windowWidth(3),
                        color: appColors.iconColor,
                      }}
                    >
                      {translateData?.sendmsg}
                    </Text>
                  </TouchableOpacity>
                  <TouchableOpacity
                    activeOpacity={0.7}
                    style={[
                      styles.callContainer,
                      {
                        borderColor: colors.border,
                        backgroundColor: appColors.online,
                      },
                    ]}
                    onPress={() => gotoCall(item)}
                  >
                    <Icons.Call color={appColors.white} />
                  </TouchableOpacity>
                </View>
              )}
            <View
              style={[styles.line, { backgroundColor: colors.background }]}
            />

            <LocationDetails locationDetails={item.locations} item={item} />
            {(
              Array.isArray(status)
                ? status.includes('completed') || status.includes('cancelled')
                : status === 'completed' || status === 'cancelled'
            ) ? null : (
              <View style={{ marginBottom: windowHeight(2.5) }}>
                <Button
                  title={translateData?.pickupCustomer}
                  backgroundColor={colors.text}
                  color={isDark ? appColors.black : appColors.white}
                  onPress={() => handlePress(item, vehicleData)}
                />
              </View>
            )}
          </View>
        </View>
      </TouchableOpacity>
    )
  }

  return (
    <View style={styles.listContainer}>
      {loading && acceptedRides?.length > 0 ? (
        <LoaderRide />
      ) : !acceptedRides || acceptedRides.length === 0 ? (
        <View style={styles.noDataContainer}>
          <Image source={Images.noRides} style={styles.noDataImage} />
          <Text style={styles.noDataText}>{translateData.norideTitle}</Text>
          <Text style={styles.noDataDesc}>
            {translateData.norideDescription}
          </Text>
        </View>
      ) : (
        <>
          <FlatList
            data={paginatedData}
            scrollEnabled={true}
            keyExtractor={item => item.id.toString()}
            renderItem={renderItem}
            onEndReached={loadMoreData}
            onEndReachedThreshold={0.9}
            ListFooterComponent={
              loading && (
                <ActivityIndicator
                  size="large"
                  color={appColors.buttonBg}
                  style={{ marginTop: 10 }}
                />
              )
            }
          />
          <View style={styles.bottomView} />
        </>
      )}
    </View>
  )
}
