import { Component, linkEvent } from 'inferno';
import { SearchParams } from '../interfaces';


interface State {
  searchParams: SearchParams;
}

export class Navbar extends Component<any, State> {

  state: State = {
    searchParams: {
      page: 1,
      q: ""
    }
  }

  constructor(props, context) {
    super(props, context);
  }

  render() {
    return (
      <div>{this.navbar()}</div>
    )
  }

  navbar() {
    return (
      <nav class="navbar navbar-dark" style="background-color: #673ab7">
        <a class="navbar-brand" href="#">
          <i class="fas fa-fw fa-database mr-1"></i>Torrents.csv
      </a>
        <div class="col-12 col-sm-6">
          {this.searchForm()}
        </div>
      </nav>
    );
  }

  // TODO
  // https://www.codeply.com/go/xBVaM3q5X4/bootstrap-4-navbar-search-full-width
  searchForm() {
    return (
      <form class="my-2 my-lg-0 d-inline w-100" onSubmit={linkEvent(this, this.search)}>
        <div class="input-group">
          <input value={this.state.searchParams.q} onInput={linkEvent(this, this.searchChange)} type="text" class="form-control" placeholder="Search..." />
          <button type="submit" class="btn btn-light border border-left-0 border-radius-left-0">
            <i className="fas fa-fw fa-search"></i>
          </button>
        </div>
      </form>
    );
  }

  search(i: Navbar, event) {
    event.preventDefault();
    i.context.router.history.push(`/search/${i.state.searchParams.q}/${i.state.searchParams.page}`);
  }

  searchChange(i: Navbar, event) {
    let searchParams: SearchParams = {
      q: event.target.value,
      page: 1
    }
    i.setState({ searchParams: searchParams });
  }
}