import React from 'react';
import { View, TouchableOpacity, Image, Text } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { uploadImage } from '@/lib/appwrite';
import icons from '@/constants/icons';

interface Props {
    onImageSelected: (url: string) => void;
    multiple?: boolean;
}

export const ImagePickerComponent = ({ onImageSelected, multiple = false }: Props) => {
    const pickImage = async () => {
        const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
        
        if (status !== 'granted') {
            alert('Sorry, we need camera roll permissions to make this work!');
            return;
        }

        const result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,
            allowsMultipleSelection: multiple,
        });

        if (!result.canceled) {
            try {
                // Convert image to blob
                const response = await fetch(result.assets[0].uri);
                const blob = await response.blob();
                
                // Upload to Appwrite
                const imageUrl = await uploadImage({
                    uri: result.assets[0].uri,
                    type: 'image/jpeg',
                    name: 'image.jpg',
                    size: blob.size
                });
                onImageSelected(imageUrl);
            } catch (error) {
                console.error('Error uploading image:', error);
                alert('Failed to upload image');
            }
        }
    };

    return (
        <TouchableOpacity 
            onPress={pickImage}
            className="flex items-center justify-center border-2 border-dashed border-gray-300 rounded-lg p-4"
        >
            <Image 
                source={icons.dumbell} 
                className="w-8 h-8 mb-2"
            />
            {/* change dumbell to camera */}
            <Text className="text-gray-500">Upload Image</Text>
        </TouchableOpacity>
    );
}; 