import React, { useState } from 'react';
import {
  View,
  Image,
  TouchableOpacity,
  Alert,
  Text
} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { Modal } from '../Modal';
import { Input } from '../Input';
import { styles } from './style';

import AddSVG from '../../../assets/icons/add.svg';
import TrashSVG from '../../../assets/icons/trash.svg';

interface AddPhotoProps {
  isModalVisible: boolean;
  initialImagePath?: string | null;
  initialImageDescription?: string;
  closeModal: () => void;
}

const AddPhoto: React.FC<AddPhotoProps> = ({ isModalVisible, initialImagePath, initialImageDescription, closeModal }) => {
  const [image, setImage] = useState(initialImagePath);
  const [description, setDescription] = useState(initialImageDescription ?? '');

  const handleDelete = () => {
    Alert.alert('Delete Image', 'Are you sure you want to delete this image?', [
      { text: 'Cancel' },
      { text: 'Delete', onPress: () => {
        setImage(null);
      }},
    ]);
  };

  const handleImagePick = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('Permission Denied', 'Sorry, we need media library permissions to make this work!');
      return;
    }

    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      quality: 1,
    });

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
  };

  return (
    <Modal
      visibleInPercent={'90%'}
      visible={isModalVisible}
      onRequestClose={closeModal}
      headerTitle='Add Photo'
    >
      <View style={[styles.container, styles.centerPosition]}>
        <View style={[styles.imageContainer, styles.centerPosition]}>
          {image ? (
            <>
              <TouchableOpacity onPress={handleDelete} style={styles.deleteButton}>
                <View style={[styles.centerPosition, styles.deleteBtn]}>
                  <TrashSVG />
                </View>
              </TouchableOpacity>
              <Image source={{ uri: image }} style={styles.image} />
            </>
          ) : (
            <TouchableOpacity onPress={handleImagePick} style={styles.centerPosition}>
              <View style={[styles.centerPosition, styles.addBtn]}>
                <AddSVG width={48} height={48} />
              </View>
              
              <Text style={styles.addButtonText}>Upload Photo</Text>
            </TouchableOpacity>
          )}
        </View>
        <View style={styles.description}>
          <Input
            header='Description'
            placeholder="Add photo description here"
            onChange={setDescription}
          />
        </View>
      </View>
    </Modal>
  );
};

export default AddPhoto;
