import React, { useState, useEffect } from "react"
import Container from "@/components/container"
import * as styles from "./index.module.scss"
import cls from "classnames"
import { graphql, useStaticQuery, navigate } from "gatsby"
import Icon from "@/components/icon"

type Props = {
  selectedTag: string
  allTags: string[]
}

const AllSolutions = ({ selectedTag, allTags }: Props) => {
  const [size] = useState(12)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const [solutions, setSolutions] = useState<{ node: StrapiSolutions }[]>([])

  const fetchSolutions = () => {
    return useStaticQuery<AllStrapiSolutions>(graphql`
      query fetchSolutions {
        allStrapiSolutions(sort: { order: ASC, fields: order }) {
          edges {
            node {
              id
              order
              tags
              title
              description
              customUrl
            }
          }
        }
      }
    `)
  }

  const result = fetchSolutions()
  const {
    allStrapiSolutions: { edges = [] },
  } = result

  const pageChange = page => {
    setPage(page)
  }

  useEffect(() => {
    const data = filterData({ solutions: edges, selectedTag, allTags })
    setPage(1)
    setTotal(data.length)
    setSolutions(pageifyData(page, data))
  }, [selectedTag, allTags])

  useEffect(() => {
    const data = filterData({ solutions: edges, selectedTag, allTags })
    setTotal(data.length)
    setSolutions(pageifyData(page, data))
  }, [page])

  const filterData = ({
    solutions = [],
    selectedTag,
    allTags,
  }: {
    solutions: { node: StrapiSolutions }[]
    selectedTag: string
    allTags: string[]
  }) => {
    return solutions.filter(({ node }) => {
      const tags = node.tags || []
      const selected = selectedTag ? [selectedTag] : allTags
      return tags.filter(tag => {
        return selected.includes(tag)
      }).length
    })
  }

  const pageifyData = (page: number, data: { node: StrapiSolutions }[]) => {
    return data.slice(0, page * size)
  }

  return (
    <div className={styles.container}>
      <Container>
        <ul className={"columns is-variable is-4 is-multiline is-flex"}>
          {solutions.map(({ node }: { node: StrapiSolutions }) => (
            <li
              key={node.id}
              className={"column is-full-mobile is-half-tablet is-one-quarter"}
              onClick={() =>
                navigate(`/solution-detail/${node.customUrl ?? node.id}`)
              }
              data-tag={node.tags}
            >
              <h4 className={styles.h4}>{node.title}</h4>
              <p className={cls(styles.p1)}>{node.description}</p>
            </li>
          ))}
        </ul>
        <div
          className={cls(
            "is-flex is-justify-content-center",
            styles.moreButton
          )}
        >
          {!!total && page * size < total && (
            <button
              className="button is-medium is-ghost is-primary"
              onClick={() => pageChange(page + 1)}
            >
              <span>展开更多</span>
              <span className="icon">
                <Icon name="chevron-right" />
              </span>
            </button>
          )}
        </div>
      </Container>
    </div>
  )
}

export default AllSolutions
