import React, { useState, useEffect } from 'react';
import { TouchableOpacity, StyleSheet, ActivityIndicator } from 'react-native';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { LinearGradient } from 'expo-linear-gradient';
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 = process.env.EXPO_PUBLIC_API_KEY;
const BASE_URL = process.env.EXPO_PUBLIC_BASE_URL;

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: 48,
    lineHeight: 56,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  button: {
    backgroundColor: '#730FF8',
    padding: 15,
    borderRadius: 5,
    marginVertical: 10,
    width: 200,
    alignItems: 'center',
  },
  buttonText: {
    color: 'white',
    fontSize: 24,
    fontWeight: 'bold',
  },
});

export default UserSelection;
