import React, { useEffect, useState } from "react";
import { StatusBar } from "expo-status-bar";
import { PaperProvider } from "react-native-paper";
import { View, ActivityIndicator, StyleSheet } from "react-native";
import Navigation from "./src/navigation";
import { theme, colors } from "./src/theme";
import { useAuthStore } from "./src/stores/authStore";
import { useConstitutionStore } from "./src/stores/constitutionStore";
import { useChatStore } from "./src/stores/chatStore";
import { useSettingsStore } from "./src/stores/settingsStore";
import { AlertProvider } from "./src/components";

export default function App() {
  const [isReady, setIsReady] = useState(false);
  const initAuth = useAuthStore((state) => state.init);
  const user = useAuthStore((state) => state.user);
  const initConstitution = useConstitutionStore((state) => state.init);
  const fetchConstitutionResult = useConstitutionStore(
    (state) => state.fetchResult
  );
  const initChat = useChatStore((state) => state.init);
  const initSettings = useSettingsStore((state) => state.init);

  useEffect(() => {
    async function init() {
      try {
        await Promise.all([
          initAuth(),
          initConstitution(),
          initChat(),
          initSettings(),
        ]);
      } finally {
        setIsReady(true);
      }
    }
    init();
  }, []);

  // 登录状态变化时重新获取体质结果
  useEffect(() => {
    if (user) {
      fetchConstitutionResult();
    }
  }, [user]);

  if (!isReady) {
    return (
      <View style={styles.loading}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  return (
    <PaperProvider theme={theme}>
      <AlertProvider>
        <StatusBar style="auto" />
        <Navigation />
      </AlertProvider>
    </PaperProvider>
  );
}

const styles = StyleSheet.create({
  loading: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: colors.background,
  },
});
