import type { RootScreenProps } from '@/navigation/types';
import { Paths } from '@/navigation/paths';
import { useTranslation } from 'react-i18next';
import { Alert, Platform, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { GoogleSignin } from '@react-native-google-signin/google-signin';
import { appleAuth } from '@invertase/react-native-apple-authentication';
import DeviceInfo from 'react-native-device-info';

import { AUTH_CONFIG } from '@/config/auth';

import { useI18n } from '@/hooks';
import { useTheme } from '@/theme';

import { AssetByVariant, IconByVariant, Skeleton } from '@/components/atoms';
import { SafeScreen } from '@/components/templates';



function Login({ navigation }: RootScreenProps<Paths.Login>) {
  const { toggleLanguage } = useI18n();

  const {
    backgrounds,
    changeTheme,
    colors,
    components,
    fonts,
    gutters,
    layout,
    variant,
  } = useTheme();


  const onChangeTheme = () => {
    changeTheme(variant === 'default' ? 'dark' : 'default');
  };

  const onGoHome = () => {
    navigation.navigate(Paths.Home);
  }

  const onGoPage = (page: Paths) => {
    navigation.navigate(page);
  }


  const handleLogin = async () => {
    try {
      const deviceId = await DeviceInfo.getUniqueId();
      console.log('设备ID:', deviceId);

      if (Platform.OS === 'ios') {
        // iOS使用Apple登录
        await handleAppleLogin();
      } else {
        // Android使用Google登录
        await handleGoogleLogin();
      }
    } catch (error) {
      console.error('登录失败:', error);
      Alert.alert('登录失败', '请稍后重试');
    }
  };

  const handleAppleLogin = async () => {
    try {
      // 执行Apple登录请求
      const appleAuthRequestResponse = await appleAuth.performRequest({
        requestedOperation: appleAuth.Operation.LOGIN,
        requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
      });

      // 获取凭证状态
      const credentialState = await appleAuth.getCredentialStateForUser(
        appleAuthRequestResponse.user,
      );

      if (credentialState === appleAuth.State.AUTHORIZED) {
        console.log('Apple登录成功:', appleAuthRequestResponse);
        Alert.alert('登录成功', `欢迎 ${appleAuthRequestResponse.fullName?.givenName || '用户'}`);
      }
    } catch (error) {
      console.error('Apple登录失败:', error);
      throw error;
    }
  };

  const handleGoogleLogin = async () => {
    try {
      // 配置Google登录
      await GoogleSignin.configure({
        webClientId: AUTH_CONFIG.GOOGLE.WEB_CLIENT_ID,
        offlineAccess: true,
      });

      // 检查是否已登录
      await GoogleSignin.hasPlayServices();
      
      // 执行登录
      const userInfo = await GoogleSignin.signIn();
      console.log('Google登录成功:', userInfo);
      Alert.alert('登录成功', `欢迎 ${userInfo.data?.user.name || '用户'}`);
    } catch (error) {
      console.error('Google登录失败:', error);
      throw error;
    }
  };

  return (
    <SafeScreen> 
      <ScrollView>
        <View
          style={[
            layout.justifyCenter,
            layout.itemsCenter,
            gutters.marginTop_80,
          ]}
        >
          <View
            style={[layout.relative, backgrounds.gray100, components.circle250]}
          />

          <View style={[layout.absolute, gutters.paddingTop_80]}>
            <AssetByVariant
              path="tom"
              resizeMode="contain"
              style={{ height: 300, width: 300 }}
            />
          </View>
        </View>

        <View style={[gutters.paddingHorizontal_32, gutters.marginTop_40]}>
          <View style={[gutters.marginTop_40]}>
            <Text style={[fonts.size_40, fonts.gray800, fonts.bold]}>
              欢迎使用
            </Text>
            <Text
              style={[fonts.size_16, fonts.gray200, gutters.marginBottom_40]}
            >
              {/* {t('screen_example.description')} */}
            </Text>
          </View>

          <View
            style={[
              layout.row,
              layout.justifyBetween,
              layout.fullWidth,
              gutters.marginTop_16,
            ]}
          >
            <Skeleton
              height={64}
              loading={false}
              style={{ borderRadius: components.buttonCircle.borderRadius }}
              width={64}
            >
              <TouchableOpacity
                onPress={handleLogin}
                style={[components.buttonCircle, gutters.marginBottom_16]}
                testID="fetch-user-button"
              >
                <IconByVariant path="user" stroke={colors.purple500} />
              </TouchableOpacity>
            </Skeleton>

            <TouchableOpacity
              onPress={onGoHome}
              style={[components.buttonCircle, gutters.marginBottom_16]}
              testID="change-theme-button"
            >
              <IconByVariant path="home" stroke={colors.purple500} />
            </TouchableOpacity>

            <TouchableOpacity
              onPress={() => onGoPage(Paths.Pay)}
              style={[components.buttonCircle, gutters.marginBottom_16]}
              testID="change-theme-button"
            >
              <View>支付</View>
            </TouchableOpacity>

            <TouchableOpacity
              onPress={() => onGoPage(Paths.SubList)}
              style={[components.buttonCircle, gutters.marginBottom_16]}
              testID="change-theme-button"
            >
              <View>订阅</View>
            </TouchableOpacity>

            <TouchableOpacity
              onPress={onChangeTheme}
              style={[components.buttonCircle, gutters.marginBottom_16]}
              testID="change-theme-button"
            >
              <IconByVariant path="theme" stroke={colors.purple500} />
            </TouchableOpacity>

            <TouchableOpacity
              onPress={toggleLanguage}
              style={[components.buttonCircle, gutters.marginBottom_16]}
              testID="change-language-button"
            >
              <IconByVariant path="language" stroke={colors.purple500} />
            </TouchableOpacity>
          </View>
        </View>
      </ScrollView>
    </SafeScreen>
  );
}

export default Login;
