import {
  ScrollView,
  View,
  TouchableOpacity,
  Image,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  Linking,
  ActivityIndicator,
  Alert,
} from "react-native";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import {
  Button,
  HeaderContainer,
  notificationHelper,
} from "@src/commonComponent";
import { external } from "../../../../styles/externalStyle";
import { PendingDetails } from "./pendingDetails/index";
import {
  appColors,
  appFonts,
  fontSizes,
  windowHeight,
  windowWidth,
} from "@src/themes";
import { useValues } from "@src/utils/context/index";
import {
  useFocusEffect,
  useNavigation,
  useRoute,
} from "@react-navigation/native";
import {
  CalenderSmall,
  Call,
  ClockSmall,
  Location,
  PickLocation,
  RatingEmptyStart,
  RatingHalfStar,
  RatingStar,
  StarEmpty,
  StarFill,
} from "@src/utils/icons";
import { styles } from "../rideContainer/style";
import { useDispatch, useSelector } from "react-redux";
import { clearValue, getValue } from "@src/utils/localstorage";
import {
  allRide,
  paymentsData,
  driverReviewPost,
  allRides,
  rideDataPut,
  cancelationDataGet,
} from "@src/api/store/actions";
import { URL } from "@src/api/config";
import { UserRegistrationPayload } from "@src/api/interface/authInterface";
import styless from "./styles";
import { commonStyles } from "@src/styles/commonStyle";
import firestore from "@react-native-firebase/firestore";
import { apiformatDates } from "@src/utils/functions";
import BottomSheet, {
  BottomSheetBackdrop,
  BottomSheetFlatList,
  BottomSheetView,
} from "@gorhom/bottom-sheet";
import { Invoice } from "@src/assets/icons/recipet";
import { AppDispatch } from "@src/api/store";

export function PendingRideScreen() {
  const {
    bgFullStyle,
    textColorStyle,
    viewRTLStyle,
    textRTLStyle,
    isDark,
    isRTL,
  } = useValues();
  const route = useRoute();
  const { item, vehicleDetail, rideStatus } = route?.params;
  const dispatch = useDispatch<AppDispatch>();
  const { navigate }: any = useNavigation();
  const { rideData } = useSelector((state: any) => state.allRide);
  const [rating, setRating] = useState<number>(0);
  const [reviewText, setReviewText] = useState<string>("");
  const { translateData } = useSelector((state) => state.setting);
  const navigation = useNavigation();
  const { self } = useSelector((state: any) => state.account);
  const [loader, setLoader] = useState(false);
  const [paymentLoading, setpaymentLoading] = useState(false);
  const [isBottomSheetVisible, setIsBottomSheetVisible] = useState(false);
  const { canceldata } = useSelector((state) => state.cancelationReason);
  const sheetRef = useRef<BottomSheet>(null);

  useEffect(() => {
    dispatch(cancelationDataGet());
  }, []);

  const bottomSheetRef = useRef<BottomSheet>(null);
  const snapPoints = useMemo(() => ["74%"], []);

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

  const viewInvoice = async () => {
    setLoader(true);
    const token = await getValue("token");
    const response = await fetch(
      `${URL}/api/ride/rider-invoice/${rideData?.invoice_id}`,
      {
        method: "GET",
        headers: {
          "Content-Type": "multipart/form-data",
          Accept: "application/json",
        },
      }
    );

    if (response.status == 200) {
      setLoader(false);
      navigate("PdfViewer", {
        pdfUrl: response?.url,
        token: token,
        rideNumber: rideData?.invoice_id,
      });
    }
  };

  const cancelRental = () => {
    sheetRef.current?.snapToIndex(0);
  };

  const cancelRide = (selectedItem) => {
    const ride_id = item?.id;

    let payload: ReviewInterface = {
      status: "cancelled",
      cancellation_reason: selectedItem.title,
    };
    dispatch(rideDataPut({ payload, ride_id }))
      .unwrap()
      .then((res: any) => {
        sheetRef.current?.close();
        if (res?.ride_status?.slug == "cancelled") {
          const rideId = activeRideOTP?.id;
          if (rideId) {
            navigate("MyTabs");
            dispatch(allRides());
          } else {
          }
        }
      });
  };

  const gotoTrack = () => {
    setLoader(true);
    if (item?.service_category.service_category_type === "package") {
      navigate("PaymentRental", { rideId: item?.id });
      setLoader(false);
    } else {
      navigate("Payment", { rideId: item?.id });
      setLoader(false);
    }
  };

  const payNow = () => {
    setpaymentLoading(true);
    const rideData = item;
    navigate("PaymentMethod", { rideData });
    setpaymentLoading(false);
  };

  const review = () => {
    bottomSheetRef.current?.expand();
    setIsBottomSheetVisible(true);
  };

  const reviewSubmit = async () => {
    let payload: UserRegistrationPayload = {
      ride_id: item?.id,
      driver_id: item?.driver_id,
      rating: rating,
      message: reviewText,
    };
    dispatch(driverReviewPost(payload))
      .unwrap()
      .then((res: any) => {
        if (res?.success === false) {
          notificationHelper("", res.message, "error");
          bottomSheetRef.current?.close();
          setIsBottomSheetVisible(false);
        } else {
          dispatch(allRides());
          bottomSheetRef.current?.close();
          setIsBottomSheetVisible(false);
          notificationHelper("", translateData.reviewSubmited, "success");
          navigation.goBack();
        }
      })
      .catch((err) => {
        notificationHelper("", err, "error");
      });
  };



  useFocusEffect(
    useCallback(() => {
      dispatch(paymentsData())
        .unwrap()
        .then((res: any) => {
          if (res?.status == 403) {
            notificationHelper("", translateData.loginAgain, "error");
            clearValue("token").then(() => {
              navigation.reset({
                index: 0,
                routes: [{ name: "SignIn" }],
              });
            });
          }
        })
        .catch((error) => { });

      dispatch(allRide({ ride_id: item.id }))
        .unwrap()
        .then((res: any) => {
          if (res?.status == 403) {
            notificationHelper("", translateData.loginAgain, "error");
            clearValue("token").then(() => {
              navigation.reset({
                index: 0,
                routes: [{ name: "SignIn" }],
              });
            });
          }
        })
        .catch((error) => { });
    }, [item.id])
  );

  const handleStarPress = (selectedRating: number) => {
    setRating(selectedRating);
  };

  const gotoOtpRide = async () => {
    setLoader(true);

    try {
      const rideId = item?.id;

      if (!rideId) {
        Alert.alert(
          "Ride Error",
          "Ride ID not found. Please try again."
        );
        return;
      }

      console.log("Ride ID:", rideId);

      const rideDoc = await firestore()
        .collection("rides")
        .doc(rideId.toString())
        .get();

      if (!rideDoc.exists) {
        Alert.alert(
          "No Ride Found",
          translateData?.noRecordsFound || "No ride data available"
        );
        return;
      }

      const rideData = rideDoc.data();
      console.log("Ride Data:", rideData);

      navigation.navigate("RideActive", {
        activeRideOTP: rideData,
      });

    } catch (error: any) {
      console.error("gotoOtpRide error:", error);

      Alert.alert(
        "Something went wrong",
        error?.message || "Unable to fetch ride details"
      );
    } finally {
      setLoader(false);
    }
  };


  const formattedDate = apiformatDates(item.created_at);
  const hasProfileImage = item?.driver.driver_profile_image_url;

  const handleSheetChange = useCallback((index) => { }, []);

  const renderItem = useCallback(({ item }) => {
    return (
      <TouchableOpacity
        activeOpacity={0.7}
        key={item.id}
        style={[
          styles.container2,
          {
            backgroundColor: appColors.lightGray,
            flexDirection: viewRTLStyle,
          },
        ]}
        onPress={() => cancelRide(item)}
      >
        <View style={styles.textContainer}>
          <Text
            style={[
              styles.text,
              { color: textColorStyle, textAlign: textRTLStyle },
            ]}
          >
            {item.title}
          </Text>
        </View>
      </TouchableOpacity>
    );
  }, []);
  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}`);
  };

  return (
    <View
      style={{
        backgroundColor: isDark ? appColors.solidBorder : appColors.lightGray,
      }}
    >
      <ScrollView>
        {item?.ride_status?.slug === "completed" &&
          item?.payment_status === "COMPLETED" ? (
          <HeaderContainer
            value={`${rideStatus} ${translateData.ride}`}
            show={true}
            icon={
              <View>
                {loader ? (
                  <ActivityIndicator color={appColors.primary} size={"small"} />
                ) : (
                  <Invoice
                    color={isDark ? appColors.whiteColor : appColors.blackColor}
                  />
                )}
              </View>
            }
            onPressIcon={viewInvoice}
          />
        ) : (
          <HeaderContainer value={`${rideStatus} ${translateData.ride}`} />
        )}

        <ScrollView
          showsVerticalScrollIndicator={false}
          contentContainerStyle={{ paddingBottom: windowHeight(15) }}
        >
          <View
            style={[
              styles.container,
              {
                backgroundColor: isDark
                  ? appColors.primaryText
                  : appColors.whiteColor,
              },
            ]}
          >
            <View
              style={[
                styles.rideInfoContainer,
                { backgroundColor: bgFullStyle },
              ]}
            >
              <View style={[{ flexDirection: viewRTLStyle }]}>
                {hasProfileImage ? (
                  <Image
                    style={styles.profileImage}
                    source={{ uri: item?.driver.driver_profile_image_url }}
                  />
                ) : (
                  <View
                    style={{
                      width: windowHeight(37),
                      height: windowHeight(37),
                      borderRadius: windowHeight(37),
                      backgroundColor: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                      justifyContent: "center",
                      alignItems: "center",
                    }}
                  >
                    <Text
                      style={{
                        fontSize: fontSizes.FONT23,
                        fontFamily: appFonts.bold,
                        color: isDark
                          ? appColors.blackColor
                          : appColors.whiteColor,
                      }}
                    >
                      {item?.driver?.name?.charAt(0)?.toUpperCase() || "D"}
                    </Text>
                  </View>
                )}
                <View
                  style={[
                    styles.profileTextContainer,
                    { marginTop: windowHeight(2) },
                  ]}
                >
                  <Text
                    style={[
                      styles.profileName,
                      { color: textColorStyle },
                      { textAlign: textRTLStyle },
                      { fontFamily: appFonts.semiBold },
                    ]}
                  >
                    {item?.driver?.name}
                  </Text>
                  <View
                    style={[
                      styles.carInfoContainer,
                      { flexDirection: viewRTLStyle },
                    ]}
                  >
                    <View style={styles.PendingRideContainer}>
                      <View style={{ flexDirection: viewRTLStyle }}>
                        <View
                          style={{
                            flexDirection: viewRTLStyle,
                          }}
                        >
                          {Array.from({ length: 5 }).map((_, index) => {
                            const fullStarThreshold = index + 1;
                            const halfStarThreshold = index + 0.5;
                            if (
                              item?.driver?.rating_count >= fullStarThreshold
                            ) {
                              return <RatingStar key={index} />;
                            } else if (
                              item?.driver?.rating_count >= halfStarThreshold
                            ) {
                              return <RatingHalfStar key={index} />;
                            } else {
                              return <RatingEmptyStart key={index} />;
                            }
                          })}
                        </View>
                        <View style={{ flexDirection: viewRTLStyle }}>
                          <Text
                            style={[
                              commonStyles.mediumTextBlack12,
                              ,
                              {
                                color: isDark
                                  ? appColors.whiteColor
                                  : appColors.blackColor,
                                marginHorizontal: windowWidth(4),
                              },
                            ]}
                          >
                            {Number(item?.driver?.rating_count).toFixed(1)}
                          </Text>
                          <Text
                            style={[
                              commonStyles.regularText,
                              {
                                color: appColors.regularText,
                                marginTop: windowHeight(0),
                              },
                            ]}
                          >
                            ({item?.driver?.review_count})
                          </Text>
                        </View>
                      </View>
                    </View>
                  </View>
                </View>

                <Text
                  style={[
                    styles.carInfoText,
                    { textAlign: textRTLStyle, marginTop: windowHeight(7) },
                  ]}
                >
                  {item?.vehicle_model}
                </Text>
              </View>

              {(item?.ride_status?.slug == "accepted" ||
                item?.ride_status?.slug == "arrived") &&
                item?.service_category?.service_category_type != "rental" && (
                  <View>
                    <View
                      style={{
                        flexDirection: viewRTLStyle,
                        justifyContent: "space-between",
                        marginBottom: windowHeight(0),
                        marginTop: windowHeight(14),
                      }}
                    >
                      <TouchableOpacity
                        onPress={() => gotoMessage(item)}
                        style={[
                          styles.message,
                          {
                            backgroundColor: isDark
                              ? appColors.solidBorder
                              : appColors.lightGray,
                            height: windowHeight(38),
                            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,
                            height: windowHeight(38),
                            width: windowHeight(38),
                          },
                        ]}
                      >
                        <Call color={appColors.whiteColor} />
                      </TouchableOpacity>
                    </View>
                  </View>
                )}

              <View
                style={[
                  styless.dashedLine,
                  {
                    backgroundColor: isDark
                      ? appColors.solidBorder
                      : appColors.lightGray,
                  },
                ]}
              />

              <View>
                <View
                  style={[external.mh_3, { marginBottom: windowHeight(4) }]}
                >
                  <View
                    style={[
                      styless.calenderSmallView,
                      {
                        flexDirection: viewRTLStyle,
                      },
                    ]}
                  >
                    <View
                      style={[
                        styles.round,
                        {
                          backgroundColor: isDark
                            ? appColors.solidBorder
                            : appColors.lightGray,
                          zIndex: 3,
                        },
                      ]}
                    >
                      <PickLocation height={12} width={12} />
                    </View>
                    <Text
                      style={[
                        styles.itemStyle,
                        { color: textColorStyle },
                        {
                          textAlign: textRTLStyle,
                          marginHorizontal: windowWidth(10),
                        },
                      ]}
                    >
                      {item?.locations?.[0]?.length > 30
                        ? item.locations[0].substring(0, 30) + "..."
                        : item.locations[0]}
                    </Text>
                  </View>
                  {item?.service?.slug !== "ambulance" && item?.service_category?.service_category_type !== 'rental' && <View style={[styles.borderVertical1, { alignSelf: isRTL ? 'flex-end' : 'flex-start' }]} />}
                  {item?.service?.slug !== "ambulance" && item?.service_category?.service_category_type !== 'rental' &&
                    item.locations.length > 1 && (
                      <View>
                        <View
                          style={[
                            styles.round1,
                            {
                              marginTop: windowHeight(-10),
                              zIndex: 3,
                              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
                          style={[
                            styles.dashedLine1,
                            {
                              backgroundColor: isDark
                                ? appColors.darkBorder
                                : appColors.border,
                              alignSelf: isRTL ? 'flex-end' : 'flex-start'
                            },
                          ]}
                        />
                        <View
                          style={[
                            styless.calenderSmallView,
                            {
                              flexDirection: viewRTLStyle,
                            },
                          ]}
                        >
                          <View
                            style={[
                              styles.round,
                              {
                                backgroundColor: isDark
                                  ? appColors.solidBorder
                                  : appColors.lightGray,
                                zIndex: 3,
                              },
                            ]}
                          >
                            <Location
                              height={12}
                              width={12}
                              color={isDark ? appColors.gray : appColors.gray}
                            />
                          </View>
                          <Text
                            style={[
                              styles.pickUpLocationStyles,
                              {
                                color: textColorStyle,
                                marginHorizontal: windowWidth(10),
                              },
                            ]}
                          >
                            {item?.locations?.[1]?.length > 30
                              ? item.locations[1].substring(0, 30) + "..."
                              : item.locations[1]}
                          </Text>
                        </View>
                      </View>
                    )}
                </View>
              </View>
            </View>
          </View>

          {item?.service_category?.slug === "schedule" && (
            <View
              style={[
                styless.scheduleView,
                {
                  flexDirection: viewRTLStyle,
                  backgroundColor: isDark
                    ? appColors.darkHeader
                    : appColors.whiteColor,
                  borderColor: isDark ? appColors.darkBorder : appColors.border,
                },
              ]}
            >
              <View style={styless.viewRental}>
                <Text
                  style={[
                    styless.startDateText,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                    },
                  ]}
                >
                  {translateData.startDate}
                </Text>
                <View
                  style={[
                    styless.clockSmall,
                    {
                      flexDirection: viewRTLStyle,
                    },
                  ]}
                >
                  <CalenderSmall />
                  <Text style={styless.timeText}>{formattedDate.date}</Text>
                </View>
              </View>
              <View
                style={[
                  styless.rentalLine,
                  {
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.border,
                  },
                ]}
              />
              <View style={[styless.viewRental, { alignItems: "flex-end" }]}>
                <Text
                  style={[
                    styless.startDateText,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                    },
                  ]}
                >
                  {translateData.startTime}
                </Text>
                <View
                  style={[
                    styless.clockSmall,
                    {
                      flexDirection: viewRTLStyle,
                    },
                  ]}
                >
                  <ClockSmall />
                  <Text style={styless.timeText}>{formattedDate.time}</Text>
                </View>
              </View>
            </View>
          )}



          {item?.service_category?.slug === "rental" && (
            <View
              style={[
                {
                  marginTop: windowHeight(8),
                  marginHorizontal: windowWidth(18),
                },
              ]}
            >
              <View
                style={[
                  styless.rentalView,
                  {
                    flexDirection: viewRTLStyle,
                    backgroundColor: isDark
                      ? appColors.primaryText
                      : appColors.lightGray,
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.border,
                  },
                ]}
              >
                <View
                  style={[
                    styles.box,
                    {
                      backgroundColor: isDark
                        ? appColors.primaryText
                        : appColors.whiteColor,
                      borderColor: isDark
                        ? appColors.darkBorder
                        : appColors.border,
                    },
                  ]}
                >
                  <Text
                    style={[
                      styless.startDateText,
                      {
                        color: isDark
                          ? appColors.whiteColor
                          : appColors.primaryText,
                      },
                    ]}
                  >
                    {translateData.endDate}
                  </Text>
                  <View
                    style={[
                      styless.vieww,
                      {
                        flexDirection: viewRTLStyle,
                      },
                    ]}
                  >
                    <CalenderSmall />
                    <Text
                      style={{
                        color: appColors.regularText,
                        fontFamily: appFonts.regular,
                      }}
                    >
                      {" "}
                      {formattedDate.date}
                    </Text>
                  </View>
                </View>
                <View
                  style={[
                    styless.rentalLine,
                    {
                      borderColor: isDark
                        ? appColors.darkBorder
                        : appColors.border,
                    },
                  ]}
                />
                <View
                  style={[
                    styles.box,
                    {
                      backgroundColor: isDark
                        ? appColors.primaryText
                        : appColors.whiteColor,
                      borderColor: isDark
                        ? appColors.darkBorder
                        : appColors.border,
                    },
                  ]}
                >
                  <Text
                    style={{
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.primaryText,
                      fontFamily: appFonts.medium,
                    }}
                  >
                    {translateData.endTime}
                  </Text>
                  <View
                    style={[
                      styless.vieww,
                      {
                        flexDirection: viewRTLStyle,
                      },
                    ]}
                  >
                    <ClockSmall />
                    <Text style={styless.timeText}> {formattedDate.time}</Text>
                  </View>
                </View>
              </View>

              <View
                style={[
                  styless.rentalView1,
                  {
                    flexDirection: viewRTLStyle,
                    backgroundColor: isDark
                      ? appColors.primaryText
                      : appColors.whiteColor,
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.border,
                  },
                ]}
              >
                <View
                  style={{
                    flexDirection: viewRTLStyle,
                    alignItems: "center",
                    justifyContent: "space-between",
                  }}
                >
                  <Text
                    style={[
                      styless.timeText,
                      {
                        color: isDark
                          ? appColors.whiteColor
                          : appColors.blackColor,
                        fontSize: fontSizes.FONT18,
                        fontFamily: appFonts.medium,
                        width: "77%",
                      },
                    ]}
                  >
                    {translateData.totalDays}
                  </Text>
                  <View
                    style={[
                      styless.vieww,
                      {
                        flexDirection: viewRTLStyle,
                        marginTop: 0,
                      },
                    ]}
                  >
                    <CalenderSmall />
                    <Text style={styless.timeText}>
                      {item?.total_no_ofday} {translateData?.day}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
          )}

          {item?.service_category?.service_category_type === "schedule" && (
            <View
              style={[
                styless.scheduleView,
                {
                  flexDirection: viewRTLStyle,
                  backgroundColor: isDark
                    ? appColors.darkHeader
                    : appColors.whiteColor,
                  borderColor: isDark ? appColors.darkBorder : appColors.border,
                },
              ]}
            >
              <View style={styless.viewRental}>
                <Text
                  style={[
                    styless.startDateText,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                    },
                  ]}
                >
                  {translateData.startDate}
                </Text>
                <View
                  style={[
                    styless.clockSmall,
                    {
                      flexDirection: viewRTLStyle,
                    },
                  ]}
                >
                  <CalenderSmall />
                  <Text style={styless.timeText}>{formattedDate.date}</Text>
                </View>
              </View>
              <View
                style={[
                  styless.rentalLine,
                  {
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.border,
                  },
                ]}
              />
              <View style={[styless.viewRental, { alignItems: "flex-end" }]}>
                <Text
                  style={[
                    styless.startDateText,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                    },
                  ]}
                >
                  {translateData.startTime}
                </Text>
                <View
                  style={[
                    styless.clockSmall,
                    {
                      flexDirection: viewRTLStyle,
                    },
                  ]}
                >
                  <ClockSmall />
                  <Text style={styless.timeText}>{formattedDate.time}</Text>
                </View>
              </View>
            </View>
          )}

          <View style={[external.mt_10]}>
            {item.ride_status.slug === "cancelled" ? (
              <View style={styless.cancelledView}>
                <Text style={styless.cancellation_reasonText}>
                  {translateData.reason}
                </Text>

                <View style={styless.cancellation_reasonView}>
                  <Text style={styless.cancellation_reasonText}>
                    {rideData?.cancellation_reason}
                  </Text>
                </View>
              </View>
            ) : (
              <PendingDetails rideDetails={item} vehicleData={vehicleDetail} />
            )}
          </View>

          {item.ride_status.slug != "cancelled" && (
            <View>
              <Text
                style={[
                  styles.title,
                  {
                    color: isDark
                      ? appColors.whiteColor
                      : appColors.primaryText,
                    textAlign: textRTLStyle,
                    fontFamily: appFonts.semiBold,
                    marginHorizontal: windowWidth(20),
                  },
                ]}
              >
                {translateData.paymentMethod}
              </Text>

              <View
                style={[
                  styless.ride_statusView,
                  { backgroundColor: bgFullStyle },
                ]}
              >
                <View style={[styles.contain, { flexDirection: viewRTLStyle }]}>
                  <Text style={[styles.type, { color: appColors.regularText }]}>
                    {translateData.PaymentId || "Payment Id"}
                  </Text>
                  <Text
                    style={[
                      styles.type,
                      {
                        color: isDark
                          ? appColors.whiteColor
                          : appColors.primaryText,
                      },
                    ]}
                  >
                    {item?.invoice_id}
                  </Text>
                </View>

                <View style={[styles.contain, { flexDirection: viewRTLStyle }]}>
                  <Text style={[styles.type, { color: appColors.regularText }]}>
                    {translateData.paymentMethod}
                  </Text>
                  <Text
                    style={[
                      styles.type,
                      {
                        color: isDark
                          ? appColors.whiteColor
                          : appColors.primaryText,
                      },
                    ]}
                  >
                    {item?.payment_method}
                  </Text>
                </View>
                <View style={[styles.contain, { flexDirection: viewRTLStyle }]}>
                  <Text style={[styles.type, { color: appColors.regularText }]}>
                    {translateData.status}
                  </Text>
                  <Text
                    style={[
                      external.mh_2,
                      styles.type,
                      {
                        color:
                          item?.payment_status === "PENDING"
                            ? appColors.statusText
                            : item?.payment_status === "COMPLETED"
                              ? appColors.online
                              : appColors.alertRed,
                      },
                    ]}
                  >
                    {item?.payment_status}
                  </Text>
                </View>
              </View>
            </View>
          )}

          <TouchableOpacity
            activeOpacity={0.1}
            onPress={() =>
              navigate("ChatScreen", {
                from: "help",
                riderId: self && self?.id,
              })
            }
            style={styless.needHelpView}
          >
            <Text
              style={[
                styless.needHelpText,
                {
                  textAlign: isRTL ? "left" : "right",
                  color: isDark ? appColors.whiteColor : appColors.blackColor,
                },
              ]}
              onPress={() =>
                navigate("ChatScreen", {
                  from: "help",
                  riderId: self && self?.id,
                })
              }
            >
              {translateData.needHelp}
            </Text>
          </TouchableOpacity>
          {(item?.ride_status?.slug == "accepted" ||
            item?.ride_status?.slug == "arrived") &&
            item?.service_category?.service_category_type != "rental" && (
              <View style={{ marginHorizontal: windowWidth(20) }}>
                <Button
                  backgroundColor={
                    isDark ? appColors.whiteColor : appColors.blackColor
                  }
                  textColor={
                    isDark ? appColors.blackColor : appColors.whiteColor
                  }
                  title={translateData.startRide}
                  onPress={gotoOtpRide}
                  loading={loader}
                />
              </View>
            )}

          <View style={styless.ride_status}>
            {item?.ride_status?.slug == "completed" &&
              item?.payment_status == "PENDING" && (
                <Button
                  title={translateData.payNow}
                  onPress={payNow}
                  loading={paymentLoading}
                  backgroundColor={
                    isDark ? appColors.whiteColor : appColors.blackColor
                  }
                  textColor={
                    isDark ? appColors.blackColor : appColors.whiteColor
                  }
                />
              )}
            {item?.ride_status?.slug == "completed" &&
              item?.payment_status == "COMPLETED" &&
              item?.riderReview == null && (
                <Button
                  title={translateData.review}
                  onPress={review}
                  backgroundColor={
                    isDark ? appColors.whiteColor : appColors.blackColor
                  }
                  textColor={
                    isDark ? appColors.blackColor : appColors.whiteColor
                  }
                />
              )}
            {item?.ride_status?.slug == "started" &&
              item?.service_category?.service_category_type != "rental" && (
                <Button
                  title={translateData.trackRide}
                  onPress={gotoTrack}
                  loading={loader}
                  backgroundColor={
                    isDark ? appColors.whiteColor : appColors.blackColor
                  }
                  textColor={
                    isDark ? appColors.blackColor : appColors.whiteColor
                  }
                />
              )}
            {item?.service_category?.service_category_type == "rental" &&
              item?.ride_status?.slug == "accepted" && (
                <Button
                  title={translateData.modelCancelText}
                  onPress={cancelRental}
                  backgroundColor={appColors.alertRed}
                  loading={loader}
                />
              )}
          </View>
        </ScrollView>
      </ScrollView>

      <BottomSheet
        ref={bottomSheetRef}
        index={-1}
        snapPoints={snapPoints}
        backdropComponent={renderBackdrop}
        backgroundStyle={{
          backgroundColor: isDark
            ? appColors.primaryText
            : appColors.whiteColor,
        }}
        handleIndicatorStyle={{
          backgroundColor: isDark ? appColors.primary : appColors.primary,
          width: windowWidth(48),
          height: windowHeight(4.5),
          borderRadius: windowWidth(25),
        }}
        enablePanDownToClose={true}
      >
        <BottomSheetView>
          <TouchableWithoutFeedback>
            <View style={styles.bgmodal}>
              <TouchableWithoutFeedback onPress={() => { }}>
                <View
                  style={[
                    styles.background,
                    {
                      backgroundColor: isDark
                        ? appColors.darkHeader
                        : appColors.whiteColor,
                      borderColor: isDark
                        ? appColors.darkBorder
                        : appColors.border,
                    },
                  ]}
                >
                  <Text style={[styles.title, { color: textColorStyle }]}>
                    {translateData.modalTitle}
                  </Text>

                  <View style={styles.userAlign}>
                    {item?.driver?.driver_profile_image_url ? (
                      <Image
                        style={styles.modalImage}
                        source={{ uri: item?.driver?.driver_profile_image_url }}
                      />
                    ) : (
                      <View
                        style={[
                          styles.profileround1,
                          {
                            backgroundColor: isDark
                              ? appColors.whiteColor
                              : appColors.blackColor,
                          },
                        ]}
                      >
                        <Text
                          style={[
                            styles.drivername,
                            {
                              color: isDark
                                ? appColors.blackColor
                                : appColors.whiteColor,
                            },
                          ]}
                        >
                          {item?.driver?.name.charAt(0).toUpperCase()}
                        </Text>
                      </View>
                    )}

                    <Text style={[styles.modalName, { color: textColorStyle }]}>
                      {item?.driver?.name}
                    </Text>
                    <Text
                      style={[styles.modalMail, { color: appColors.iconColor }]}
                    >
                      {item?.driver?.email}
                    </Text>
                  </View>
                  <View
                    style={[
                      styles.line,
                      {
                        backgroundColor: isDark
                          ? appColors.bgDark
                          : appColors.lightGray,
                      },
                    ]}
                  />
                  <Text
                    style={[
                      styles.rate,
                      {
                        color: textColorStyle,
                        textAlign: textRTLStyle,
                        right: windowWidth(5),
                      },
                    ]}
                  >
                    {translateData.driverRating}
                  </Text>

                  <View
                    style={[
                      styles.containerReview,
                      {
                        backgroundColor: isDark
                          ? appColors.solidBorder
                          : appColors.lightGray,
                      },
                      { flexDirection: viewRTLStyle },
                    ]}
                  >
                    {[1, 2, 3, 4, 5].map((index) => (
                      <TouchableOpacity
                        activeOpacity={0.7}
                        key={index}
                        onPress={() => handleStarPress(index)}
                        style={styles.starIcon}
                      >
                        {index <= rating ? <StarFill /> : <StarEmpty />}
                      </TouchableOpacity>
                    ))}
                    <View
                      style={[
                        styles.ratingView,
                        { flexDirection: viewRTLStyle },
                      ]}
                    >
                      <View
                        style={[
                          styles.borderVertical,
                          {
                            borderColor: isDark
                              ? appColors.darkBorder
                              : appColors.border,
                          },
                        ]}
                      />
                      <Text style={[styles.rating, { color: textColorStyle }]}>
                        {rating}/5
                      </Text>
                    </View>
                  </View>

                  <Text
                    style={[
                      styles.comment,
                      {
                        color: textColorStyle,
                        textAlign: textRTLStyle,
                        right: windowWidth(6),
                      },
                    ]}
                  >
                    {translateData.addComments}
                  </Text>

                  <View style={[styless.textinput]}>
                    <TextInput
                      style={[
                        styles.textinput,
                        { color: textColorStyle, textAlign: textRTLStyle },
                        {
                          borderColor: isDark
                            ? appColors.darkBorder
                            : appColors.border,
                        },
                      ]}
                      multiline={true}
                      textAlignVertical="top"
                      value={reviewText}
                      onChangeText={(text) => setReviewText(text)}
                      placeholder={translateData?.writehere}
                      placeholderTextColor={appColors.iconColor}
                    />
                  </View>
                </View>
              </TouchableWithoutFeedback>
            </View>
          </TouchableWithoutFeedback>

          <View
            style={{ alignItems: "center", marginVertical: windowHeight(15) }}
          >
            <Button
              width={windowWidth(420)}
              backgroundColor={
                isDark ? appColors.whiteColor : appColors.blackColor
              }
              textColor={isDark ? appColors.blackColor : appColors.whiteColor}
              title={translateData.submit}
              onPress={reviewSubmit}
            />
          </View>
        </BottomSheetView>
      </BottomSheet>
      <BottomSheet
        ref={sheetRef}
        snapPoints={snapPoints}
        enableDynamicSizing={false}
        onChange={handleSheetChange}
        index={-1}
      >
        <BottomSheetFlatList
          data={canceldata?.data}
          keyExtractor={(item) => item}
          renderItem={renderItem}
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.contentContainer}
        />
      </BottomSheet>
    </View>
  );
}
