import {notFound} from 'next/navigation'
import Box from '@mui/material/Box'
import Container from '@mui/material/Container'
import Grid from '@mui/material/Grid'

import ChecheAwtis from '../../components/awtis/cheche-awtis'
import AwtisKat from '../../components/awtis/awtis-kat'
import Pajinasyon from '../../components/awtis/pajinasyon'

import {jwennAwtisPajinasyon} from '../../lib/oki-api'
import Footer from '../../components/footer'

const siteName = process.env.NEXT_PUBLIC_SITE_NAME || 'PAWÒL-NU. Paroles et traductions.'
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://pawol.nu'
const twitterHandle = `@${process.env.NEXT_PUBLIC_TWITTER_USERNAME || 'OrganisationKA'}`

export const metadata = {
  title: `${siteName} | Artistes`,
  description: 'Liste des artistes ayant une ou plusieurs œuvres présentes sur le site.',
  openGraph: {
    title: `${siteName} | Artistes`,
    description: 'Liste des artistes ayant une ou plusieurs œuvres présentes sur le site.',
    url: `${siteUrl}/awtis`,
    siteName,
    images: [
      {
        url: `${siteUrl}/logo-512x512.png`,
        width: 512,
        height: 512
      }
    ],
    locale: 'fr_FR',
    type: 'website'
  },
  twitter: {
    site: twitterHandle,
    card: 'summary_large_image',
    title: `${siteName} | Artistes`,
    description: 'Liste des artistes ayant une ou plusieurs œuvres présentes sur le site.',
    creator: twitterHandle,
    images: {
      url: `${siteUrl}/logo-512x512.png`,
      alt: `${siteName} Logo`,
    }
  }
}

async function jwennDone(paj) {
  const pajParsed = Array.isArray(paj) ? Number.parseInt(paj[1], 10) : Number.parseInt(paj, 10)

  if (Number.isNaN(pajParsed)) {
    notFound()
  }

  const {data, meta} = await jwennAwtisPajinasyon(pajParsed)
  const pajTotal = Math.ceil(meta.pagination.total / meta.pagination.limit)

  if (pajParsed > pajTotal || pajParsed < 1) {
    notFound()
  }

  return {pajTotal, awtisPouChakPaj: data, pajParsed}
}

export default async function AwitsPaj(props) {
  const searchParams = await props.searchParams
  const {paj} = searchParams
  const {pajTotal, awtisPouChakPaj, pajParsed} = await jwennDone(paj || 1)

  return (
    <Box sx={{display: 'flex', flexDirection: 'column', minHeight: '100vh'}}>
      <Pajinasyon pajTotal={pajTotal} paj={pajParsed} />
      <ChecheAwtis />
      <Container sx={{marginBottom: 5, flexGrow: 100}}>
        <Grid container spacing={{xs: 2, md: 3}}>
          {awtisPouChakPaj.map(artiste => <AwtisKat key={artiste.id} artiste={artiste} />)}
        </Grid>
      </Container>
      <Footer />
    </Box>
  )
}
