import React, { ReactElement, useState } from "react"
import { graphql, PageProps } from "gatsby"
import { IGatsbyImageData } from "gatsby-plugin-image"
import dayjs from "dayjs"

import { Layout, Content, CardList } from "@onegeo-suite/gatsby-theme-onegeo"

import { ViewListIcon, ViewGridIcon } from "@heroicons/react/outline"

interface INew {
    id?: string
    title?: string
    content?: string
    abstract?: string
    image?: {
        id?: string
        imageFile?: IGatsbyImageData
    }
}

interface DataProps {
    directus: {
        news: INew[]
    }
}

function News({ data }: PageProps<DataProps>): ReactElement {
    const [bLayoutGrid, setLayoutGrid] = useState(false)

    const onSetLayout = () => {
        setLayoutGrid((prevState) => !prevState)
    }

    const layout = bLayoutGrid ? "grid" : "row"

    const listNews = data.directus.news.map((dt) => {
        return {
            name: dt.title,
            description: dt.abstract || dt.content,
            image: dt.image?.imageFile,
            url: "/news/" + dt.slug,
            category: dt.categories,
            date: dayjs(dt.date_published).format("DD/MM/YYYY"),
        }
    })

    return (
        <Layout>
            <Content>
                <div className="p-6 sm:flex">
                    <h2 className="w-full text-3xl font-extrabold tracking-tight sm:text-4xl">
                        Actualités
                    </h2>
                    <div className="flex w-full items-center gap-6">
                        <button className="h-8 w-8" onClick={onSetLayout}>
                            {bLayoutGrid ? <ViewGridIcon /> : <ViewListIcon />}
                        </button>
                        <input
                            type="text"
                            placeholder="Titre, description"
                            className="input input-bordered w-full"
                        />
                    </div>
                </div>

                <CardList
                    cards={listNews}
                    layout={layout}
                    anime={bLayoutGrid}
                />
            </Content>
        </Layout>
    )
}

export default News

export const query = graphql`
    query {
        directus {
            news(
                filter: { status: { _eq: "published" } }
                sort: "-date_published"
            ) {
                id
                slug
                content
                abstract
                title
                date_published
                image {
                    id
                    imageFile {
                        childImageSharp {
                            gatsbyImageData
                        }
                        name
                        publicURL
                    }
                }
                categories {
                    id
                    name
                    label
                }
            }
        }
    }
`