import React, { useEffect, useState } from "react";
import { View, Text } from "react-native";
import { appColors, windowHeight } from "@src/themes";
import { useValues } from "@src/utils/context";
import {
  NativeAd,
  NativeAdView,
  NativeAsset,
  NativeMediaView,
  NativeAssetType,
  TestIds,
  AdEventType,
} from "react-native-google-mobile-ads";
import { useSelector } from "react-redux";
import styles from "./styles";

type Props = {
  heights?: number;
  adsHeight?: number;
};

const NativeAdComponent = ({
  heights = windowHeight(40),
  adsHeight,
}: Props) => {
  const [nativeAd, setNativeAd] = useState<NativeAd | null>(null);
  const { translateData, taxidoSettingData } = useSelector(
    (state: any) => state.setting
  );
  const { isDark } = useValues();
  const NativeAdsId =
    taxidoSettingData?.cabbooking_values?.ads?.native_android_unit_id;

  useEffect(() => {
    let removeListener: any;

    NativeAd.createForAdRequest(TestIds.NATIVE)
      .then((ad) => {
        setNativeAd(ad);

        removeListener = ad.addAdEventListener(AdEventType.LOADED, () =>
          console.log("Native ad loaded")
        );

        ad.load();
      })
      .catch((error) => console.error("Error loading native ad:", error));

    return () => {
      if (removeListener) removeListener();
    };
  }, []);

  if (!nativeAd) {
    return (
      <View style={[styles.placeholder, { height: heights }]}>
        <Text>{translateData?.loadingAd}</Text>
      </View>
    );
  }

  return (
    <NativeAdView
      nativeAd={nativeAd}
      style={[styles.adView, { height: heights }]}
    >
      <NativeAsset assetType={NativeAssetType.HEADLINE}>
        <Text
          style={[
            styles.headline,
            { color: isDark ? appColors.whiteColor : appColors.blackColor },
          ]}
        >
          {nativeAd.headline}
        </Text>
      </NativeAsset>

      <NativeMediaView style={[styles.media, { height: adsHeight }]} />

      <NativeAsset assetType={NativeAssetType.CALL_TO_ACTION}>
        <View>
          <View style={styles.ctaButton}>
            <Text style={styles.ctaText}>{nativeAd.callToAction}</Text>
          </View>
        </View>
      </NativeAsset>
    </NativeAdView>
  );
};

export default NativeAdComponent;
