import { AnimatedSplashOverlay } from '@/components/animated-icon';
import { antdTheme } from '@/constants/antd-theme';
import { Colors } from '@/constants/theme';
import '@/global.css';
import api from '@/utils/api';
import { AuthProvider } from '@/utils/auth';
import { getGlobalStorage } from '@/utils/storage';
import { Modal, Provider, Toast } from '@ant-design/react-native';
import {
  DefaultTheme as ReactNavigationDefaultTheme,
  Theme,
  ThemeProvider,
} from '@react-navigation/native';
import * as application from 'expo-application';
import { useFonts } from 'expo-font';
import { Image } from 'expo-image';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import * as updates from 'expo-updates';
import { useEffect, useState } from 'react';
import { Linking, Platform, View } from 'react-native';


SplashScreen.preventAutoHideAsync();

// import * as app from 'expo-'
export const DefaultTheme: Theme = {
  ...ReactNavigationDefaultTheme,
  colors: {
    ...ReactNavigationDefaultTheme.colors,
    primary: antdTheme.brand_primary,
    background: antdTheme.fill_body,
    card: antdTheme.fill_base,
    text: antdTheme.color_text_base,
    border: antdTheme.border_color_base,
    notification: antdTheme.brand_error,
  },
};


export default function RootLayout() {
  const [initing, setIniting] = useState(true);


  // const colorScheme = useColorScheme();
  const [fontsLoaded] = useFonts({
    antoutline: require('@ant-design/icons-react-native/fonts/antoutline.ttf'),
  });

  useEffect(() => {
    const now = Date.now() / 1000;

    async function checkApp() {
      try {
        const lastTime = parseInt(getGlobalStorage().getString('last_update_app') || '0');
        if (now - lastTime < 15 * 60000) {
          SplashScreen.hide();
          return true;
        }
        const {
          version,
          package: pkg,
          type,
          force,
        } = await api.post<{ version: string, package: string, type: 'apk' | 'url', force: boolean }>('common/check_version', {
          platform: Platform.OS,
          version: application.nativeApplicationVersion,
        }, { timeout: 5000 });
        getGlobalStorage().set('last_update_app', now);

        SplashScreen.hide();
        if (!version || version === application.nativeApplicationVersion) {
          return true;
        }
        const va = version.split('.');
        let vb = (application.nativeApplicationVersion || '').split('.');
        let update = false;
        for (let i = 0; i < va.length; i++) {
          if (vb.length <= i || parseInt(va[i]) > parseInt(vb[i])) {
            update = true;
            break;
          }
        }
        if (!update) {
          return true;
        }
        let ok = true;
        do {
          ok = await new Promise<boolean>((resolve, reject) => {
            const actions: any[] = [
              {
                text: '立即更新',
                onPress: async () => {
                  if (type === 'url' || type === 'apk') {
                    if (pkg) {
                      if (await Linking.canOpenURL(pkg)) {
                        Linking.openURL(pkg);
                        resolve(false);
                        return;
                      }
                    }
                    Modal.alert('无法自动更新', "请前往应用商店更新");
                    resolve(true);
                    return;
                  }
                  resolve(true);
                }
              }
            ];
            if (!force) {
              actions.unshift({
                text: '否',
                style: { color: Colors.textSecondary },
                onPress: () => {
                  resolve(true);
                }
              });
            }
            Modal.alert(`${version}可更新`, force ? '请更新后继续使用' : '是否立即更新？', actions);
          });
        } while (!ok);
        return true;
      } catch (e) {

        SplashScreen.hide();
        console.warn(e);
        return true;
      }
    }

    (async () => {
      if (__DEV__) {
        setIniting(false);
        return;
      }
      if (!await checkApp()) {
        setIniting(false);
        return;
      }

      try {

        const res = await updates.checkForUpdateAsync();
        // alert(JSON.stringify(res))
        if (res.isAvailable) {

          Modal.alert("发现热更新", "需要立即下载", [
            {
              text: '确认',
              onPress: async () => {
                const l = Toast.loading("正在下载更新 ...");
                try {
                  await updates.fetchUpdateAsync();
                  await updates.reloadAsync();
                  // eslint-disable-next-line @typescript-eslint/no-unused-vars
                } catch (e) {
                  Modal.alert("提示", "更新遇到问题");
                }
                Toast.remove(l);
              }
            }
          ], () => false);
        }

        // eslint-disable-next-line @typescript-eslint/no-unused-vars
      } catch (e) {
        // alert(e?.message || e+"");
      }
      setIniting(false);

    })();

  }, []);



  return (
    <ThemeProvider value={DefaultTheme}>
      <Provider theme={antdTheme}>
        {(!initing && fontsLoaded) &&
          <AuthProvider>
            <AnimatedSplashOverlay />
            <Stack screenOptions={{
              headerShown: true,
              headerTransparent: true,
              headerBlurEffect: 'light',
              headerBackButtonDisplayMode: 'minimal',
              headerBackground: Platform.OS === 'android' ? () => <View style={{ flex: 1, backgroundColor: 'rgba(255, 255, 255, 0.9)' }} /> : undefined,
              // headerLeft: ({ canGoBack }) => canGoBack && <Icon name="arrow-left" size={24} />,
              animation: 'ios_from_right'
            }}>
              <Stack.Screen name="(tabs)" options={{ headerShown: false, }} />
              <Stack.Screen name="sign-in" options={{ animation: 'fade_from_bottom' }} />
            </Stack>
          </AuthProvider>}
      </Provider>
      {initing && <View className='absolute left-0 top-0 right-0 bottom-0 bg-[#f6f6f6] z-50'>
        <Image contentFit='contain' style={{ flex: 1 }} source={require('@/assets/images/uploading.jpg')} />
      </View>}
    </ThemeProvider>
  );
}
