import React, { useEffect, useState } from "react"
import { useStaticQuery, graphql } from "gatsby"
import * as styles from "./index.module.scss"
import { Container } from "@/components"
import CompanyNewsCard from "@/components/about-us/company-news-card"
import MediaReportsNewsCard from "@/components/about-us/media-reports-news-card"
import Pagination from "@/components/practice/pagination"

interface IProps {
  isNews?: boolean
}

const NewsList: React.FC<IProps> = ({ isNews }) => {
  const {
    allStrapiAboutUsNews,
    allStrapiAboutUsMediaReports,
  } = useStaticQuery<{
    allStrapiAboutUsNews: {
      nodes: CompanyNewsDetail[]
    }
    allStrapiAboutUsMediaReports: {
      nodes: AboutUsMediaReports[]
    }
  }>(
    graphql`
      query FatchStrapiNewsList {
        allStrapiAboutUsNews(sort: { fields: date, order: DESC }) {
          nodes {
            id
            title
            customUrl
            image {
              alt
              media {
                url
              }
            }
            date
            author
            body
            type
          }
        }
        allStrapiAboutUsMediaReports(sort: { fields: date, order: DESC }) {
          nodes {
            id
            title
            link
            logo {
              alt
              media {
                url
              }
            }
            date
          }
        }
      }
    `
  )
  const NEWS_PAGE_SIZE = 6
  const MEDIA_PAGE_SIZE = 10
  const pageSize = isNews ? NEWS_PAGE_SIZE : MEDIA_PAGE_SIZE
  const list = isNews
    ? allStrapiAboutUsNews.nodes
    : allStrapiAboutUsMediaReports.nodes
  const total = list.length
  const [currentPage, setCurrentPage] = useState<number>(0)
  const [renderList, setRenderList] = useState<any[]>([])

  const onPagination = (page: number) => {
    setCurrentPage(page)
  }
  const slicePage = (list: any[]) =>
    list.slice(currentPage * pageSize, (currentPage + 1) * pageSize)

  useEffect(() => {
    setRenderList(list && slicePage(list))
  }, [currentPage])

  return (
    <Container isSmall={true}>
      <div>
        {renderList.map(item =>
          isNews ? (
            <CompanyNewsCard {...item} key={item.id} />
          ) : (
            <MediaReportsNewsCard {...item} key={item.id} />
          )
        )}
      </div>
      <div className={styles.pager}>
        <Pagination
          pageSize={pageSize}
          total={total}
          onSelect={onPagination}
          currentPage={currentPage}
        />
      </div>
    </Container>
  )
}

export default NewsList
