import React, { useEffect, useState, useCallback } from "react";
import { Image, View, Linking, Platform } from "react-native";
import { external } from "../../../styles/externalStyle";
import { appColors } from "@src/themes";
import Images from "@utils/images";
import { styles } from "./styles";
import {
  getValue,
  setValue,
  deleteValue,
} from "../../../utils/localstorage/index";
import { useDispatch, useSelector } from "react-redux";
import {
  homeScreenPrimary,
  selfData,
  settingDataGet,
  taxidosettingDataGet,
  translateDataGet,
} from "../../../api/store/actions";
import { NoInternet, UpdateRequiredModal } from "@src/components";
import { useAppNavigation } from "@src/utils/navigation";
import DeviceInfo from "react-native-device-info";
import useSmartLocation from "@src/components/helper/locationHelper";
import { AppDispatch } from "@src/api/store";
import { useValues } from "@src/utils/context/index";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { ensureLocationAccess } from "../../../components/helper/permissionHelper";

export function Splash() {
  const { replace } = useAppNavigation();
  const { isDark, setIsRTL } = useValues();
  const dispatch = useDispatch<AppDispatch>();
  const { settingData, taxidoSettingData, serverStatus } = useSelector(
    (state) => state.setting
  );
  const [splashImage, setSplashImage] = useState(null);
  const [showNoInternet, setShowNoInternet] = useState(false);
  const [showUpdateModal, setShowUpdateModal] = useState(false);
  const { translateData } = useSelector((state) => state.setting);
  const { currentLatitude, currentLongitude } = useSmartLocation();

  useEffect(() => {
    const setDefaultLanguage = async () => {
      if (
        Array.isArray(settingData) ||
        !settingData?.values?.general?.default_language
      )
        return;

      const defaultLang = settingData.values.general.default_language.locale;

      let storedLang = await getValue("selectedLanguage");
      if (storedLang) {
        storedLang = storedLang.replace(/^"|"$/g, "");
      }

      if (storedLang != null) {
        const isRTL = storedLang === "ar";
        setIsRTL(isRTL);
        AsyncStorage.setItem("rtl", JSON.stringify(isRTL));
      } else {
        const isRTL = defaultLang === "ar";
        setIsRTL(isRTL);
        AsyncStorage.setItem("rtl", JSON.stringify(isRTL));
      }
    };

    setDefaultLanguage();
  }, [settingData]);

  useEffect(() => {
    const AppInfo = async () => {
      const version = await DeviceInfo.getVersion();
    };
    AppInfo();
  }, []);

  useEffect(() => {
    const loadSplashImage = async () => {
      try {
        const cachedImage = await getValue("splashImage");
        if (cachedImage) setSplashImage(cachedImage);
      } catch (error) {
        console.error("Error loading splash image:", error);
      }
    };
    loadSplashImage();
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      await dispatch(homeScreenPrimary());
      await dispatch(taxidosettingDataGet());
      await dispatch(translateDataGet());
      await dispatch(settingDataGet());
    };
    fetchData();
  }, [dispatch]);

  useEffect(() => {
    if (serverStatus === 500) {
      replace("NoInternalServer");
    }
  }, [serverStatus]);

  useEffect(() => {
    const updateSplashImage = async () => {
      const serverImage = !Array.isArray(taxidoSettingData)
        ? taxidoSettingData?.cabbooking_values?.setting?.splash_screen_url
        : null;
      try {
        if (serverImage) await setValue("splashImage", serverImage);
        else await deleteValue("splashImage");
      } catch (error) {
        console.error("Error updating splash image:", error);
      }
    };
    if (taxidoSettingData) updateSplashImage();
  }, [taxidoSettingData]);

  useEffect(() => {
    if (Array.isArray(settingData) || !settingData?.values?.maintenance) return;
    if (settingData?.values?.maintenance?.maintenance_mode == "1") {
      setShowNoInternet(true);
    } else {
      const handleLocationAndProceed = async () => {
        const granted = await ensureLocationAccess();
        if (granted) {
          proceedToNextScreen();
        }
      };
      handleLocationAndProceed();
    }
  }, [settingData]);

  const proceedToNextScreen = useCallback(async () => {
    try {
      const token = await getValue("token");
      const versionCode = await DeviceInfo.getVersion();
      const requiredVersion = !Array.isArray(taxidoSettingData)
        ? taxidoSettingData?.cabbooking_values?.setting?.app_version
        : null;
      const forceUpdate = !Array.isArray(taxidoSettingData)
        ? taxidoSettingData?.cabbooking_values?.activation?.force_update == "1"
        : false;

      if (forceUpdate && versionCode < requiredVersion) {
        setShowUpdateModal(true);
        return;
      }

      const waitForZone = async () => {
        if (token) {
          dispatch(selfData())
            .unwrap()
            .then((res) => {
              if (res?.status == 403 || !res?.status) {
                replace("SignIn");
              } else {
                replace("MyTabs");
              }
            })
            .catch((err) => { });
        } else {
          replace("Onboarding");
        }
      };
      await waitForZone();
    } catch (error) {
      console.error("Error in proceedToNextScreen:", error);
    }
  }, [dispatch, replace, taxidoSettingData]);

  const handleRefresh = useCallback(() => {
    dispatch(taxidosettingDataGet());
    dispatch(settingDataGet())
      .then((res) => {
        if (res?.payload._status == 500) {
          replace("NoInternalServer");
        } else {
        }
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  }, [dispatch]);

  if (showNoInternet) {
    return (
      <NoInternet
        onRefresh={handleRefresh}
        title={translateData.appUnderMaintenance}
        details={translateData.onlineShortly}
        image={isDark ? Images.maintenanceDark : Images.maintenance}
        infoIcon={false}
      />
    );
  }

  return (
    <View style={[external.fx_1, { backgroundColor: appColors.blackColor }]}>
      <View style={[external.ai_center, external.js_center, external.fx_1]}>
        <Image
          source={splashImage ? { uri: splashImage } : Images.splashUser}
          style={styles.img}
          onError={() => deleteValue("splashImage")}
        />
      </View>

      <UpdateRequiredModal
        visible={showUpdateModal}
        onUpdate={() => {
          const appId = DeviceInfo.getBundleId();
          if (Platform.OS === "android") {
            Linking.openURL(`market://details?id=${appId}`);
          } else {
            Linking.openURL(`itms-apps://itunes.apple.com/app/id${appId}`);
          }
        }}
      />
    </View>
  );
}
