import React, { useState } from 'react';
import { View, TouchableOpacity, Image, Text, ScrollView } 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;
    images: string[];
}

export const ImagePickerComponent = ({ onImageSelected, images }: Props) => {
    const pickImage = async () => {
        if (images.length >= 5) {
            alert('Maximum 5 images allowed');
            return;
        }

        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: ['images'],
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,
        });

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

    const removeImage = (index: number) => {
        const newImages = [...images];
        newImages.splice(index, 1);
        onImageSelected(newImages);
    };

    return (
        <View>
            <ScrollView 
                horizontal 
                showsHorizontalScrollIndicator={false}
                className="mb-4"
            >
                {images.map((image, index) => (
                    <View key={index} className="relative mr-2">
                        <Image 
                            source={{ uri: image }} 
                            className="w-24 h-24 rounded-lg"
                        />
                        <TouchableOpacity 
                            onPress={() => removeImage(index)}
                            className="absolute -top-2 -right-2 bg-red-500 rounded-full p-1"
                        >
                            <Text className="text-white text-xs">✕</Text>
                        </TouchableOpacity>
                    </View>
                ))}
            </ScrollView>

            {images.length < 5 && (
                <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"
                    />
                    <Text className="text-gray-500">
                        Upload Image ({images.length}/5)
                    </Text>
                </TouchableOpacity>
            )}
        </View>
    );
}; 