import * as React from 'react'
import { stripLocale } from "./utils"

const { Icon } = window.wagtail.components


/*
 * this code is copied from wagtail, only the extra select dropdown has been added
 */

export const SearchWithLanguageChooserInput = (
  { slim, expandingOrCollapsing, searchUrl, strings, navigate, setLanguageUrl, currentLanguage, LANGUAGES, languageNeutralUrlPath}) => {
  const isVisible = !slim || expandingOrCollapsing

  const onSubmitForm = e => {
    if (e.target instanceof HTMLFormElement) {
      e.preventDefault()

      if (isVisible) {
        const inputElement = e.target.querySelector('input[name="q"]')
        navigate(searchUrl + '?q=' + encodeURIComponent(inputElement.value))
      } else {
        navigate(searchUrl)
      }
    }
  }

  const className =
    'sidebar-search' +
    (slim ? ' sidebar-search--slim' : '') +
    (isVisible ? ' sidebar-search--visible' : '')


  const selectForm = React.useRef(null)
  const handleSubmit = () => {
    selectForm.current.submit()
  }

  return (
    <>
      <form id="language_selector" ref={selectForm} className={`form language-selector-form ${className}`} action={setLanguageUrl} method="post">
        <input name="csrfmiddlewaretoken" type="hidden" value={window.wagtailConfig.CSRF_TOKEN} />
        <input name="next" type="hidden" value={ languageNeutralUrlPath } />
        <select name="language" onChange={handleSubmit} value={currentLanguage}>
          {LANGUAGES.map(([code, lang]) => (
            <option key={code} value={ code }>
              { lang }
            </option>
          ))}
        </select>
      </form>
      <form role="search" className="w-h-[42px] w-relative w-box-border w-flex w-items-center w-justify-start w-flex-row w-flex-shrink-0" action={searchUrl} method="get" onSubmit={onSubmitForm}>
        <div className="w-flex w-flex-row w-items-center w-h-full">
          <button className="w-pr-0 w-w-full w-pl-[23px] w-h-[35px] w-bg-transparent w-outline-offset-inside w-border-0 w-rounded-none w-text-text-label-menus-default w-z-10 hover:w-text-text-label-menus-active focus:w-text-text-label-menus-active hover:w-bg-transparent" type="submit" aria-label={strings.SEARCH}>
            <Icon className="icon--menuitem" name="search" />
          </button>
          <label className="w-sr-only" for="menu-search-q">{strings.SEARCH}</label>
          <input className="!w-pl-[55px] !w-py-[13px] !w-subpixel-antialiased !w-absolute !w-left-0 !w-font-normal !w-top-0 !w-text-14 !w-bg-transparent !w-border-0 !w-rounded-none !w-text-text-label-menus-default !w-outline-offset-inside !w-leading-none placeholder:!w-text-text-label-menus-default" type="text" id="menu-search-q" name="q" placeholder={strings.SEARCH}/>
        </div>
      </form>
    </>
  )
}

export class SearchWithLanguageChooserModuleDefinition {

  constructor(searchUrl, setLanguageUrl, currentLanguage, LANGUAGES, meta) {
    const { pathname, search } = window.location
    this.searchUrl = searchUrl
    this.setLanguageUrl = setLanguageUrl
    this.currentLanguage = currentLanguage
    this.LANGUAGES = LANGUAGES
    this.languageNeutralUrlPath = stripLocale(`${pathname}${search}`, LANGUAGES)
    this.meta = meta
    this.attrs = {}
  }

  render({ slim, key, expandingOrCollapsing, navigate }) {
    return (
      <SearchWithLanguageChooserInput
        searchUrl={this.searchUrl}
        slim={slim}
        key={key}
        expandingOrCollapsing={expandingOrCollapsing}
        strings={this.meta.strings}
        navigate={navigate}
        setLanguageUrl={this.setLanguageUrl}
        currentLanguage={this.currentLanguage}
        LANGUAGES={this.LANGUAGES}
        languageNeutralUrlPath={this.languageNeutralUrlPath}
      />
    )
  }
}

window.telepath.register('ocyan.sidebar.SearchWithLanguageChooserModule', SearchWithLanguageChooserModuleDefinition)
