import { View, Text, Image, FlatList } from "react-native";
import React, { useState } from "react";
import { appColors, windowHeight, windowWidth } from "@src/themes";
import {
  CalenderSmall,
  ClockSmall,
  Gps,
  LocationFill,
  PickLocation,
} from "@src/utils/icons";
import { external } from "@src/styles/externalStyle";
import { styles } from "./styles";
import { useValues } from "@src/utils/context/index";
import {
  Button,
  formatDateTime,
  notificationHelper,
} from "@src/commonComponent";
import { useAppNavigation } from "@src/utils/navigation";
import { useDispatch, useSelector } from "react-redux";
import { userRideLocation, vehicleTypeDataGet } from "@src/api/store/actions";

export function Recentbooking({ recentRideData }) {
  const {
    bgFullStyle,
    textColorStyle,
    viewRTLStyle,
    isDark,
    textRTLStyle,
    Google_Map_Key,
    isRTL
  } = useValues();
  const dispatch = useDispatch();
  const [loadingIndex, setLoadingIndex] = useState(null);
  const { zoneValue } = useSelector((state: any) => state.zone);
  const { translateData } = useSelector((state) => state.setting);
  const { navigate }: any = useAppNavigation();

  if (!recentRideData || recentRideData.length === 0) {
    return null;
  }

  const convertToCoords = async (address) => {
    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) {
      return null;
    }
  };

  const convertStopsToCoords = async (stopList) => {
    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) {
        coordsArray.push(null);
      }
    }
    return coordsArray;
  };

  const gotoBook = async (item) => {
    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) => coord && coord.latitude != null && coord.longitude != null
        )
        .map((coord) => ({
          lat: coord.latitude,
          lng: coord.longitude,
        }));

      const payload = {
        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) {
      notificationHelper("", error, "error");
    } finally {
    }
  };

  const renderItem = ({ item, index }: any) => {
    const { date, time } = formatDateTime(item?.created_at);

    return (
      <View
        style={[
          styles.view,
          {
            borderColor: isDark ? appColors.darkBorder : "#CCCCCC",
            backgroundColor: isDark
              ? appColors.darkPrimary
              : appColors.whiteColor,
          },
        ]}
      >
        <View
          style={{
            flexDirection: viewRTLStyle,
            paddingHorizontal: windowHeight(5),
          }}
        >
          <View
            style={[
              styles.imageView,
              {
                backgroundColor: isDark
                  ? appColors.primaryText
                  : appColors.lightGray,
              },
            ]}
          >
            <Image
              source={{
                uri: item?.vehicle_type?.vehicle_image_url,
              }}
              style={styles.img}
            />
          </View>
          <View
            style={[
              {
                flexDirection: viewRTLStyle,
                alignItems: "flex-start",
                marginHorizontal: windowWidth(5),
              },
            ]}
          >
            <View>
              <View
                style={[
                  styles.textView,
                  { flexDirection: viewRTLStyle, alignItems: "center" },
                ]}
              >
                <View
                  style={[
                    styles.box,
                    {
                      backgroundColor: isDark
                        ? appColors.solidBorder
                        : appColors.lightGray,
                    },
                  ]}
                >
                  <Text
                    style={[
                      styles.textId,
                      {
                        color: isDark
                          ? appColors.whiteColor
                          : appColors.primaryText,
                      },
                    ]}
                  >
                    #{item?.ride_number}
                  </Text>
                </View>
                <View
                  style={[
                    styles.box1,
                    {
                      backgroundColor: isDark
                        ? appColors.type1
                        : appColors.type,
                    },
                  ]}
                >
                  <Text style={styles.price}>{item?.vehicle_type?.name}</Text>
                </View>
              </View>
              <View
                style={[
                  styles.viewWidth1,
                  { flexDirection: viewRTLStyle, marginTop: windowHeight(1) },
                ]}
              >
                <View
                  style={[
                    styles.clockSmallView1,
                    { flexDirection: viewRTLStyle },
                  ]}
                >
                  <View style={styles.clockSmall}>
                    <CalenderSmall />
                  </View>
                  <Text style={styles.date}>{date}</Text>
                </View>
                <View style={styles.divider} />
                <View
                  style={[
                    styles.clockSmallView,
                    { flexDirection: viewRTLStyle },
                  ]}
                >
                  <View style={styles.clockSmall}>
                    <ClockSmall />
                  </View>
                  <Text
                    style={[styles.date, { marginBottom: windowHeight(0.5) }]}
                  >
                    {time}
                  </Text>
                </View>
              </View>
            </View>
          </View>
          <Text
            style={[
              styles.price1,
              { color: isDark ? appColors.whiteColor : appColors.blackColor },
            ]}
          >
            {zoneValue?.currency_symbol}
            {item?.total}
          </Text>
        </View>
        <View
          style={[
            styles.line,
            {
              backgroundColor: isDark
                ? appColors.solidBorder
                : appColors.lightGray,
            },
          ]}
        />

        <View
          style={[
            { flexDirection: viewRTLStyle },
            {
              backgroundColor: isDark
                ? appColors.darkPrimary
                : appColors.whiteColor,
            },
          ]}
        >
          <View style={[external.pv_10]}>
            <View style={[styles.addressView, { flexDirection: viewRTLStyle }]}>
              <View
                style={[
                  styles.searchView,
                  {
                    backgroundColor: isDark
                      ? appColors.primaryText
                      : appColors.lightGray,
                    flexDirection: viewRTLStyle,
                  },
                ]}
              >
                <PickLocation colors={appColors.dotLight} />
              </View>
              <View>
                <Text
                  style={[
                    styles.itemStyle,
                    { color: textColorStyle, width: windowWidth(310), textAlign: isRTL ? 'right' : 'left' },
                  ]}
                >
                  {item?.locations[0]?.length > 42
                    ? `${item.locations[0].slice(0, 35)}...`
                    : item?.locations[0]}
                </Text>
                <Text
                  style={[
                    styles.locationType,
                    { color: isDark ? appColors.darkText : appColors.gray, textAlign: isRTL ? 'right' : 'left' },
                  ]}
                >
                  {translateData?.pickupLocation}
                </Text>
              </View>
            </View>
            <View style={[styles.dot, { alignSelf: isRTL ? 'flex-end' : 'flex-start' }]}></View>
            <View
              style={[
                styles.dashedLine,
                {
                  borderColor: isDark ? appColors.darkBorder : appColors.border,
                  alignSelf: isRTL ? 'flex-start' : 'flex-end'
                },
              ]}
            />
            <View
              style={[
                styles.searchView,
                styles.kmView,
                {
                  backgroundColor: isDark
                    ? appColors.primaryText
                    : appColors.lightGray,
                  flexDirection: viewRTLStyle,
                  borderColor: isDark
                    ? appColors.darkPrimary
                    : appColors.lightGray,
                  alignSelf: isRTL ? 'flex-start' : 'flex-end'
                },
              ]}
            >
              <Text
                style={[
                  styles.textId,
                  {
                    color: isDark ? appColors.whiteColor : appColors.gray,
                    width: windowWidth(35),
                    textAlign: "center",
                  },
                ]}
              >
                {Number(item?.distance).toFixed(1)} {item?.distance_unit}
              </Text>{" "}
            </View>
            <View style={[styles.addressView, { flexDirection: viewRTLStyle }]}>
              <View
                style={[
                  styles.searchView,
                  {
                    backgroundColor: isDark
                      ? appColors.primaryText
                      : appColors.lightGray,
                    flexDirection: viewRTLStyle,
                  },
                ]}
              >
                <LocationFill color={appColors.dotLight} />
              </View>
              <View>
                <Text
                  style={[
                    styles.pickUpLocationStyles,
                    { color: textColorStyle, textAlign: isRTL ? 'right' : 'left' },
                  ]}
                >
                  {item?.locations[item?.locations.length - 1]?.length > 35
                    ? item?.locations[item?.locations.length - 1].substring(
                      0,
                      35
                    ) + "..."
                    : item?.locations[item?.locations.length - 1]}
                </Text>
                <Text
                  style={[
                    styles.locationType,
                    { color: isDark ? appColors.darkText : appColors.gray, textAlign: isRTL ? 'right' : 'left' },
                  ]}
                >
                  {translateData?.dropOffLocation || "Destination"}
                </Text>
              </View>
            </View>
          </View>
        </View>

        <View
          style={{
            paddingHorizontal: windowHeight(10),
            marginTop: windowHeight(5),
          }}
        >
          <Button
            backgroundColor={appColors.blackColor}
            onPress={() => {
              setLoadingIndex(index);
              gotoBook(item).finally(() => setLoadingIndex(null));
            }}
            textColor={appColors.whiteColor}
            title={translateData.BookAgainTextttt}
            loading={loadingIndex === index}
          />
        </View>
      </View>
    );
  };

  return (
    <View
      style={[
        styles.mainContainer,
        {
          backgroundColor: isDark ? appColors.solidBorder : appColors.lightGray,
        },
      ]}
    >
      <Text
        style={[
          styles.recentRides,
          {
            color: isDark ? appColors.whiteColor : appColors.primaryText,
            textAlign: textRTLStyle,
          },
        ]}
      >
        {translateData.homeRecentRides}
      </Text>
      <FlatList
        data={recentRideData}
        keyExtractor={(item) => item?.id}
        renderItem={renderItem}
        contentContainerStyle={styles.container}
        showsVerticalScrollIndicator={false}
      />
    </View>
  );
}
