import { Image, Text, TouchableOpacity, View, StyleSheet } from "react-native";
import React, { memo, useEffect } from "react";
import { external } from "../../../styles/externalStyle";
import { styles } from "../styles";
import { commonStyles } from "../../../styles/commonStyle";
import {
  appColors,
  appFonts,
  fontSizes,
  windowHeight,
  windowWidth,
} from "@src/themes";
import { Info } from "@src/utils/icons";
import { BookRideItemType, ItemType } from "./types";
import { useValues } from "@src/utils/context/index";

export const BookRideItem = memo(function BookRideItem({
  item,
  onPress,
  isSelected,
  onPressAlternate,
  isDisabled,
  couponsData,
  onPriceCalculated,
  selectedPrefsValue,
}: BookRideItemType) {
  const { viewRTLStyle, isDark } = useValues();

  const originalFare = Number(item?.charges?.total ?? 0);
  if (originalFare <= 0) return null;

  const prefsTotal =
    isSelected && Array.isArray(selectedPrefsValue)
      ? selectedPrefsValue.reduce(
          (sum, pref) => sum + Number(pref.price ?? 0),
          0
        )
      : 0;

  let finalFare = Number((originalFare + prefsTotal).toFixed(2));

  const isCouponApplicable =
    couponsData?.success &&
    (couponsData?.is_apply_all === 1 ||
      couponsData?.applicable_vehicles?.includes(item?.id));

  let discountedFare = originalFare;
  let couponSaving = 0;

  if (isCouponApplicable) {
    const discountValue = `${couponsData?.amount ?? 0}`;
    const flatValue = couponsData?.total_coupon_discount ?? 0;

    if (couponsData?.coupon_type === "percentage") {
      couponSaving = originalFare * (Number(discountValue) / 100);
    } else {
      couponSaving = flatValue;
    }

    couponSaving = Number(couponSaving.toFixed(2));

    discountedFare = Math.max(
      0,
      Number((originalFare - couponSaving).toFixed(2))
    );

    if (isSelected) {
      discountedFare = Number((discountedFare + prefsTotal).toFixed(2));
    }
  }

  const finalPrice = isCouponApplicable ? discountedFare : finalFare;

  useEffect(() => {
    if (onPriceCalculated) {
      onPriceCalculated(item?.id, finalPrice);
    }
  }, [finalPrice, selectedPrefsValue, isSelected]);

  const handlePress = (item: ItemType | any) => {
    if (isSelected) {
      onPressAlternate?.(item);
    } else {
      onPress?.(item);
    }
  };

  return (
    <TouchableOpacity
      activeOpacity={0.7}
      style={[
        styles.container,
        {
          borderColor: isSelected
            ? isDark
              ? appColors.solidBorder
              : appColors.lightGray
            : isDark
            ? appColors.darkBorder
            : appColors.loaderPrimary,
          backgroundColor: isSelected
            ? isDark
              ? appColors.solidBorder
              : appColors.lightGray
            : isDark
            ? appColors.darkPrimary
            : appColors.whiteColor,
        },
      ]}
      onPress={() => handlePress(item)}
      disabled={isDisabled}
    >
      <View
        style={{
          alignItems: "center",
          justifyContent: "center",
          height: windowWidth(65),
          backgroundColor: isSelected
            ? isDark
              ? appColors.primaryText
              : appColors.whiteColor
            : isDark
            ? appColors.bgDark
            : appColors.lightGray,
          margin: windowHeight(2),
          borderRadius: windowHeight(4),
          width: windowWidth(115),
          alignSelf: "center",
        }}
      >
        <Image
          style={[styles.img, isDisabled && !isSelected && { opacity: 0.5 }]}
          source={{ uri: item?.vehicle_image_url }}
        />
      </View>

      <View
        style={[
          external.js_space,
          external.mh_8,
          { marginTop: windowHeight(5) },
        ]}
      >
        <View
          style={{
            flexDirection: viewRTLStyle,
            justifyContent: "space-between",
          }}
        >
          <Text
            style={[
              commonStyles.regularText,
              styles.vehicleName,
              isDisabled && !isSelected && { color: "gray" },
            ]}
          >
            {item?.name}
          </Text>
          <Info />
        </View>
        <View>
          <View>
            {isCouponApplicable ? (
              <>
                <Text
                  style={{
                    fontFamily: appFonts.regular,
                    fontSize: fontSizes.FONT12,
                    textDecorationLine: "line-through",
                    color: appColors.primaryText,
                  }}
                >
                  {item?.currency_symbol}
                  {originalFare.toFixed(2)}
                </Text>
                <Text
                  style={{
                    fontFamily: appFonts.medium,
                    fontSize: fontSizes.FONT14,
                    color: appColors.blackColor,
                  }}
                >
                  {item?.currency_symbol}
                  {discountedFare.toFixed(2)}
                </Text>
              </>
            ) : (
              <Text
                style={{
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT14,
                  color: isDark ? appColors.darkText : appColors.blackColor,
                }}
              >
                {item?.currency_symbol}
                {finalFare.toFixed(2)}
              </Text>
            )}
          </View>
        </View>
      </View>

      {isDisabled && !isSelected && (
        <View
          style={{
            ...StyleSheet.absoluteFillObject,
            backgroundColor: appColors.transparentBlack,
            borderRadius: styles.container.borderRadius,
          }}
          pointerEvents="none"
        />
      )}
    </TouchableOpacity>
  );
});
