import React, { useState, useEffect } from 'react';
import { StyleSheet, TouchableOpacity, Image, Alert, ActivityIndicator } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedText, ThemedTextInput } from '@/components/theme';
import { IconSymbol } from '@/components/ui/IconSymbol';

export default function ProfileScreen() {
  const [loading, setLoading] = useState(false);
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [avatar, setAvatar] = useState(null);

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

  const fetchUserProfile = async () => {
    setLoading(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      
      if (user) {
        const { data, error } = await supabase
          .from('profiles')
          .select('*')
          .eq('id', user.id)
          .single();
        
        if (data) {
          setFullName(data.full_name || '');
          setEmail(data.email || '');
          setAvatar(data.avatar_url || null);
        }
      }
    } catch (error) {
      console.error('Error fetching profile:', error);
    } finally {
      setLoading(false);
    }
  };

  const updateProfile = async () => {
    setLoading(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      
      if (!user) throw new Error('User not found');
      
      const updates = {
        id: user.id,
        full_name: fullName,
        email,
        updated_at: new Date(),
      };
      
      const { error } = await supabase
        .from('profiles')
        .upsert(updates);
        
      if (error) throw error;
      
      Alert.alert('Success', 'Profile updated successfully!');
    } catch (error) {
      Alert.alert('Error updating profile', error.message);
    } finally {
      setLoading(false);
    }
  };

  // Add image picking functionality here (similar to previous example)

  return (
    <ThemedView style={styles.container}>
      <TouchableOpacity style={styles.avatarContainer}>
        {avatar ? (
          <Image source={{ uri: avatar }} style={styles.avatar} />
        ) : (
          <ThemedView style={styles.avatarPlaceholder}>
            <IconSymbol name="person.fill" size={50} color="#999" />
          </ThemedView>
        )}
        <ThemedText style={styles.changePhotoText}>Change Photo</ThemedText>
      </TouchableOpacity>

      <ThemedView style={styles.formSection}>
        <ThemedText style={styles.label}>Full Name</ThemedText>
        <ThemedTextInput
          value={fullName}
          onChangeText={setFullName}
          placeholder="Enter your full name"
          style={styles.input}
        />
        
        <ThemedText style={styles.label}>Email</ThemedText>
        <ThemedTextInput
          value={email}
          onChangeText={setEmail}
          placeholder="Enter your email"
          keyboardType="email-address"
          autoCapitalize="none"
          style={styles.input}
        />
      </ThemedView>

      <TouchableOpacity 
        style={styles.saveButton} 
        onPress={updateProfile}
        disabled={loading}
      >
        {loading ? (
          <ActivityIndicator color="#fff" />
        ) : (
          <ThemedText style={styles.saveButtonText}>Save Changes</ThemedText>
        )}
      </TouchableOpacity>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  avatarContainer: {
    alignItems: 'center',
    marginTop: 20,
    marginBottom: 30,
  },
  avatar: {
    width: 120,
    height: 120,
    borderRadius: 60,
  },
  avatarPlaceholder: {
    width: 120,
    height: 120,
    borderRadius: 60,
    backgroundColor: '#E1E1E1',
    justifyContent: 'center',
    alignItems: 'center',
  },
  changePhotoText: {
    marginTop: 8,
    color: '#007AFF',
    fontSize: 16,
  },
  formSection: {
    marginBottom: 30,
  },
  label: {
    marginBottom: 8,
    fontSize: 16,
  },
  input: {
    fontSize: 16,
    paddingVertical: 12,
    paddingHorizontal: 10,
    borderRadius: 8,
    marginBottom: 20,
  },
  saveButton: {
    backgroundColor: '#007AFF',
    paddingVertical: 14,
    borderRadius: 8,
    alignItems: 'center',
  },
  saveButtonText: {
    color: '#fff',
    fontSize: 16,
  },
});
