import { useState } from 'react';
import { View, Text, StyleSheet, Pressable, ActivityIndicator } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import * as Linking from 'expo-linking';
import { devLogin } from '../../../api/auth';
import { WEB_URL } from '../../../api/client';
import { useAuthStore } from '../../../store/authStore';
import { colors, spacing, typography } from '../../../theme';

// Pas de flow OAuth natif dédié au mobile (SDK Google Sign-In, expo-auth-session) : ça
// exigerait un Development Build (Expo Go ne peut pas enregistrer de scheme personnalisé
// pour un redirect OAuth) et un client OAuth Google séparé. À la place, on rouvre le
// flow web existant (`/connect/google`, déjà en prod) dans le navigateur système, et le
// backend redirige vers l'URL de retour du device (`exp://.../--/auth-callback` en dev,
// le scheme de l'app en build standalone) avec un JWT en query string une fois connecté —
// voir SecurityController::connectAction() + GoogleAuthenticator::MOBILE_RETURN_SESSION_KEY.
export function LoginScreen() {
  const setToken = useAuthStore((state) => state.setToken);
  const [isLoggingIn, setIsLoggingIn] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleGoogleLogin() {
    setIsLoggingIn(true);
    setError(null);
    try {
      const returnUrl = Linking.createURL('auth-callback');
      const authUrl = `${WEB_URL}/connect/google?mobile_return=${encodeURIComponent(returnUrl)}`;
      const result = await WebBrowser.openAuthSessionAsync(authUrl, returnUrl);

      if (result.type !== 'success') {
        setError('Connexion annulée.');
        return;
      }

      const { queryParams } = Linking.parse(result.url);
      const token = queryParams?.token;
      if (typeof token !== 'string') {
        setError(
          queryParams?.error === 'auth_failed' ? "Compte introuvable ou accès refusé." : 'Connexion impossible.'
        );
        return;
      }

      await setToken(token);
    } catch {
      setError('Connexion impossible — vérifie ta connexion.');
    } finally {
      setIsLoggingIn(false);
    }
  }

  async function handleDevLogin() {
    setIsLoggingIn(true);
    setError(null);
    try {
      const { token } = await devLogin();
      await setToken(token);
    } catch {
      setError('Connexion dev impossible — vérifie que le backend tourne.');
    } finally {
      setIsLoggingIn(false);
    }
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Assistant Santé</Text>
      <Pressable style={styles.button} onPress={handleGoogleLogin} disabled={isLoggingIn}>
        {isLoggingIn ? <ActivityIndicator color="#fff" /> : <Text style={styles.buttonText}>Continuer avec Google</Text>}
      </Pressable>

      {__DEV__ && (
        <Pressable style={[styles.button, styles.devButton]} onPress={handleDevLogin} disabled={isLoggingIn}>
          {isLoggingIn ? (
            <ActivityIndicator color={colors.primary} />
          ) : (
            <Text style={styles.devButtonText}>Connexion dev</Text>
          )}
        </Pressable>
      )}

      {error && <Text style={styles.error}>{error}</Text>}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.background,
    padding: spacing.lg,
    gap: spacing.md,
  },
  title: {
    ...typography.title,
    color: colors.text,
    marginBottom: spacing.xl,
  },
  button: {
    backgroundColor: colors.primary,
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.lg,
    borderRadius: 8,
  },
  buttonText: {
    color: '#fff',
    fontWeight: '600',
  },
  devButton: {
    backgroundColor: colors.surface,
    opacity: 1,
    borderWidth: 1,
    borderColor: colors.border,
  },
  devButtonText: {
    color: colors.text,
    fontWeight: '600',
  },
  error: {
    ...typography.caption,
    color: colors.danger,
  },
});
