import React from 'react';

import * as ApolloTypes from '../queries/__generated__/GetProducts';
import ProductDetail from './ProductDetail';

type Props = {
  products: Array<ApolloTypes.GetProducts_allProductsSearch_products>
}

type State = {
  selectedProductId: number | null;
}

const style = {
  cursor: 'pointer'
};

class Products extends React.Component<Props, State> {

  constructor(props: any) {
    super(props);
    this.state = {
      selectedProductId: null
    };
  }

  handleProductClick(newSelectedProductId: number): void {
    const { selectedProductId } = this.state;
    if (newSelectedProductId === selectedProductId) {
      this.setState({ selectedProductId: null });
    } else {
      this.setState({ selectedProductId: newSelectedProductId });
    }
  }

  render() {
    const { products } = this.props;
    const { selectedProductId } = this.state;
    return (
      <div>
      {
        products.map(({ productName, productId }) => 
          <div onClick={ () => this.handleProductClick(productId) } key={ productId.toString() }>
            <div style={ style }>
              { productName }
            </div>
            {
              selectedProductId === productId &&
                <ProductDetail />
            }
          </div>
        )
      }
    </div>
    );
  }

}

export default Products;
