/**
 * 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, ScrollView } from 'react-native';
import {
  Container,
  Content,
  Item,
  Label,
  Form,
  Textarea,
  ListItem,
  H3,
} from 'native-base';
import styles from './style';
import Firebase, { withFirebase } from '../../../firebase';
import { showToast } from '../../../utils';
import InputBlock from '../../../components/firebase/InputBlock';
import ActionButton from '../../../components/firebase/ActionButton';
import AppHeader from '../../../components/firebase/AppHeader';
import FaqCard from './FaqCard';
import { NavigationDrawerScreenProps } from 'react-navigation-drawer';
import { QuestionModel } from '../../../firebase/models';

interface Iprops extends NavigationDrawerScreenProps {
  firebase: Firebase;
}
interface Istate {
  id: string | null;
  answer: string;
  question: string;
  faqList: Array<QuestionModel>;
  isLoading: boolean;
}

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

  constructor(props: Iprops) {
    super(props);
    this.state = {
      id: null,
      answer: '',
      question: '',
      faqList: [],
      isLoading: false,
    };
  }

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


  }

  onChangeAnswer = (answer: string) => this.setState({ answer });

  onChangeQuestion = (question: string) => this.setState({ question });

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

  setEditState = (questionId: string) => {
    const { faqList } = this.state;
    const editQuestion = faqList.find((el) => el.id === questionId);
    if (editQuestion) {
      const { question, answer, id } = editQuestion;
      this.setState({ question, answer, id });
    } else {
      showToast('User cannot edit this question. It is a protected question.');
    }
  };

  getListData = () => {
    return this.state.faqList.map((el) => (
      <FaqCard
        key={el.id}
        dataItem={el}
        editEvent={this.setEditState}
        deleteEvent={this.confirmDelete}
      />
    ));
  };

  getAction = () => {
    const { id, question, answer, isLoading } = this.state;
    const disableAction = question.length > 0 && answer.length > 0;
    return id ? (
      <ActionButton
        onPress={this.updateQuestion}
        disabled={!disableAction}
        displayText="update question"
        activityLoading={isLoading}
      />
    ) : (
        <ActionButton
          onPress={this.addQuestion}
          disabled={!disableAction}
          displayText="add question"
          activityLoading={isLoading}
        />
      );
  };

  addQuestion = async () => {
    this.setState({ isLoading: true });
    const { question, answer } = this.state;
    const userId = this.props.firebase.getCurrentUserId();
    const questionData = {
      question,
      answer,
      userId,
    };
    try {
      const fireData = await this.props.firebase.addNewQuestion(questionData);
      if (fireData.id) {
        await this.props.firebase.updateQuestion({ id: fireData.id });
      }
      showToast('Question added successfully.');
      this.setState({ question: '', answer: '', isLoading: false });
    } catch (e) {
      console.log(e, 'error in create one');
      if (e.message) {
        showToast(e.message);
      }
      this.setState({ isLoading: false });
    }
  };

  updateQuestion = async () => {
    this.setState({ isLoading: true });
    const { id, question, answer } = this.state;
    if (id) {
      try {
        await this.props.firebase.updateQuestion({ id, question, answer });
        showToast('Question updated successfully');
        this.setState({ question: '', answer: '', id: null, isLoading: false });
      } catch (e) {
        console.log('error in update', e);
        if (e.message) {
          showToast(e.message);
        }
        this.setState({ isLoading: false });
      }
    } else {
      showToast('Unable to update the question. The question is protected.');
    }
  };

  removeQuestion = async (questionId: string) => {
    try {
      await this.props.firebase.removeQuestion(questionId);
      showToast('Question removed successfully.');
    } catch (e) {
      console.log('error msg', e);
    }
  };

  confirmDelete = (questionId: string) => {
    Alert.alert(
      'Delete Entry',
      'You want to delete the Entry. Are you sure ?',
      [
        {
          text: 'No',
          onPress: () => console.log('Cancel Pressed'),
          style: 'cancel',
        },
        { text: 'Yes', onPress: () => this.removeQuestion(questionId) },
      ]
    );
  };

  toggleMenu = () => this.props.navigation.toggleDrawer();

  render() {
    const { question, answer } = this.state;
    return (
      <Container>
        <AppHeader title="CRUD" toggleMenu={this.toggleMenu} />
        <Content padder>
          <Form>
            <InputBlock
              name="question"
              onChangeText={this.onChangeQuestion}
              value={question}
            />
            <Item stackedLabel last>
              <Label>Answer</Label>
              <Textarea
                rowSpan={5}
                style={styles.textarea}
                onChangeText={this.onChangeAnswer}
                value={answer}
              />
            </Item>
            {this.getAction()}
          </Form>
          <ListItem itemHeader first>
            <H3>Faq Data</H3>
          </ListItem>
          <ScrollView style={styles.scrollableList}>
            {this.getListData()}
          </ScrollView>
        </Content>
      </Container>
    );
  }
}

export default withFirebase(HomePage);
