import React, {useContext, useState} from "react";
import {Image, Platform, ScrollView} from "react-native";

import {StackScreenProps} from "@react-navigation/stack";
import Config from "react-native-config";

import Alert from "@components/alert";
import Background from "@components/background";
import Label from "@components/label";
import Button from "@components/primaryButton";
import StepTextView from "@components/stepTextView";

import {DEFAULT_INITIAL_ALERT_STATUS} from "@config/constants/AppConstants";
import {IOS_LOCAL_NETWORK_CHECK_ASYNC_STORAGE_KEY} from "@config/constants/DaikinLiteConstants";
import {DeviceType} from "@config/constants/DeviceTypeConstants";
import {HomeNavigatorParamList} from "@config/constants/NavConstants";
import {PermissionStatus} from "@config/constants/PermissionConstants";
import {LITE_SSID} from "@config/constants/ThermostatConstants";
import {IOS_LOCAL_NETWORK_TIMEOUT} from "@config/constants/TimeoutConstants";
import {translationKeys} from "@config/constants/TranslationConstants";
import {getLocalizationContext} from "@config/Translations";
import {iAlertState} from "@config/types/CommonTypes";

import {DeviceModelContext} from "@context/deviceModel";
import localStorage from "@services/asyncStorage";
import {useAppDispatch} from "@store/Hooks";
import {
	hideLoader as hideFanLoader,
	showLoader as showFanLoader,
} from "@store/loader/LoaderSlice";
import * as miniThermostatThunkActions from "@store/miniThermostat/ThunkActions";
import {disableAppStateListener} from "@store/settings/SettingsSlice";

import Page from "@styles/Page";
import {useThemeAwareObject} from "@styles/theming/ThemingHelper";
import {
	checkForLocationPermission,
	triggerAndroidLocationPermissionPopUp,
} from "@utils/LocationPermissionUtil";
import {checkAndConnectToWifiSSID} from "@utils/WifiManagerUtils";

import {getStepImage} from "./ImageHelper";
import Styles from "./Styles";

type Props = StackScreenProps<
	HomeNavigatorParamList,
	"ConfigureWifiStepIIScreen"
>;

const ConfigureWifiStepIIScreen = ({navigation}: Props) => {
	const {translate} = useContext(getLocalizationContext());
	const context = useContext(DeviceModelContext);

	const styles = useThemeAwareObject(Styles.createStyles);

	const dispatch = useAppDispatch();

	const [alertStatus, setAlertStatus] = useState<iAlertState>(
		DEFAULT_INITIAL_ALERT_STATUS,
	);

	/**
	 * Function which shows or hide loader based on boolean value passed
	 *
	 * @param loading
	 */
	const showLoader = (loading: boolean) => {
		if (loading) {
			dispatch(showFanLoader());
		} else {
			dispatch(hideFanLoader({className: "ConfigureWifiStepIIScreen"}));
		}
	};

	/**
	 * Sets the alert info to dismissed state.
	 */
	const onDismissAlert = () => {
		setAlertStatus({
			isVisible: false,
			title: alertStatus.title,
			message: alertStatus.message,
			positiveBtnLabel: alertStatus.positiveBtnLabel,
			negativeBtnLabel: alertStatus.negativeBtnLabel,
			onPress: null,
			onCancel: null,
		});
	};

	const onNavigateBack = () => {
		onDismissAlert();
		navigation.goBack();
	};

	const onNavigate = () => {
		showLoader(false);
		navigation.navigate("ConfigureWifiNetworkScreen");
	};

	const onNavigateToConfigureThermostatScreen = () => {
		onDismissAlert();
		navigation.navigate("ConfigureThermostatScreen", {
			deviceType: DeviceType.oneLite,
			ssidPrefix: LITE_SSID,
			password: Config.DAIKIN_LITE_PASSWORD as string,
		});
	};

	/**
	 * Allow to display a GoogleMap like android popup to ask for user to enable location services if disabled
	 */
	const showAndroidLocationPermissionPopUp = async () => {
		const {status} = await triggerAndroidLocationPermissionPopUp(
			setAlertStatus,
			onDismissAlert,
		);
		if (status === PermissionStatus.granted) {
			getWifiSSID();
		}
	};

	const onNavigateBasedOnPlatform = async () => {
		const localNetworkPermissionChecked = await localStorage.getItem(
			IOS_LOCAL_NETWORK_CHECK_ASYNC_STORAGE_KEY,
		);
		if (
			Platform.OS === "ios" &&
			(localNetworkPermissionChecked === null ||
				JSON.parse(localNetworkPermissionChecked) === false)
		) {
			const response = await dispatch(miniThermostatThunkActions.getWifiList());
			if (response.meta.requestStatus === "rejected") {
				await localStorage.setItem(
					IOS_LOCAL_NETWORK_CHECK_ASYNC_STORAGE_KEY,
					JSON.stringify(true),
				);
				setTimeout(() => {
					onNavigate();
				}, IOS_LOCAL_NETWORK_TIMEOUT);
			} else {
				onNavigate();
			}
		} else {
			onNavigate();
		}
	};

	/**
	 * Checks the current wifi ssid
	 */
	const getWifiSSID = async () => {
		const isConnected = await checkAndConnectToWifiSSID(
			LITE_SSID,
			Config.DAIKIN_LITE_PASSWORD as string,
			setAlertStatus,
			onDismissAlert,
			showLoader,
			true,
			onNavigate,
			onNavigateBack,
			onNavigateToConfigureThermostatScreen,
		);
		if (isConnected) {
			await onNavigateBasedOnPlatform();
		}
	};

	/**
	 * Called on press of next button
	 */
	const onPressDiscover = async () => {
		dispatch(disableAppStateListener());
		const {status} = await checkForLocationPermission(
			setAlertStatus,
			onDismissAlert,
		);
		if (Platform.OS === "android") {
			if (status === PermissionStatus.granted) {
				showAndroidLocationPermissionPopUp();
			}
		} else if (Platform.OS === "ios") {
			if (status === PermissionStatus.granted) {
				getWifiSSID();
			}
		}
	};

	return (
		<Background>
			<Alert
				visible={alertStatus.isVisible}
				title={alertStatus.title}
				description={alertStatus.message}
				positiveButtonTitle={
					alertStatus.positiveBtnLabel ||
					translate(translationKeys.alert.okayButtonLabel)
				}
				negativeButtonTitle={alertStatus.negativeBtnLabel}
				onPress={alertStatus.onPress || onDismissAlert}
				onCancel={alertStatus.onCancel || onDismissAlert}
				isWifiEnableAlert={alertStatus.isWifiEnableAlert}
			/>
			<ScrollView style={Page.container}>
				<Image
					source={{uri: getStepImage(context?.deviceModel)}}
					resizeMode="contain"
					style={styles.image}
				/>
				<StepTextView
					pointNo="4"
					style={styles.step}
					description={translate(translationKeys.configureWifi.point[3])}
				/>

				<Button
					title={translate(translationKeys.buttonTitle.continue)}
					style={[styles.nextButton]}
					onPress={onPressDiscover}
				/>

				<Label
					text={translate(translationKeys.configureWifi.description.step2)}
					style={styles.description}
				/>
			</ScrollView>
		</Background>
	);
};

export default ConfigureWifiStepIIScreen; this is my current wifi connection code now create a similar dummy screen with the wifi connection