import { Controller } from "@hotwired/stimulus"
import SlimSelect from 'slim-select'

export default class extends Controller {
  static targets = [
                    "checkbox",
                    "submit",
                    "whoWasInvolved",
                    "didYouInteractWithAnyoneDetails",
                    "toldAnyoneDetails",
                    "offenderDetailsQuestions",
                    "whoMightKnowQuestions",
                    "whenDidItHappen",
                    "incidentSeason",
                    "incidentDate",
                    "incidentTime",
                    "whereDidItHappen",
                    "whatHappened",
                    "unwantedBecauseCheckboxes",
                    "unableToReactCheckboxes",
                    "unableToConsentCheckboxes",
                    "whatHappenedBeforeQuestions",
                    "whatHappenedDuringAndAfterQuestions",
                    "howHasItImpactedYouQuestions",
                    "physicalChanges",
                    "emotionalChanges",
                    "dailyFunctionChanges",
                    "incidentSelectInput"
                  ]

  connect() {
    const addable = (value) => value

    new SlimSelect({
      select: '#incident_detail_offender_relationship',
      settings: {
        focusSearch: false,
        searchPlaceholder: "Add different relationship"
      },
      events: {
        addable
      }
    })

    const howQuestionsIds = ['incident_detail_physical_changes', 'incident_detail_emotional_changes', 'incident_detail_daily_functioning_changes']
    howQuestionsIds.forEach(id => {
      new SlimSelect({
        select: `#${id}`,
        settings: {
          closeOnSelect: false,
          focusSearch: false,
          searchPlaceholder: "Add how this has affected you",
          placeholderText: "Select all that are applicable, and/or add specifics about how you have been affected"
        },
        events: {
          addable
        }
      })
    })

    const questionsElements = [...document.getElementsByClassName('ss-search')]
    questionsElements.forEach(element => {
      element.addEventListener('keyup', (event) => {
        if (event.key === 'Enter') {
          element.querySelector('.ss-addable').click()
          element.querySelector('input').value = ''
        }
      })
    })
  }

  changeIncidentTime(ev) {
    if (ev.target.value == 'I know the exact time') {
      this.incidentTimeTarget.classList.remove("hidden")
    } else {
      this.incidentTimeTarget.classList.add("hidden")
    }
  }

  rotateChevron(ev) {
    ev.preventDefault()
    let parent_button = ev.target.closest("button")
    let icon = parent_button.querySelector("span")
    this.toggleClasslist(icon, 'rotate-0', 'rotate-90')
  }

  expandSection(ev) {
    ev.preventDefault()
    this.rotateChevron(ev)
    let section_target = this[`${ev.params.section}Target`]
    this.toggleClasslist(section_target, 'hidden')
  }

  onSelectIncidentDetails(event) {
    let path
    if (event.target.value === 'new-incident') {
      path = '/incident_details/new'
    } else {
      const incident_id = event.target.options[event.target.selectedIndex].value
      path = `/incident_details/${incident_id}`
    }

    fetch(path, { headers: { Accept: "text/vnd.turbo-stream.html" } })
      .then(r => r.text())
      .then(html => Turbo.renderStreamMessage(html))
  }

  toggleShowIncidentDetailsSelect() {
    const selectInput = document.getElementById("view_incident_incident_detail")
    this.toggleClasslist(selectInput, 'hidden', 'standard-input')

    const icon = document.getElementsByClassName("ti-arrow-circle-up")[0]
    this.toggleClasslist(icon, 'rotate-0', 'rotate-180')
  }

  toggleClasslist(element, ...classes) {
    classes.forEach(klass => element.classList.toggle(klass))
  }
};
