import React, { useState, useEffect } from 'react';
import { TouchableOpacity, StyleSheet, ActivityIndicator } from 'react-native';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';

interface User {
  id: number;
  name: string;
  message: string;
}

interface UserSelectionProps {
  onUserSelected: (user: User) => void;
}

const API_KEY = 'I_Love_Madeline';
//const BASE_URL = 'https://ismadelinethecutest.gibbyb.com/api';
const BASE_URL = 'http://192.168.0.39:3000/api';

const UserSelection: React.FC<UserSelectionProps> = ({ onUserSelected }) => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    checkStoredUser();
  }, []);

  const checkStoredUser = async () => {
    try {
      const storedUser = await AsyncStorage.getItem('@user');
      if (storedUser) {
        onUserSelected(JSON.parse(storedUser));
      } else {
        fetchUsers();
      }
    } catch (e) {
      console.error('Failed to load user', e);
      fetchUsers();
    }
  };

  const fetchUsers = async () => {
    try {
      const response = await axios.get(`${BASE_URL}/getUsers`, {
        params: { apiKey: API_KEY }
      });
      setUsers(response.data);
    } catch (e) {
      console.error('Failed to fetch users', e);
    } finally {
      setLoading(false);
    }
  };

  const selectUser = async (user: User) => {
    try {
      await AsyncStorage.setItem('@user', JSON.stringify(user));
      onUserSelected(user);
    } catch (e) {
      console.error('Failed to save user', e);
    }
  };

  if (loading) {
    return (
      <ThemedView style={styles.container}>
        <ActivityIndicator size="large" color="#0000ff" />
      </ThemedView>
    );
  }

  return (
    <ThemedView style={styles.container}>
      <ThemedText style={styles.title}>Who are you?</ThemedText>
      {users.map((user) => (
        <TouchableOpacity
          key={user.id}
          style={styles.button}
          onPress={() => selectUser(user)}
        >
          <ThemedText style={styles.buttonText}>{user.name}</ThemedText>
        </TouchableOpacity>
      ))}
    </ThemedView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  button: {
    backgroundColor: '#007AFF',
    padding: 15,
    borderRadius: 5,
    marginVertical: 10,
    width: 200,
    alignItems: 'center',
  },
  buttonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
  },
});

export default UserSelection;
