import * as React from "react"
import * as ReactDOM from "react-dom"
import styled from "styled-components"
import { isElementOnScreen } from "jamplay-common/client/utils"
import ReviewItemInList, { TReview } from "./ReviewItemInList.component"

const Container = styled.div`
  .list {
    .review-list__item {
      border-bottom: 1px solid ${(props) => props.theme.borderGrey};
      padding: 20px 5px;
      &:first-child {
        padding-top: 0;
      }
      &:last-child {
        padding-bottom: 0;
        border-bottom: none;
      }
    }
  }
`

export type TProps = {
  style?: any
  ref?: any
  className?: any
  reviews: TReview[]
  loading: boolean
  hasMore: boolean
  onLoadMore?: () => Promise<any>
  onDelete?: (string) => any
}

class Component extends React.Component<TProps> {
  public static defaultProps = {
    reviews: [],
    loading: false,
    hasMore: false
  }
  public state = {
    loadingMore: false
  }
  private loadMoreChecker: any
  public handleDelete(_id: string) {
    if (this.props.onDelete) {
      this.props.onDelete(_id)
    }
  }
  public componentDidMount() {
    if (typeof window !== "undefined") {
      window.addEventListener("scroll", this.handleScroll)
    }
  }

  public componentWillUnmount() {
    if (typeof window !== "undefined") {
      window.removeEventListener("scroll", this.handleScroll)
    }
  }
  public render() {
    return (
      <Container
        innerRef={this.props.ref}
        style={this.props.style}
        className={this.props.className}
      >
        <div className="list">
          {this.props.reviews.map((review) => {
            return (
              <ReviewItemInList
                className="review-list__item"
                key={review._id}
                review={review}
                onDelete={this.handleDelete.bind(this, review._id)}
              />
            )
          })}
          {(this.props.loading || this.state.loadingMore) &&
            [-1, -2, -3].map((key) => (
              <ReviewItemInList
                className="review-list__item"
                key={key}
                isPlaceholder
              />
            ))}
        </div>
        {this.props.hasMore && (
          <div
            ref={(node) => (this.loadMoreChecker = node)}
            style={{ visibility: "hidden", width: 0, height: 0 }}
          >
            load more
          </div>
        )}
      </Container>
    )
  }
  private handleScroll = () => {
    if (
      !this.props.loading &&
      !this.state.loadingMore &&
      this.props.onLoadMore &&
      this.props.hasMore &&
      this.loadMoreChecker &&
      isElementOnScreen(ReactDOM.findDOMNode(this.loadMoreChecker))
    ) {
      this.setState({ loadingMore: true })
      this.props.onLoadMore().then(() => {
        this.setState({ loadingMore: false })
      })
    }
  }
}

export default Object.assign(Component, {
  fragments: ReviewItemInList.fragments
})
export { TReview }
