import { Text, View, TextInput, Pressable, ScrollView, Image } from 'react-native';
import { gStyle } from '../styles/style';
import Footer from '../components/Footer';
import Header from '../components/Header';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState,} from 'react';
import * as ImagePicker from 'expo-image-picker';

export default function FormAddMK() {
    const [imageData, setImageData] = useState(null);
    const chooseImage = async() => {
        const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
        if (status !== 'granted') {
            console.log('Permission to access media library was denied')
            return; // exit the function if permission is not granted
            }
            const options = {
            mediaType: ImagePicker.MediaTypeOptions.Images,
            quality: 0.5,
            };
            let result = await ImagePicker.launchImageLibraryAsync(options); // use launchImageLibraryAsync
            if (!result.canceled) { // check if the user selected an image
            setImageData(result);
            }
            };

    if (Platform.OS !== 'web') { // use Platform.OS instead of Constants.platform
    ImagePicker.requestMediaLibraryPermissionsAsync().then(() => {
    console.log('Media permissions have been granted.');
    }).catch((error) => {
    console.log('Error getting media permissions:', error);
    });
    }
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [price, setPrice] = useState('');
    const [time, setTime] = useState('');
    const [timeOfMK, setTimeOfMK] = useState('');
    const [person, setPerson] = useState('');
    const [image, setImage] = useState(null);

    const onChangeName = (text) => setName(text);
    const onChangeDescription = (text) => setDescription(text);
    const onChangePrice = (text) => setPrice(text);
    const onChangeTime = (text) => setTime(text);
    const onChangeTimeOfMK = (text) => setTimeOfMK(text);
    const onChangePerson = (text) => setPerson(text);
    const onChangeImage = (event) => {
    const file = event.target.files[0];
    setImage(file);
    };
    const addHandler = async () => {
        try {
        const storageRef = firebase.storage().ref();
        const imageRef = storageRef.child(`images/${Date.now()}`);
        const response = await fetch(imageData.uri);
        const blob = await response.blob();
        const uploadTask = imageRef.put(blob);
        uploadTask.on(
        'state_changed',
        null,
        (error) => {
        console.log('Error uploading image:', error);
        },
        async () => {
        const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
        firebase
        .database()
        .ref('FutureMK')
        .push({
        id: Date.now(),
        name: name,
        description: description,
        price: price,
        time: time,
        timeOfMK: timeOfMK,
        person: person,
        image: downloadURL,
        });
        }
        );
        } catch (error) {
        console.log('Error adding MK:', error);
        }
        };
  return (
    <View>
<ScrollView>
    <Header/>
    <View style={gStyle.formAdd}>
        <Text style={gStyle.header}>Добавить мастер-класс</Text>
        <View style={gStyle.formBlock}>
            <View>
                <Text>Название мастер-класса</Text>
                <TextInput style={gStyle.inputForm} onChangeText={onChangeName}
                />
            </View>
            <View>
                <Text>Дата мастер-класса</Text>
                <TextInput style={gStyle.inputForm} onChangeText={onChangeTime}
                />
            </View>
            <View>
                <Text>Описание мастер-класса</Text>
                <TextInput style={gStyle.inputForm} onChangeText={onChangeDescription}
                />
            </View>
            <View>
                <Text>Изображение</Text>
                {imageData ? (
            <Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} />
            ) : null}
            <Pressable onPress={chooseImage}>
                <Text>Выбрать изображение</Text>
            </Pressable>
            </View>
            <View>
                <Text>Стоимость мастер-класса</Text>
                <TextInput style={gStyle.inputForm} onChangeText={onChangePrice}
                />
            </View>
            <View>
                <Text>Кол-во людей на бронирование</Text>
                <TextInput style={gStyle.inputForm} onChangeText={onChangePerson}
                />
            </View>
            <View>
                <Text>Продолжительность мастер-класса</Text>
                <TextInput style={gStyle.inputForm} onChangeText={onChangeTimeOfMK}
                />
            </View>
        <Pressable style={gStyle.btnAddMK} 
        onPress={addHandler}
        >
            <Text style={gStyle.btnAddMKtxt}>Сохранить</Text>
        </Pressable>
        </View>
  </View>
  <Footer/>
  </ScrollView>
  </View>

  );
}

it says that key uri in the image picker result is deprecated and will be removed in sdk 48, you can access selected assets through the assets array instead