import { Redirect } from 'expo-router';
import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native';

import { useAuth } from '@/src/providers/auth-provider';

export default function IndexScreen() {
  const { isBootstrapping, bootstrapError, token, requiresTenantSelection, retryBootstrap, resetLocalSession } = useAuth();

  if (isBootstrapping) {
    return (
      <View style={styles.centered}>
        <ActivityIndicator size="large" />
        <Text style={styles.copy}>Initialisiere mobile Session...</Text>
      </View>
    );
  }

  if (bootstrapError) {
    return (
      <View style={styles.centered}>
        <Text style={styles.title}>Session konnte nicht gestartet werden</Text>
        <Text style={styles.copy}>{bootstrapError}</Text>
        <View style={styles.actions}>
          <Pressable style={styles.primaryButton} onPress={retryBootstrap}>
            <Text style={styles.primaryButtonText}>Erneut versuchen</Text>
          </Pressable>
          <Pressable style={styles.secondaryButton} onPress={resetLocalSession}>
            <Text style={styles.secondaryButtonText}>Lokale Session löschen</Text>
          </Pressable>
        </View>
      </View>
    );
  }

  if (!token) {
    return <Redirect href="/login" />;
  }

  if (requiresTenantSelection) {
    return <Redirect href="/tenant-select" />;
  }

  return <Redirect href="/(tabs)" />;
}

const styles = StyleSheet.create({
  centered: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    gap: 12,
    padding: 24,
  },
  copy: {
    fontSize: 14,
    color: '#4b5563',
    textAlign: 'center',
  },
  title: {
    fontSize: 20,
    fontWeight: '700',
    color: '#111827',
    textAlign: 'center',
  },
  actions: {
    width: '100%',
    gap: 10,
    marginTop: 4,
  },
  primaryButton: {
    minHeight: 44,
    borderRadius: 10,
    backgroundColor: '#69c350',
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 16,
  },
  primaryButtonText: {
    color: '#ffffff',
    fontWeight: '700',
  },
  secondaryButton: {
    minHeight: 44,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#d1d5db',
    backgroundColor: '#ffffff',
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 16,
  },
  secondaryButtonText: {
    color: '#374151',
    fontWeight: '600',
  },
});
