import {
  View,
  Text,
  TouchableOpacity,
  Linking,
  StyleSheet,
  Image,
} from "react-native";
import React, {
  useState,
  useEffect,
  useRef,
  useMemo,
  useCallback,
} from "react";
import { Map } from "@src/commonComponent";
import styles from "./styles";
import { useValues } from "@src/utils/context/index";
import { DriverData } from "./component/driverData/index";
import { TotalFare } from "./component/totalFare/index";
import { useRoute } from "@react-navigation/native";
import { CustomBackHandler } from "@src/components";
import { useAppNavigation } from "@src/utils/navigation";
import { external } from "@src/styles/externalStyle";
import {
  BottomSheetModal,
  BottomSheetModalProvider,
  BottomSheetView,
  BottomSheetFlatList,
  BottomSheetBackdrop,
} from "@gorhom/bottom-sheet";
import {
  appColors,
  appFonts,
  fontSizes,
  windowHeight,
  windowWidth,
} from "@src/themes";
import { useDispatch, useSelector } from "react-redux";
import { allRides, sosData } from "@src/api/store/actions";
import { initializeApp } from "firebase/app";
import { getFirestore, doc, onSnapshot } from "firebase/firestore";
import { firebaseConfig } from "../../../firebase";
import { Edit } from "@src/utils/icons";
import NativeAdComponent from "@src/commonComponent/google/NativeAdCard";

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

export function Payment() {
  const { textColorStyle, textRTLStyle, isDark, isRTL, viewRTLStyle } =
    useValues();
  const { navigate } = useAppNavigation();
  const route = useRoute();
  const { rideId } = route.params;
  const [rideDatas, setRideData] = useState(null);
  const [duration, setDuration] = useState(null);
  const bottomSheetRef = useRef<BottomSheetModal>(null);
  const sosSheetRef = useRef<BottomSheetModal>(null);
  const snapPoints = useMemo(
    () => (rideDatas?.service?.service_type === "parcel" ? ["52%"] : ["52%"]),
    [rideDatas?.service?.service_type]
  );
  const { taxidoSettingData } = useSelector((state: any) => state.setting);

  const sosSnapPoints = useMemo(() => ["35%"], []);
  const dispatch = useDispatch();
  const { zoneValue } = useSelector((state: any) => state.zone);
  const { sosValue } = useSelector((state: any) => state.sos);
  const { translateData } = useSelector((state: any) => state.setting);
  const [driverLocation, setDriverLocation] = useState<any | null>(null);

  // useEffect(() => {
  //   if (!rideId) return;

  //   const rideDocRef = doc(db, "rides", rideId.toString());

  //   const unsubscribe = onSnapshot(rideDocRef, snapshot => {
  //     if (snapshot.exists()) {
  //       setRideData(snapshot.data());
  //     }
  //   });

  //   return () => unsubscribe();
  // }, [rideId]);

  useEffect(() => {
    if (!rideId) return;
    const rideDocRef = doc(db, "rides", rideId.toString());
    const unsubscribe = onSnapshot(
      rideDocRef,
      (snapshot) => {
        if (snapshot.exists()) {
          setRideData(snapshot.data());
        } else {
        }
      },
      (error) => { }
    );
    return () => unsubscribe();
  }, [rideId]);

  const waypoints = useMemo(() => {
    if (
      !rideDatas?.location_coordinates ||
      rideDatas.location_coordinates.length <= 2
    )
      return [];
    const stops = rideDatas.location_coordinates
      .slice(1, -1)
      .map((coord: any) => ({
        lat: parseFloat(coord.lat),
        lng: parseFloat(coord.lng),
      }));
    return stops;
  }, [rideDatas?.location_coordinates]);

  useEffect(() => {
    bottomSheetRef.current?.present();
    if (zoneValue?.id) {
      dispatch(sosData({ zone_id: zoneValue.id }));
    }
  }, [zoneValue]);

  const handlePress = () => {
    navigate("PaymentMethod", { rideId, rideData: rideDatas });
    dispatch(allRides());
  };

  const handleDurationChange = (newDuration: any) => {
    setDuration(newDuration);
  };

  const handleSOSPress = () => {
    sosSheetRef.current?.present();
  };

  const handleContactPress = (phoneNumber: string) => {
    Linking.openURL(`tel:${phoneNumber}`);
  };

  const handleAddressChange = () => {
    navigate("AddressChange", { rideId, rideDatas });
  };

  const renderSosItem = useCallback(
    ({ item }) => (
      <View
        style={{
          marginHorizontal: windowWidth(18),
          borderRadius: windowHeight(5),
        }}
      >
        <TouchableOpacity
          style={[
            componentStyles.sosItem,
            {
              backgroundColor: isDark
                ? appColors.darkHeader
                : appColors.lightGray,
            },
          ]}
          onPress={() => handleContactPress(item.number)}
        >
          <View style={{ flexDirection: viewRTLStyle }}>
            <Image
              source={{ uri: item.sos_image_url }}
              style={styles.sosImage}
            />
            <View
              style={[
                styles.sideLine,
                {
                  backgroundColor: isDark
                    ? appColors.darkBorder
                    : appColors.border,
                },
              ]}
            />
            <Text
              style={[
                componentStyles.sosName,
                { color: isDark ? appColors.darkText : appColors.primaryText },
              ]}
            >
              {item?.title}
            </Text>
          </View>
        </TouchableOpacity>
      </View>
    ),
    []
  );

  const renderBackdrop = useCallback(
    (props) => (
      <BottomSheetBackdrop
        {...props}
        disappearsOnIndex={-1}
        appearsOnIndex={0}
      />
    ),
    []
  );
  const otpDigits =
    rideDatas?.parcel_delivered_otp != null
      ? rideDatas.parcel_delivered_otp.toString().padStart(4, "0").split("")
      : [];

  const orderedDigits = isRTL ? [...otpDigits].reverse() : otpDigits;

  return (
    <BottomSheetModalProvider>
      <View style={external.main}>
        <CustomBackHandler />
        <View style={{ flex: 1 }}>
          <Map
            markerImage={rideDatas?.vehicle_type?.vehicle_map_icon_url}
            userLocation={
              rideDatas?.location_coordinates?.[
              rideDatas?.location_coordinates?.length - 1
              ] || {}
            }
            waypoints={waypoints}
            onDurationChange={handleDurationChange}
            driverId={rideDatas?.driver?.id || ""}
            driverLocation={driverLocation}
            setDriverLocation={setDriverLocation}
          />
        </View>

        <BottomSheetModal
          ref={bottomSheetRef}
          index={1}
          snapPoints={snapPoints}
          enablePanDownToClose={false}
          enableDismissOnClose={false}
          handleComponent={null}
          backgroundStyle={{
            backgroundColor: isDark
              ? appColors.primaryText
              : appColors.whiteColor,
          }}
          handleIndicatorStyle={{
            backgroundColor: isDark ? appColors.whiteColor : appColors.primary,
            width: windowWidth(45),
            height: windowHeight(5),
          }}
        >
          <BottomSheetView style={{ paddingHorizontal: 16 }}>
            <View>
              <View
                style={{
                  backgroundColor: isDark
                    ? appColors.whiteColor
                    : appColors.primary,
                  width: windowWidth(45),
                  height: windowHeight(5),
                  alignSelf: "center",
                  marginTop: windowHeight(8),
                  borderRadius: windowWidth(99),
                }}
              />
              <View
                style={[
                  styles.mainView,
                  {
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.border,
                    borderWidth: windowWidth(2),
                    marginVertical: windowHeight(12),
                    borderRadius: windowWidth(25),
                  },
                ]}
              >
                <DriverData
                  driverDetails={rideDatas}
                  duration={duration}
                  onSOSPress={handleSOSPress}
                />
                {rideDatas?.service?.service_type === "parcel" && (
                  <>
                    <View
                      style={{
                        flexDirection: viewRTLStyle,
                        alignItems: "center",
                        justifyContent: "space-between",
                        marginTop: windowHeight(15),
                        marginVertical: windowHeight(20),
                      }}
                    >
                      <Text
                        style={[
                          styles.number1,
                          { color: textColorStyle, textAlign: textRTLStyle },
                        ]}
                      >
                        {translateData?.deliveryOtp}
                      </Text>
                      <View
                        style={{
                          flexDirection: viewRTLStyle,
                          justifyContent: "center",
                          marginTop: windowHeight(5),
                        }}
                      >
                        {orderedDigits?.map((digit, index) => (
                          <View
                            key={index}
                            style={[
                              styles.pinBox,
                              {
                                backgroundColor: isDark
                                  ? appColors.blackColor
                                  : appColors.blackColor,
                              },
                            ]}
                          >
                            <Text style={styles.pin}>{digit}</Text>
                          </View>
                        ))}
                      </View>

                    </View>
                  </>
                )}
              </View>
              <View
                style={[
                  external.fd_row,
                  {
                    backgroundColor: isDark
                      ? appColors.primaryText
                      : appColors.whiteColor,
                    borderRadius: windowHeight(15),
                    padding: windowHeight(8),
                    justifyContent: "space-between",
                    borderWidth: windowWidth(2),
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.border,
                    paddingHorizontal: windowWidth(20),
                    marginTop:
                      rideDatas?.service?.service_type === "parcel"
                        ? windowHeight(38)
                        : 0,
                  },
                ]}
              >
                <View>
                  <Text
                    style={{
                      fontFamily: appFonts.bold,
                      fontSize: fontSizes.FONT17,
                      color: textColorStyle,
                    }}
                  >
                    {translateData?.destinationpoint}
                  </Text>
                  <Text
                    style={{
                      fontFamily: appFonts.regular,
                      color: appColors.regularText,
                    }}
                  >
                    {rideDatas?.locations?.[rideDatas?.locations?.length - 1]
                      ?.length > 30
                      ? `${rideDatas?.locations?.[
                        rideDatas?.locations?.length - 1
                      ].slice(0, 30)}...`
                      : rideDatas?.locations?.[
                      rideDatas?.locations?.length - 1
                      ]}
                  </Text>
                </View>
                <TouchableOpacity
                  onPress={handleAddressChange}
                  style={external.fd_row}
                >
                  <View
                    style={{
                      borderLeftWidth: 1,
                      borderLeftColor: appColors.whiteColor,
                      marginHorizontal: windowWidth(12),
                    }}
                  />
                  <View
                    style={{ alignItems: "center", justifyContent: "center" }}
                  >
                    <Edit color={appColors.dotLight} />
                  </View>
                </TouchableOpacity>
              </View>

              {rideDatas?.ride_status?.slug === "completed" && (
                <View style={{ marginBottom: windowHeight(15) }}>
                  <TotalFare
                    handlePress={() => handlePress(rideDatas)}
                    fareAmount={rideDatas?.total || 0}
                    rideStatus={rideDatas?.ride_status?.slug || ""}
                  />
                </View>
              )}
            </View>
          </BottomSheetView>
        </BottomSheetModal>

        <BottomSheetModal
          ref={sosSheetRef}
          index={1}
          snapPoints={sosSnapPoints}
          enablePanDownToClose={true}
          backdropComponent={renderBackdrop}
          handleIndicatorStyle={{
            backgroundColor: appColors.primary,
            width: "13%",
          }}
          backgroundStyle={{
            borderTopLeftRadius: 16,
            borderTopRightRadius: 16,
            backgroundColor: isDark ? appColors.bgDark : appColors.whiteColor,
          }}
        >
          <BottomSheetView style={componentStyles.contentContainer}>
            <Text
              style={[
                componentStyles.title,
                { color: isDark ? appColors.whiteColor : appColors.blackColor },
              ]}
            >
              {translateData.keepYourselfSafe}
            </Text>
          </BottomSheetView>
          <BottomSheetFlatList
            data={sosValue?.data}
            keyExtractor={(item) => item.id.toString()}
            renderItem={renderSosItem}
            style={{ marginTop: windowHeight(20) }}
          />
        </BottomSheetModal>
      </View>
    </BottomSheetModalProvider>
  );
}

const componentStyles = StyleSheet.create({
  contentContainer: {
    width: "100%",
  },
  title: {
    fontSize: fontSizes.FONT22,
    color: appColors.primaryText,
    fontFamily: appFonts.bold,
    textAlign: "center",
  },
  sosItem: {
    marginTop: windowHeight(10),
    padding: windowHeight(10),
  },
  sosName: {
    fontFamily: appFonts.medium,
  },
  sosNumber: {},
});

export default Payment;
