import React, { useCallback, useEffect, useRef, useState } from "react"
import cls from "classnames"

import { Icon } from "@/components"
import t from "@/constants/wording"

import * as styles from "./index.module.scss"
import { STORAGE_KEY } from "@/constants/common"
import * as queryString from "querystring"

type IProps = {
  tagsAndCount: { [key: string]: number }
  checkedTags: string[]
  submitCheck: (tags: string[]) => void
}

const MobilePracticeTagSelect: React.FC<IProps> = props => {
  const { tagsAndCount, checkedTags, submitCheck } = props
  const headerRef = useRef<HTMLInputElement>(null)
  const [hasActiveClass, setClass] = useState(false)
  const [mobileTags, setMobileTags] = useState<string[]>([])

  const tagsJointChar = ","

  function queryUrl() {
    const { tag } = queryString.parse(
      typeof window !== "undefined"
        ? window.location.search.replace("?", "")
        : ""
    ) as { [key: string]: string }
    const tagsStr = tag || t("all")
    sessionStorage.setItem(STORAGE_KEY.PRACTICE, tagsStr)
    const tagsArr = tagsStr.split(tagsJointChar)
    submitCheck(tagsArr)
  }

  useEffect(() => {
    queryUrl()
  }, [])

  useEffect(() => {
    setMobileTags([...checkedTags])
  }, [checkedTags])
  const submit = () => {
    headerRef.current?.click()
    submitCheck(mobileTags)
  }

  const onCheck = useCallback(
    (tag: string) => {
      if (mobileTags.length === 1 && mobileTags[0] === tag) {
        return
      }
      const isChecked = !mobileTags.includes(tag)

      let newMobileTags = []
      if (isChecked && tag === t("all")) {
        newMobileTags = [t("all")]
      } else {
        newMobileTags = isChecked
          ? [...mobileTags.filter(i => i !== t("all")), tag]
          : mobileTags.filter(item => tag !== item)
      }

      setMobileTags(newMobileTags)

      sessionStorage.setItem(
        STORAGE_KEY.PRACTICE,
        newMobileTags.join(tagsJointChar)
      )

      window.history.replaceState(
        null,
        "",
        "?tag=" + newMobileTags.join(tagsJointChar)
      )
    },
    [mobileTags]
  )
  const onHeaderClick = () => {
    const target = headerRef.current as HTMLElement
    const classes = target?.classList || {}
    const hasClass = Object.values(classes).includes("tagListActive")
    setClass(!hasClass)
    hasClass ? classes.remove("tagListActive") : classes.add("tagListActive")
  }
  const renderSelectedTags = useCallback(() => {
    if (mobileTags.length === 1 && mobileTags[0] === t("all")) {
      return t("multi selectable")
    }
    const showTags = !hasActiveClass ? checkedTags : mobileTags
    return showTags.join(tagsJointChar)
  }, [hasActiveClass, mobileTags])
  return (
    <div className={cls(styles.tagContainer)}>
      <div
        ref={headerRef}
        className={cls(
          styles.headerContainer,
          "is-flex is-justify-content-space-between"
        )}
        onClick={onHeaderClick}
      >
        <h5>{t("select by tags")}</h5>
        <div className={styles.tipArea}>
          <span className={cls(styles.tipTitle, "mr-4")}>
            {renderSelectedTags()}
          </span>
          <span className={styles.headerIcon}>
            <Icon name="chevron-right" />
          </span>
        </div>
      </div>
      <div className={styles.tagList}>
        <ul>
          {Object.entries(tagsAndCount).map((item, i) => {
            return (
              <li
                className="is-flex is-justify-content-space-between"
                key={item[0] + i}
                onClick={() => onCheck(item[0])}
              >
                <span className={styles.checkboxWrapper}>
                  <span
                    className={
                      mobileTags.includes(item[0])
                        ? styles.iconChecked
                        : styles.iconNormal
                    }
                  >
                    <Icon
                      name={
                        mobileTags.includes(item[0])
                          ? "checkbox-active"
                          : "checkbox-normal"
                      }
                    />
                  </span>
                  <label className="checkbox">{item[0]}</label>
                </span>
                <p>{item[1]}</p>
              </li>
            )
          })}
        </ul>
        <button className="button is-primary" onClick={submit}>
          {t("confirm")}
        </button>
      </div>
    </div>
  )
}

export default MobilePracticeTagSelect
