import * as React from "react"
import groupBy from "lodash/groupBy"
import * as styles from "./index.module.scss"
import { CardItem } from "./card-item"
import Container from "@/components/container"
import { graphql, useStaticQuery } from "gatsby"
import { useEffect, useState } from "react"
import cls from "classnames"
import Icon from "@/components/icon"
import t from "@/constants/wording"
import Select from "react-select"
import EmptyList from "@/components/empty-list"
import MultiSelectComponent from "@/components/search-partner/all-partner/multi-select"

interface IPartner {
  node: Partner
}

const SelectAttr = {
  isSearchable: false,
  maxMenuHeight: 216,
  className: styles.selectItem,
  classNamePrefix: "select",
  placeholder: "请选择",
}

const CARD_NUM = 8

const partnerTypeOptions: Option[] = [{ label: "全部", value: "all" }]
const industryOptions: Option[] = []
const regionOptions: Option[] = [{ label: "全部", value: "all" }]

const AllPartner: React.FC = () => {
  const [sliceNum, setSliceNum] = useState<number>(CARD_NUM)
  const [isShowMoreButton, setIsShowMoreButton] = useState<boolean>(false)
  const [isLoading, setIsLoading] = useState<boolean>(true)
  const [renderPartners, setRenderPartners] = useState<IPartner[]>([])

  const data = useStaticQuery<AllPartner>(graphql`
    query AllPartner {
      allStrapiPartners(sort: { fields: order, order: ASC }) {
        edges {
          node {
            description
            name
            id
            link
            logo {
              alt
              media {
                url
              }
            }
            jointSolution {
              id
              customUrl
            }
            industries
            region
            partnerTypes {
              name
            }
          }
        }
      }
      strapiPartnerPage {
        logoDefault {
          media {
            url
          }
          alt
        }
      }
    }
  `)

  const partners = data.allStrapiPartners.edges
  const defaultLogo = data.strapiPartnerPage.logoDefault

  const [partnerTypeValue, setPartnerTypeValue] = useState<Option>()
  const [industryValue, setIndustryValue] = useState<Option[]>([])
  const [regionValue, setRegionValue] = useState<Option>()

  function creatOptions() {
    const partnerTypes: string[] = []
    const industries: string[] = []
    const region: string[] = []
    for (const item of partners) {
      if (item.node.partnerTypes && item.node.industries) {
        item.node.partnerTypes.map(i => partnerTypes.push(i.name))
        item.node.industries.map(i => industries.push(i))
      }
      if (item.node.region && !region.includes(item.node.region)) {
        region.push(item.node.region)
        regionOptions.push({
          label: item.node.region,
          value: item.node.region,
        })
      }
    }
    for (const item of Object.keys(groupBy(partnerTypes))) {
      partnerTypeOptions.push({
        label: item,
        value: item,
      })
    }
    for (const item of Object.keys(groupBy(industries))) {
      item !== "全行业" &&
        industryOptions.push({
          label: item,
          value: item,
        })
    }
  }

  function filterPartners() {
    const filteredPartners = partners.filter(item => {
      return (
        (!partnerTypeValue ||
          partnerTypeValue.value === "all" ||
          item.node.partnerTypes
            .map(i => i.name)
            .includes(partnerTypeValue.value)) &&
        (industryValue.length === 0 ||
          item.node.industries.includes("全行业") ||
          item.node.industries
            .map(i => industryValue.map(i => i.value).indexOf(i) !== -1)
            .includes(true)) &&
        (!regionValue ||
          regionValue.value === "all" ||
          item.node.region === regionValue.value)
      )
    })
    setRenderPartners(filteredPartners.slice(0, sliceNum))
    setIsShowMoreButton(filteredPartners.length > sliceNum)
    setIsLoading(false)
  }

  function addSliceNum() {
    setSliceNum(sliceNum + CARD_NUM)
  }

  function resetSliceNum() {
    setSliceNum(CARD_NUM)
  }

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

  useEffect(() => {
    filterPartners()
  }, [partnerTypeValue, industryValue, regionValue, sliceNum])

  useEffect(() => {
    resetSliceNum()
  }, [partnerTypeValue, industryValue, regionValue])

  return (
    <div className={styles.allPartners}>
      <Container>
        <div className={cls("columns", styles.select)}>
          <div className="column is-3 pr-4">
            <p className="pb-3">类型</p>
            <Select
              {...SelectAttr}
              value={partnerTypeValue}
              options={partnerTypeOptions}
              instanceId="partnerType"
              onChange={o => o && setPartnerTypeValue(o)}
            />
          </div>
          <div className={cls("column is-3 pr-4", styles.selectOption)}>
            <p className="pb-3">行业</p>
            <MultiSelectComponent
              options={industryOptions}
              value={industryValue}
              onChange={setIndustryValue}
            />
          </div>
          <div className={cls("column is-3 pr-4", styles.selectOption)}>
            <p className="pb-3">所在地区</p>
            <Select
              {...SelectAttr}
              value={regionValue}
              options={regionOptions}
              instanceId="region"
              onChange={o => o && setRegionValue(o)}
            />
          </div>
        </div>
        {!renderPartners.length ? (
          <div className={styles.emptyList}>{!isLoading && <EmptyList />}</div>
        ) : (
          <div>
            <div
              className={cls(
                "columns is-4-desktop is-2-tablet is-2-mobile is-variable is-flex-wrap-wrap",
                styles.partners
              )}
            >
              {renderPartners.map(data => (
                <CardItem
                  key={data.node.id}
                  cardInfo={data.node}
                  defaultLogo={defaultLogo}
                  attrs={{
                    "data-types": JSON.stringify(
                      data.node.partnerTypes.map(i => i.name)
                    ),
                    "data-industries": JSON.stringify(data.node.industries),
                    "data-region": data.node.region,
                  }}
                />
              ))}
            </div>
            <div className={styles.moreButton}>
              {isShowMoreButton && (
                <button
                  className="button is-medium is-ghost is-primary"
                  onClick={addSliceNum}
                >
                  <span>{t("expand to show more data")}</span>
                  <span className="icon">
                    <Icon name="chevron-right" />
                  </span>
                </button>
              )}
            </div>
          </div>
        )}
      </Container>
    </div>
  )
}

export default AllPartner
