/**
 * React Native Full App (https://store.enappd.com/product/react-native-full-app)
 *
 * Copyright © 2019-present Enappd. All rights reserved.
 *
 * This source code is licensed as per the terms found in the
 * LICENSE.md file in the root directory of this source tree.
 */
import React from 'react';
import { Alert } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as Permissions from 'expo-permissions';
import { Container, Content, Grid, Row, Col } from 'native-base';
import ActionButton from '../../../components/firebase/ActionButton';
import AppHeader from '../../../components/firebase/AppHeader';
import Firebase, { withFirebase } from '../../../firebase';
import { showToast, urlToBlob } from '../../../utils';
import ImageCard from './ImageCard';
import styles from './style';
import ImageLoader from './ImageLoader';
import { NavigationDrawerScreenProps } from 'react-navigation-drawer';
import { ImageModel } from '../../../firebase/models';

interface Iprops extends NavigationDrawerScreenProps {
  firebase: Firebase;
}
interface Istate {
  showLoading: boolean;
  imageList: Array<ImageModel>;
  isLoading: boolean;
}

class UploadPage extends React.Component<Iprops, Istate> {
  unsubscribe: any;

  constructor(props: Iprops) {
    super(props);
    this.state = {
      showLoading: false,
      imageList: [],
      isLoading: false,
    };
  }

  async componentDidMount() {
    this.unsubscribe = this.props.firebase
      .getImagesList()
      .onSnapshot(this.onCollectionUpdate);
  }

  onCollectionUpdate = (querySnapshot: any) => {
    const imageList: Array<ImageModel> = [];
    querySnapshot.forEach((doc: any) => {
      imageList.push(doc.data());
    });
    this.setState({
      imageList,
    });
  };

  askForSource = () => {
    Alert.alert(
      'Select Image From',
      undefined,
      [
        { text: 'Gallery', onPress: () => this.openGallery(true) },
        { text: 'Camera', onPress: () => this.openGallery(false) },
        {
          text: 'Cancel',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
      ],
      { cancelable: false }
    );
  };
  toggleMenu = () => this.props.navigation.toggleDrawer();

  openGallery = async (isGallery: boolean) => {
    try {
      const hasPermission = await Permissions.getAsync('camera', 'cameraRoll');
      if (hasPermission.status !== 'granted') {
        await Permissions.askAsync('camera', 'cameraRoll');
      }
      const imageData: any = isGallery
        ? await ImagePicker.launchImageLibraryAsync()
        : await ImagePicker.launchCameraAsync({ allowsEditing: true });
      if (imageData.uri) {
        this.uploadImage(imageData.uri);
      }
    } catch (e) {
      console.log(e, 'error in camera');
    }
  };

  uploadImage = async (uri: string) => {
    console.log(uri);
    this.setState({ showLoading: true });
    try {
      // const response = await fetch(uri);
      // console.log(response, "image response")
      const blob = await urlToBlob(uri);
      const imageData = await this.props.firebase.uploadImage(blob);
      this.setState({ showLoading: false });
      showToast('Image uploaded successfully.');

      await this.props.firebase.updateImageRef(imageData);
    } catch (e) {
      console.log('error in upload', e);
      this.setState({ showLoading: false });
      if (e.message) {
        showToast(e.message);
      }
    }
  };
  confirmAlert = (imageId: string) =>
    Alert.alert('Remove Image', 'Are you sure ?', [
      { text: 'Delete', onPress: () => this.removeImage(imageId) },
      { text: 'cancel', style: 'cancel' },
    ]);
  removeImage = async (imageId: string) => {
    try {
      await this.props.firebase.removeImage(imageId);
      showToast('Image removed successfully.');
    } catch (e) {
      console.log(e);
      if (e.message) {
        showToast(e.message);
      }
    }
  };
  render() {
    const { imageList, showLoading } = this.state;
    return (
      <Container>
        <AppHeader title="Upload" toggleMenu={this.toggleMenu} />
        <Content>
          <Grid>
            <Row style={[styles.paddingHorizontal_10]}>
              <Col>
                <ActionButton
                  displayText="upload"
                  onPress={this.askForSource}
                  activityLoading={showLoading}
                />
              </Col>
            </Row>
            <Row style={[styles.flexWrap, styles.paddingHorizontal_10]}>
              {imageList.length > 0 &&
                imageList.map((el) => (
                  <ImageCard
                    imageUrl={el.url}
                    onRemoveClick={() => this.confirmAlert(el.id)}
                  />
                ))}
              {showLoading && <ImageLoader />}
            </Row>
          </Grid>
        </Content>
      </Container>
    );
  }
}

export default withFirebase(UploadPage);
