import React, { Component } from "react";
import {
  Keyboard,
  ListView,
  Platform,
  StyleSheet,
  Text,
  View
} from "react-native";
import Header from "./header";
import Footer from "./footer";
import Row from "./row";

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F5F5F5",
    ...Platform.select({
      ios: {
        paddingTop: 30
      }
    })
  },
  content: {
    flex: 1
  },
  list: {
    backgroundColor: "#fff"
  },
  separator: {
    borderWidth: 2,
    borderColor: "#eee"
  }
});

class App extends Component {
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.state = {
      allComplete: false,
      dataSource: ds.cloneWithRows([]),
      items: [],
      value: ""
    };
    this.handleAddItem = this.handleAddItem.bind(this);
    this.handleToggleAllComplete = this.handleToggleAllComplete.bind(this);
    this.setSource = this.setSource.bind(this);
  }

  handleAddItem() {
    if (!this.state.value) {
      return;
    }
    const newItems = [
      ...this.state.items,
      {
        key: Date.now(),
        text: this.state.value,
        complete: false
      }
    ];
    this.setSource(newItems, newItems, { value: "" });
  }

  handleToggleAllComplete() {
    const complete = !this.state.allComplete;
    const newItems = this.state.items.map((item) => ({
      ...item,
      complete
    }));
    // console.table(newItems);
    this.setSource(newItems, newItems, { allComplete: complete });
  }

  render() {
    // console.log("App state", this.state);
    return (
      <View style={styles.container}>
        <Header
          onAddItem={this.handleAddItem}
          onChange={(value) => this.setState({ value })}
          onToggleAllComplete={this.handleToggleAllComplete}
          value={this.state.value}
        />
        <View style={styles.content}>
          <ListView
            enableEmptySections
            dataSource={this.state.dataSource}
            onScroll={() => Keyboard.dismiss()}
            renderRow={({ key, ...value }) => {
              // console.log("renderRow", key, value);
              return (
                <Row
                  key={key}
                  { ...value }
                />
              );
            }}
            renderSeparator={(sectionId, rowId) => {
              // console.log('renderSeparator', sectionId, rowId);
              return <View key={rowId} style={styles.separator} />;
            }}
            style={styles.list}
          />
        </View>
        <Footer />
      </View>
    );
  }

  setSource(items, itemsDataSource, otherState = {}) {
    this.setState({
      items,
      dataSource: this.state.dataSource.cloneWithRows(itemsDataSource),
      ...otherState
    });
  }
}

export default App;
