import React from 'react'
import cx from 'classnames'
import { StickyContainer, Sticky } from 'react-sticky'
import Waypoint from 'react-waypoint'
import {
  Container, Row, Col, NavLink, Nav, Table, Blockquote
} from 'components/bootstrap'

import remark from 'remark'
import toc from 'remark-toc'
import slug from 'remark-slug'
import hljs from 'highlight.js'

import highlightLsc from 'util/highlightLsc'
import markdownToReact from 'util/markdownToReact'
import mainDocsTraverser from 'util/mainDocsTraverser'
import tocTraverser from 'util/tocTraverser'
import compileLscToJs from 'util/compileLscToJs'
import rawDocs from '!raw!./docs.md'

hljs.registerLanguage('lsc', highlightLsc)
{ highlight } = hljs
{ TableOfContents, DocsContents } = convertDocsMarkdownToReact()

class PureDocsContents extends React.PureComponent:
  render() ->
    <div>
      {DocsContents}
    </div>

class Docs extends React.Component:
  constructor() ->
    this.state = {
      activeSections: new Set()
    }

  getChildContext() ->
    { activeSections } = this.state
    // TODO: debug why fat-arrows aren't working
    onEnter(id) => this.onEnter(id)
    onLeave(id) => this.onLeave(id)

    { activeSections, onEnter, onLeave }

  onEnter(sectionId): void ->
    { activeSections } = this.state
    activeSections.add(sectionId)
    this.setState({ activeSections })

  onLeave(sectionId): void ->
    { activeSections } = this.state
    activeSections.delete(sectionId)
    this.setState({ activeSections })

  render() ->
    <Container className="py-5">
      <StickyContainer>
        <Row>
          <Col sm={3} className="hidden-sm-down">
            <Sticky className="px-4 pt-2 docs-ref-toc">
              {TableOfContents}
            </Sticky>
          </Col>

          <Col className="px-2 sm-px-5 py-2 docs-ref-docs">
            <PureDocsContents />
          </Col>
        </Row>
      </StickyContainer>
    </Container>

Docs.childContextTypes = {
  activeSections: React.PropTypes.object
  onEnter: React.PropTypes.func
  onLeave: React.PropTypes.func
}

export default Docs


TocSection({ children, section }, { activeSections }) ->
  isActive = if section: activeSections.has(section)
  classes = cx("nav-item", { active: isActive })

  <li className={classes}>
    {children}
  </li>

TocSection.contextTypes = {
  activeSections: React.PropTypes.object.isRequired
}

ScrollTargetSection({ section, id, children }, { onEnter, onLeave }) ->
  sectionId = id.replace('section-', '')
  _onEnter() -> onEnter(sectionId)
  _onLeave() -> onLeave(sectionId)

  <Waypoint onEnter={_onEnter} onLeave={_onLeave}>
    <section id={id}>
      {children}
    </section>
  </Waypoint>

ScrollTargetSection.contextTypes = {
  onEnter: React.PropTypes.func.isRequired
  onLeave: React.PropTypes.func.isRequired
}

CodeCol({ code, syntax }) ->
  html = highlight(syntax, code, true).value

  <Col sm="6" className={syntax}>
    <pre className="h-100 pt-2">
      <code dangerouslySetInnerHTML={{ __html: html }} />
    </pre>
  </Col>

CompiledCode({ lsc }) ->
  js = compileLscToJs(lsc)

  <div className="compiled-code-group compiled-code-group-highlight mb-3">
    <Row className="mx-0">
      <CodeCol code={lsc} syntax="lsc" />
      <CodeCol code={js} syntax="js" />
    </Row>
  </div>

convertDocsMarkdownToReact() ->
  markdownWithTOC = remark()
    .use(toc)
    .process(rawDocs)
    .contents

  // HACK; shouldn't need to double-process this way
  split = markdownWithTOC.split('\n## ')
  tocMD = split[0].replace('## TOC\n', '')
  docMD = '## ' + split.slice(1).join('\n## ')

  const TableOfContents = remark()
    .use(markdownToReact, {
      traverse: tocTraverser
      remarkReactComponents: {
        ul: Nav
        TocSection: TocSection
        a: NavLink
      }
    })
    .process(tocMD)
    .contents

  const DocsContents = remark()
    .use(slug)
    .use(markdownToReact, {
      sanitize: { clobber: ["name"] }
      traverse: mainDocsTraverser
      remarkReactComponents: {
        section: ScrollTargetSection
        table: Table
        blockquote: Blockquote
        CompiledCode
      }
    })
    .process(docMD)
    .contents
    .props.children

  { TableOfContents, DocsContents }
