import React from 'react';

import Cookies from 'js-cookie';

import Card from '../../components/Card.js';
import CategoryCard from './components/CategoryCard.js';
import CategoryModal from './components/CategoryModal.js';
import Messages from '../../components/Messages.js';
import Sidebar from '../../components/Sidebar.js';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.token = Cookies.get('csrftoken');
    this.state = {
      categories: props.categories,
      selectedCategoryId: null,
      message: null,
    };
  }

  selectCategory = categoryId => {
    this.setState({ selectedCategoryId: categoryId });
  };

  deselectCategory = () => {
    this.setState({ selectedCategoryId: null });
  };

  deleteCategory = categoryId => {
    const url = `/api/categories/${categoryId}/`;
    const options = {
      method: 'DELETE',
      headers: {
        'X-CSRFToken': this.token,
      },
    };

    fetch(url, options).then(response => {
      if (response.ok) {
        const categories = this.state.categories.filter(category => {
          return category.pk != categoryId;
        });

        return this.setState({
          categories: categories,
          selectedCategoryId: null,
          message: null,
        });
      }
    });

    const message = {
      type: 'error',
      text: 'Unable to remove category, try again later',
    };
    return this.setState({ selectedCategoryId: null, message: message });
  };

  render() {
    const { categories } = this.state;
    const cards = categories.map(category => {
      return (
        <CategoryCard
          key={category.pk}
          category={category}
          showDialog={this.selectCategory}
          updateUrl={this.props.updateUrl}
        />
      );
    });

    const selectedCategory = categories.find(category => {
      return category.pk === this.state.selectedCategoryId;
    });

    const pageHeader = (
      <>
        <h1 className="h1">Categories</h1>
        <a className="link button button--confirm" href={`${this.props.createUrl}/`}>
          Create category
        </a>
      </>
    );

    return (
      <>
        {this.state.message && <Messages messages={[this.state.message]} />}
        <Sidebar navLinks={this.props.navLinks} />

        <div className="main__container">
          <Card header={pageHeader} />
          {cards}
          {selectedCategory && (
            <CategoryModal
              category={selectedCategory}
              handleCancel={this.deselectCategory}
              handleDelete={this.deleteCategory}
            />
          )}
        </div>
      </>
    );
  }
}

export default App;
