import { useState } from 'react';
import { StyleSheet, Text, View, TextInput, Button, ScrollView, ActivityIndicator } from 'react-native';
import JecnaapiReactNative from 'jecnaapi-react-native';

export default function App() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<string>('No data yet. Please login.');

  const handleTestLoginAndFetch = async () => {
    if (!username || !password) {
      setResult('Error: Enter username and password');
      return;
    }

    setLoading(true);
    setResult('Logging in...');

    try {
      // 1. Call the raw native Kotlin bridge
      const loginSuccess = await JecnaapiReactNative.login(username, password);
      
      if (loginSuccess) {
        setResult('Login Successful! Fetching profile...');
        
        // 2. Fetch the raw JSON string
        const rawProfileString = await JecnaapiReactNative.getStudentProfile();
        
        // 3. Manually parse it (since you kept the default export)
        const profile = JSON.parse(rawProfileString);
        
        // Display it nicely on screen
        setResult(JSON.stringify(profile, null, 2));
      } else {
        setResult('Login failed. Check credentials.');
      }
    } catch (error: any) {
      setResult(`Bridge Error: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.header}>JecnaAPI Native Tester</Text>
      
      <TextInput
        style={styles.input}
        placeholder="Username"
        value={username}
        onChangeText={setUsername}
        autoCapitalize="none"
      />
      <TextInput
        style={styles.input}
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
      />

      <Button title="Test Login & Fetch Profile" onPress={handleTestLoginAndFetch} disabled={loading} />

      {loading && <ActivityIndicator style={{ marginTop: 20 }} size="large" color="#0000ff" />}

      <ScrollView style={styles.resultBox}>
        <Text style={styles.resultText}>{result}</Text>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    paddingTop: 80,
    backgroundColor: '#F5FCFF',
  },
  header: {
    fontSize: 22,
    fontWeight: 'bold',
    marginBottom: 20,
    textAlign: 'center',
  },
  input: {
    height: 50,
    borderColor: '#ccc',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 15,
    paddingHorizontal: 15,
    backgroundColor: '#fff',
  },
  resultBox: {
    marginTop: 20,
    flex: 1,
    backgroundColor: '#1e1e1e',
    borderRadius: 8,
    padding: 15,
  },
  resultText: {
    color: '#00FF00',
    fontFamily: 'monospace',
    fontSize: 12,
  },
});
