import {
  FlatList,
  Image,
  Linking,
  Text,
  TouchableOpacity,
  View,
  ActivityIndicator,
} from "react-native";
import React, { useEffect, useState, useMemo, useRef } from "react";
import Images from "@utils/images";
import { styles } from "./style";
import { commonStyles } from "../../../../styles/commonStyle";
import { useValues } from "@src/utils/context/index";
import {
  Calender,
  Call,
  Info,
  Location,
  Message,
  PickLocation,
  RatingEmptyStart,
  RatingHalfStar,
  RatingStar,
  SafetyCall,
  Star,
} from "@utils/icons";
import { useDispatch, useSelector } from "react-redux";
import { useTheme } from "@react-navigation/native";
import {
  appColors,
  appFonts,
  fontSizes,
  windowHeight,
  windowWidth,
} from "@src/themes";
import { useAppNavigation } from "@src/utils/navigation";
import { RideLoader } from "./rideLoader";
import { external } from "@src/styles/externalStyle";
import { apiformatDates } from "@src/utils/functions";
import { Button, notificationHelper } from "@src/commonComponent";
import { userRideLocation, vehicleTypeDataGet } from "@src/api/store/actions";
import { AppDispatch } from "@src/api/store";
import { FillCalender } from "@src/assets/icons/fillCalender";
import { UnfillClock } from "@src/assets/icons/unfillClock";
import { Name } from "@src/assets/icons/name";
import { HalfStar } from "@src/assets/icons/halfStar";
import { EmptyStar } from "@src/assets/icons/emptyStar";

export default function RideContainer({ status }: any) {
  const { navigate }: any = useAppNavigation();
  const {
    bgFullStyle,
    textColorStyle,
    viewRTLStyle,
    textRTLStyle,
    isDark,
    isRTL,
    iconColorStyle,
    Google_Map_Key,
  } = useValues();
  const { colors } = useTheme();
  const { rideDatas } = useSelector((state: any) => state.allRide);
  const { allVehicle } = useSelector((state: any) => state.vehicleType);
  const { translateData } = useSelector((state: any) => state.setting);
  const [hasMoreData, setHasMoreData] = useState(true);
  const [page, setPage] = useState(1);
  const [initialLoading, setInitialLoading] = useState(false);
  const [paginationLoading, setPaginationLoading] = useState(false);
  const prevStatusRef = useRef(status);
  const { zoneValue } = useSelector((state: any) => state.zone);
  const dispatch = useDispatch<AppDispatch>();

  useEffect(() => {
    if (prevStatusRef.current !== status) {
      setPage(1);
      setHasMoreData(true);
      prevStatusRef.current = status;
    }
  }, [status]);

  const acceptedRides = useMemo(() => {
    return rideDatas?.data?.filter((ride: any) => {
      const rideStatus = ride?.ride_status?.slug?.toLowerCase();
      const categorySlug = ride?.service_category?.name?.toLowerCase();
      const currentStatus = status?.toLowerCase()?.trim();

      if (!rideStatus) return false;

      if (currentStatus === "active_combined") {
        return (
          categorySlug !== "schedule" &&
          rideStatus !== "completed" &&
          rideStatus !== "cancelled" &&
          (rideStatus === "accepted" ||
            rideStatus === "started" ||
            rideStatus === "arrived")
        );
      }

      if (currentStatus === "past_combined") {
        return rideStatus === "completed" || rideStatus === "cancelled";
      }

      if (currentStatus === "schedule") {
        return categorySlug === "schedule";
      }
      if (currentStatus === "accepted") {
        return (
          categorySlug !== "schedule" &&
          rideStatus !== "completed" &&
          rideStatus !== "cancelled"
        );
      }
      return rideStatus === currentStatus;
    });
  }, [rideDatas?.data, status]);

  const statusMapping: any = {
    accepted: {
      text: "Pending",
      color: appColors.completeColor,
      backgroundColor: appColors.lightYellow,
    },
    started: {
      text: "Active",
      color: appColors.activeColor,
      backgroundColor: appColors.grayLight,
    },
    schedule: {
      text: "Scheduled",
      color: appColors.scheduleColor,
      backgroundColor: appColors.lightPink,
    },
    cancelled: {
      text: "Cancel",
      color: appColors.alertRed,
      backgroundColor: appColors.iconRed,
    },
    completed: {
      text: "Completed",
      color: appColors.primary,
      backgroundColor: appColors.selectPrimary,
    },
    arrived: {
      text: "Pending",
      color: appColors.completeColor,
      backgroundColor: appColors.lightYellow,
    },
  };
  useEffect(() => {
    if (rideDatas?.data) {
      if (rideDatas.data.length > 0) {
        setInitialLoading(false);
      } else {
        setInitialLoading(false);
      }
    } else {
      setInitialLoading(false);
    }
  }, [rideDatas]);

  const gotoMessage = (item: any) => {
    navigate("ChatScreen", {
      driverId: item?.driver?.id,
      riderId: item?.rider?.id,
      rideId: item?.id,
      driverName: item?.driver?.name,
      driverImage: item?.driver?.profile_image_url,
    });
  };

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

  const paginatedData = useMemo(
    () => acceptedRides?.slice(0, page * 5) || [],
    [acceptedRides, page]
  );

  const loadMoreData = () => {
    if (!paginationLoading && hasMoreData) {
      setPaginationLoading(true);
      setTimeout(() => {
        if (paginatedData.length < acceptedRides?.length) {
          setPage((prev) => prev + 1);
        } else {
          setHasMoreData(false);
        }
        setPaginationLoading(false);
      }, 1000);
    }
  };

  const handlePress = (selectedItem: any, vehicleData: any) => {
    let rideStatus =
      status === "Schedule"
        ? statusMapping[selectedItem?.service_category?.service_category_type]
          ?.text
        : statusMapping[selectedItem.ride_status.slug]?.text;
    navigate("PendingRideScreen", {
      item: selectedItem,
      vehicleDetail: vehicleData,
      rideStatus: rideStatus,
    });
  };

  const convertToCoords = async (address: any) => {
    try {
      const res = await fetch(
        `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
          address
        )}&key=${Google_Map_Key}`
      );
      const data = await res.json();
      if (data.status === "OK" && data.results.length > 0) {
        const { lat, lng } = data.results[0].geometry.location;
        return { latitude: lat, longitude: lng };
      } else {
        return null;
      }
    } catch (err) {
      console.error("Geocoding error:", err);
      return null;
    }
  };

  const convertStopsToCoords = async (stopList: any) => {
    const coordsArray = [];
    for (const stop of stopList) {
      try {
        const res = await fetch(
          `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
            stop
          )}&key=${Google_Map_Key}`
        );
        const data = await res.json();
        if (data.status === "OK" && data.results.length > 0) {
          const { lat, lng } = data.results[0].geometry.location;
          coordsArray.push({ latitude: lat, longitude: lng });
        } else {
          coordsArray.push(null);
        }
      } catch (err) {
        console.error("Stop geocoding error:", err);
        coordsArray.push(null);
      }
    }
    return coordsArray;
  };

  const gotoBook = async (item: any) => {
    const locations = item?.locations || [];
    const pickupLocation = locations[0] || null;
    const destination =
      locations.length > 1 ? locations[locations.length - 1] : null;
    const stops =
      locations.length > 2 ? locations.slice(1, locations.length - 1) : [];

    try {
      const pickupCoords = await convertToCoords(pickupLocation);
      const destinationCoords = await convertToCoords(destination);
      const stopCoords = await convertStopsToCoords(stops || []);
      const ride_number = item?.id;
      const res = await dispatch(userRideLocation({ ride_number })).unwrap();
      const zoneValue = res?.data?.[0];

      const rawLocations = [
        pickupCoords,
        stopCoords[0],
        stopCoords[1],
        stopCoords[2],
        destinationCoords,
      ];

      const filteredLocations = rawLocations
        .filter(
          (coord: any) =>
            coord && coord.latitude != null && coord.longitude != null
        )
        .map((coord: any) => ({
          lat: coord.latitude,
          lng: coord.longitude,
        }));

      const payload: any = {
        locations: filteredLocations,
        service_id: item?.service_id,
        service_category_id: item?.service_category_id,
      };
      dispatch(vehicleTypeDataGet(payload)).then((res: any) => {
        const categoryId = item?.service_id;
        const categoryOptionID = item?.service_category_id;
        const scheduleDate = null;
        const service_name = item?.service?.service_type;
        const slug = item?.service_category?.slug;
        const pickupCoords1 = item?.location_coordinates[0];
        const destinationCoords1 =
          item?.location_coordinates.length > 1
            ? item?.location_coordinates[item?.location_coordinates.length - 1]
            : null;

        if (slug === "intercity" || slug === "ride") {
          navigate("BookRide", {
            destination,
            stops,
            pickupLocation,
            service_ID: categoryId,
            zoneValue,
            scheduleDate,
            service_category_ID: categoryOptionID,
            filteredLocations: filteredLocations,
            pickupCoords: pickupCoords1,
            destinationCoords: destinationCoords1,
          });
        } else if (slug === "package") {
          navigate("Rental", {
            pickupLocation,
            service_ID: categoryId,
            service_category_ID: categoryOptionID,
            zoneValue,
          });
        } else if (service_name === "parcel" || service_name === "freight") {
          navigate("Outstation", {
            destination,
            stops,
            pickupLocation,
            service_ID: categoryId,
            zoneValue,
            service_name,
            service_category_ID: categoryOptionID,
            filteredLocations: filteredLocations,
            pickupCoords: pickupCoords1,
            destinationCoords: destinationCoords1,
          });
        }
      });
    } catch (error) {
      console.error("Booking failed:", error);
      notificationHelper("", error, "error");
    } finally {
    }
  };
  const getStars = (rating: number) => {
    const stars = [];
    const totalStars = 5;

    for (let i = 1; i <= totalStars; i++) {
      if (rating >= i) {
        stars.push(<Star key={i} />);
      } else if (rating >= i - 0.5) {
        stars.push(<HalfStar key={i} />);
      } else {
        stars.push(<EmptyStar key={i} />);
      }
    }

    return stars;
  };

  const renderItem = ({ item }: any) => {

    console.log('item', 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 lastIndex = item?.locations?.length - 1;

    return (
      <View>
        <TouchableOpacity
          style={[
            styles.container,
            {
              backgroundColor: bgFullStyle,
              borderColor: isDark ? appColors.darkBorder : appColors.border,
            },
          ]}
          onPress={() => handlePress(item, vehicleData)}
          activeOpacity={0.7}
        >
          <View
            style={[
              styles.rideInfoContainer,
              {
                backgroundColor: isDark
                  ? appColors.primaryText
                  : appColors.whiteColor,
              },
            ]}
          >
            <View
              style={[
                styles.profileInfoContainer,
                { flexDirection: viewRTLStyle },
                { alignItems: "flex-start" },
              ]}
            >
              <View
                style={{
                  height: windowHeight(45),
                  width: windowHeight(50),
                  backgroundColor: isDark
                    ? appColors.solidBorder
                    : appColors.lightGray,
                  alignItems: "center",
                  justifyContent: "center",
                  borderRadius: windowHeight(8),
                }}
              >
                {item?.service?.slug != "ambulance" ? (
                  <Image
                    style={styles.profileImage}
                    source={{ uri: item?.vehicle_type?.vehicle_image_url }}
                  />
                ) : (
                  <Image
                    style={styles.profileImage}
                    source={Images.ambulance}
                  />
                )}
              </View>

              <View
                style={{ width: windowWidth(240), alignItems: "flex-start" }}
              >
                <View
                  style={[
                    styles.profileTextContainer,
                    {
                      height: windowHeight(40),
                      flexDirection: viewRTLStyle,
                      alignItems: "center",
                    },
                  ]}
                >
                  <View
                    style={[
                      styles.numberBox,
                      {
                        backgroundColor: isDark
                          ? appColors.solidBorder
                          : appColors.lightGray,
                      },
                    ]}
                  >
                    <Text
                      style={[
                        styles.profileName,
                        { color: textColorStyle },
                        { textAlign: textRTLStyle },
                      ]}
                    >
                      #{item?.ride_number}
                    </Text>
                  </View>
                  <View style={styles.service_name_view}>
                    <Text style={styles.service_name}>
                      {item?.service?.name}
                    </Text>
                  </View>
                </View>

                <View
                  style={{
                    flexDirection: "row",
                    // marginTop: windowHeight(4),
                    marginHorizontal: windowWidth(12),
                  }}
                >
                  <View
                    style={{
                      flexDirection: viewRTLStyle,
                      alignItems: "center",
                    }}
                  >
                    <FillCalender />
                    <Text
                      style={{
                        fontSize: fontSizes.FONT16,
                        color: appColors.regularText,
                        fontFamily: appFonts.medium,
                        marginHorizontal: windowWidth(3),
                      }}
                    >
                      {formattedDate.date}
                    </Text>
                  </View>

                  <View
                    style={{
                      borderLeftWidth: windowWidth(2),
                      borderColor: isDark
                        ? appColors.darkBorder
                        : appColors.border,
                      marginHorizontal: windowWidth(5),
                    }}
                  />
                  <View
                    style={{
                      flexDirection: viewRTLStyle,
                      alignItems: "center",
                    }}
                  >
                    <UnfillClock />
                    <Text
                      style={{
                        fontSize: fontSizes.FONT16,
                        color: appColors.regularText,
                        fontFamily: appFonts.medium,
                        marginHorizontal: windowWidth(3),
                      }}
                    >
                      {formattedDate.time}
                    </Text>
                  </View>
                </View>
              </View>

              <View
                style={{
                  justifyContent: "space-between",
                  alignSelf: "flex-start",
                }}
              >
                <Text
                  style={[
                    commonStyles.mediumTextBlack12,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                      fontSize: fontSizes.FONT22,
                      marginTop: windowHeight(3),
                      marginHorizontal: windowWidth(-5),
                    },
                  ]}
                >
                  {item?.currency_symbol}
                  {item?.total}
                </Text>
              </View>
            </View>

            {item?.ride_status?.slug !== "completed" &&
              item?.ride_status?.slug !== "cancelled" && (
                <View
                  style={[
                    styles.dashedLine,
                    {
                      backgroundColor: isDark
                        ? appColors.solidBorder
                        : appColors.lightGray,
                      marginTop: windowHeight(16),
                    },
                  ]}
                />
              )}

            {item?.ride_status?.slug !== "completed" &&
              item?.ride_status?.slug !== "cancelled" && (
                <View
                  style={{
                    flexDirection: viewRTLStyle,
                    alignItems: "center",
                    marginBottom: windowHeight(8),
                    marginTop: windowHeight(3),
                  }}
                >
                  <View>
                    {item?.driver?.driver_profile_image_url ? (
                      <Image
                        source={{ uri: item?.driver?.driver_profile_image_url }}
                        style={[styles.profileround]}
                        resizeMode="contain"
                      />
                    ) : (
                      <View
                        style={[
                          styles.profileround,
                          { backgroundColor: colors.text },
                        ]}
                      >
                        <Text
                          style={[
                            styles.drivername,
                            {
                              color: isDark
                                ? appColors.whiteColor
                                : appColors.whiteColor,
                            },
                          ]}
                        >
                          {item?.driver?.name?.charAt(0)?.toUpperCase()}
                        </Text>
                      </View>
                    )}
                  </View>

                  <View>
                    <View
                      style={{
                        flexDirection: viewRTLStyle,
                        alignItems: "center",
                        justifyContent: "space-between",
                        marginHorizontal: windowWidth(15),
                        width: "80.5%",
                        flexWrap: "wrap",
                      }}
                    >
                      <View
                        style={{
                          flexDirection: viewRTLStyle,
                          alignItems: "center",
                        }}
                      >
                        <Text
                          style={{
                            fontFamily: appFonts.medium,
                            fontSize: fontSizes.FONT18,
                            color: isDark
                              ? appColors.whiteColor
                              : appColors.blackColor,
                          }}
                        >
                          {item?.driver?.name?.length > 15
                            ? item?.driver?.name.substring(0, 15) + "..."
                            : item?.driver?.name}
                        </Text>
                        <View style={{ marginHorizontal: windowWidth(8) }}>
                          <Name />
                        </View>
                      </View>
                      <Text
                        style={{
                          fontFamily: appFonts.regular,
                          fontSize: fontSizes.FONT17,
                          color: appColors.iconColor,
                        }}
                      >
                        {item?.vehicle_type?.vehicle_model?.length > 12
                          ? item?.vehicle_type?.vehicle_model.substring(0, 12) +
                          "..."
                          : item?.vehicle_type?.vehicle_model}
                      </Text>
                    </View>
                    <View
                      style={{
                        flexDirection: viewRTLStyle,
                        alignItems: "center",
                        marginHorizontal: windowWidth(15),
                        marginTop: windowHeight(2),
                      }}
                    >
                      <View
                        style={{
                          flexDirection: viewRTLStyle,
                          alignItems: "center",
                        }}
                      >
                        {getStars(item?.driver?.rating_count ?? 0)}
                      </View>
                      <Text
                        style={{
                          fontFamily: appFonts.regular,
                          fontSize: fontSizes.FONT18,
                          color: isDark
                            ? appColors.whiteColor
                            : appColors.blackColor,
                          marginHorizontal: windowWidth(5),
                        }}
                      >
                        {item?.driver?.rating_count}
                      </Text>
                      <Text
                        style={{
                          fontFamily: appFonts.regular,
                          fontSize: fontSizes.FONT15,
                          color: appColors.iconColor,
                        }}
                      >{`(${item?.driver?.review_count})`}</Text>
                    </View>
                  </View>
                </View>
              )}

            {item?.ride_status?.slug !== "completed" &&
              item?.ride_status?.slug !== "cancelled" && (
                <View
                  style={{
                    flexDirection: viewRTLStyle,
                    justifyContent: "space-between",
                    marginBottom: windowHeight(8),
                    marginTop: windowHeight(4),
                  }}
                >
                  <TouchableOpacity
                    onPress={() => gotoMessage(item)}
                    style={[
                      styles.message,
                      {
                        backgroundColor: isDark
                          ? appColors.solidBorder
                          : appColors.lightGray,
                        height: windowHeight(40),
                        width: windowWidth(315),
                        alignItems: "flex-start",
                        borderRadius: windowHeight(25),
                        paddingHorizontal: windowWidth(10),
                      },
                    ]}
                    activeOpacity={0.7}
                  >
                    <Text
                      style={{
                        marginHorizontal: windowWidth(10),
                        fontFamily: appFonts.regular,
                        color: appColors.regularText,
                      }}
                    >
                      {translateData?.sendMessage}
                    </Text>
                  </TouchableOpacity>
                  <TouchableOpacity
                    onPress={() => gotoCall(item)}
                    activeOpacity={0.7}
                    style={[
                      styles.call,
                      {
                        backgroundColor: appColors.online,
                      },
                    ]}
                  >
                    <Call color={appColors.whiteColor} />
                  </TouchableOpacity>
                </View>
              )}
            <View
              style={[
                styles.dashedLine,
                {
                  backgroundColor: isDark
                    ? appColors.solidBorder
                    : appColors.lightGray,
                },
              ]}
            />

            <View style={{ marginBottom: windowHeight(8) }}>
              <View
                style={[{ flexDirection: viewRTLStyle, alignItems: "center" }]}
              >
                <View
                  style={[
                    external.fd_column,
                    styles.round,
                    {
                      backgroundColor: isDark
                        ? appColors.solidBorder
                        : appColors.lightGray,
                    },
                  ]}
                >
                  <PickLocation
                    height={12}
                    width={12}
                    colors={appColors.iconColor}
                  />
                </View>
                <Text
                  style={[
                    styles.itemStyle1,
                    external.mh_5,
                    { color: textColorStyle },
                    { textAlign: textRTLStyle },
                  ]}
                  numberOfLines={1}
                  ellipsizeMode="tail"
                >
                  {item?.locations?.[0]?.length > 32
                    ? item.locations[0].substring(0, 32) + "..."
                    : item?.locations?.[0]}
                </Text>
              </View>

              {item?.service?.slug !== "ambulance" && item?.service_category?.service_category_type !== 'rental' && <View
                style={{
                  flexDirection: viewRTLStyle,
                  alignItems: "center",
                  justifyContent: "space-between",
                }}
              >
                <View
                  style={{
                    height: windowHeight(10),
                    // width: windowWidth(1),
                    marginHorizontal: windowWidth(22.5),
                    borderStyle: "dashed",
                    borderWidth: windowHeight(0.5),
                    borderColor: appColors.primary,

                  }}
                />
                <View
                  style={{
                    width: "100%",
                    height: windowHeight(1.8),
                    backgroundColor: isDark
                      ? appColors.solidBorder
                      : appColors.lightGray,
                    marginHorizontal: windowWidth(3),
                  }}
                />
              </View>}

              {item?.service?.slug !== "ambulance" && item?.service_category?.service_category_type !== 'rental' && <View
                style={[{ flexDirection: viewRTLStyle, alignItems: "center" }]}
              >
                <View
                  style={[
                    external.fd_column,
                    styles.round,
                    {
                      backgroundColor: isDark
                        ? appColors.solidBorder
                        : appColors.lightGray,
                    },
                  ]}
                >
                  <Location height={12} width={12} color={appColors.gray} />
                </View>
                <Text
                  style={[
                    styles.itemStyle1,
                    external.mh_5,
                    { color: textColorStyle },
                    { textAlign: textRTLStyle },
                  ]}
                  numberOfLines={1}
                  ellipsizeMode="tail"
                >
                  {item?.locations?.[lastIndex]?.length > 32
                    ? item.locations[lastIndex].substring(0, 32) + "..."
                    : item?.locations?.[lastIndex]}
                </Text>
              </View>}

              {item?.service?.slug !== "ambulance" && item?.service_category?.service_category_type !== 'rental' && <View
                style={[
                  styles.round1,
                  {
                    backgroundColor: isDark
                      ? appColors.bgDark
                      : appColors.whiteColor,
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.border,
                    alignSelf: isRTL ? 'flex-start' : 'flex-end'
                  },
                ]}
              >
                <Text style={styles.km}>{`${parseFloat(item?.distance).toFixed(
                  1
                )}`}</Text>
                <Text style={styles.km}>{item?.distance_unit}</Text>
              </View>}
            </View>
          </View>


          <View style={external.mh_10}>
            <View style={[styles.serviceMainView]}>
              {item?.ride_status?.slug === "accepted" &&
                item?.ride_status?.slug === "pending" &&
                item?.ride_status?.slug === "schedule" && (
                  <View
                    style={[
                      styles.MessageMainView,
                      {
                        flexDirection: viewRTLStyle,
                      },
                    ]}
                  >
                    <TouchableOpacity
                      style={[
                        styles.MessageView,
                        {
                          borderColor: isDark
                            ? appColors.darkBorder
                            : colors.border,
                        },
                      ]}
                      activeOpacity={0.7}
                      onPress={() => gotoMessage(item)}
                    >
                      <Message />
                    </TouchableOpacity>
                    <TouchableOpacity
                      activeOpacity={0.7}
                      style={[
                        styles.safetyCallView,
                        {
                          borderColor: isDark
                            ? appColors.darkBorder
                            : colors.border,
                        },
                      ]}
                      onPress={() => gotoCall(item)}
                    >
                      <SafetyCall color={appColors.primary} />
                    </TouchableOpacity>
                  </View>
                )}

              {item?.ride_status?.slug == "completed" && (
                <View
                  style={{
                    marginBottom: windowHeight(5),
                    marginTop: windowHeight(5),
                  }}
                >
                  <Button
                    title={translateData?.BookAgainTextttt}
                    onPress={() => gotoBook(item)}
                    backgroundColor={appColors.blackColor}
                    textColor={appColors.whiteColor}
                  />
                </View>
              )}
              {item?.ride_status?.slug == "cancelled" && (
                <TouchableOpacity
                  onPress={gotoBook}
                  style={{
                    backgroundColor: isDark
                      ? appColors.whiteColor
                      : appColors.blackColor,
                    flexDirection: "row",
                    justifyContent: "center",
                    alignItems: "center",
                    height: windowHeight(40),
                    borderRadius: windowHeight(55),
                    marginBottom: windowHeight(12),
                  }}
                >
                  <Text
                    style={{
                      color: isDark
                        ? appColors.blackColor
                        : appColors.whiteColor,
                      fontFamily: appFonts.medium,
                      marginHorizontal: windowWidth(5),
                    }}
                  >
                    {translateData?.BookAgainTextttt}
                  </Text>
                </TouchableOpacity>
              )}
            </View>
          </View>
        </TouchableOpacity>
      </View>
    );
  };

  return (
    <View style={styles.main}>
      {initialLoading && acceptedRides?.length > 0 ? (
        <RideLoader />
      ) : acceptedRides?.length === 0 || acceptedRides === undefined ? (
        <View style={styles.noDataView}>
          <Image
            source={isDark ? Images.noRideDark : Images.noRide}
            style={styles.noRideImage}
            resizeMode="contain"
          />
          <View style={[styles.noRIdeView, { flexDirection: viewRTLStyle }]}>
            <Text
              style={[
                styles.noRIde,
                {
                  color: isDark ? appColors.whiteColor : appColors.primaryText,
                  fontFamily: appFonts.bold,
                },
              ]}
            >
              {translateData.noRIde}
            </Text>
            <View style={styles.Info}>
              <Info />
            </View>
          </View>
          <Text
            style={[
              styles.noRideDes,
              {
                color: isDark ? appColors.whiteColor : appColors.regularText,
                fontFamily: appFonts.regular,
              },
            ]}
          >
            {translateData.noRideDes}
          </Text>
        </View>
      ) : (
        <View style={styles.flatlistView}>
          <FlatList
            data={paginatedData}
            keyExtractor={(item) => item.id.toString()}
            renderItem={renderItem}
            onEndReached={loadMoreData}
            onEndReachedThreshold={0.5}
            contentContainerStyle={styles.containerStyle}
            initialNumToRender={3}
            maxToRenderPerBatch={2}
            windowSize={3}
            removeClippedSubviews={true}
            ListFooterComponent={() => {
              if (
                paginationLoading &&
                hasMoreData &&
                acceptedRides?.length > paginatedData.length
              ) {
                return (
                  <ActivityIndicator
                    size="large"
                    color={colors.text}
                    style={{ marginTop: windowHeight(10) }}
                  />
                );
              }
              return null;
            }}
          />
        </View>
      )}
    </View>
  );
}
