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

import {jwennDenyeTeks} from '../../lib/oki-api'
import {formatKuveti} from '../../lib/kuveti'
import DenyeTeks from '../../components/teks/denye-teks'
import Footer from '../../components/footer'

const apiUrl = process.env.NEXT_PUBLIC_API_URL_ROOT || 'http://localhost:1337'
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'
const siteName = process.env.NEXT_PUBLIC_SITE_NAME || 'PAWÒL-NU. Paroles et traductions.'
const twitterHandle = `@${process.env.NEXT_PUBLIC_TWITTER_USERNAME || 'OrganisationKA'}`

async function jwennDone() {
  const denyeTeks = await jwennDenyeTeks()

  if (!denyeTeks) {
    notFound()
  }

  return denyeTeks
}

export async function generateMetadata() {
  const denyeTeks = await jwennDone()
  const couverture = formatKuveti(denyeTeks[0]?.couverture)
  const imageUrl = couverture?.url ? `${apiUrl}${couverture.url}` : `${siteUrl}/logo-512x512.png`
  const imageWidth = couverture?.width || 512
  const imageHeight = couverture?.height || 512
  const songList = denyeTeks.slice(0, 3).map(t => `${t.artistes[0]?.alias} – ${t.titre}`).join(', ')
  const description = `Derniers morceaux : ${songList}…`

  return {
    title: `${siteName} | Derniers morceaux`,
    description,
    openGraph: {
      title: `${siteName} | Derniers morceaux`,
      description,
      url: `${siteUrl}/paroles`,
      siteName,
      images: [{url: imageUrl, width: imageWidth, height: imageHeight}],
      locale: 'fr_FR',
      type: 'website',
    },
    twitter: {
      site: twitterHandle,
      card: 'summary_large_image',
      title: `${siteName} | Derniers morceaux`,
      description,
      creator: twitterHandle,
      images: {url: imageUrl, alt: 'Couverture du dernier morceau publié'},
    },
  }
}

export default async function PawolPaj() {
  const denyeTeks = await jwennDone()

  return (
    <Box sx={{display: 'flex', flexDirection: 'column', minHeight: '100vh'}}>
      <Box
        component='main'
        sx={{flexGrow: 1, p: 2, mt: 2}}
      >
        <DenyeTeks denyeTeks={denyeTeks} />
      </Box>
      <Footer />
    </Box>
  )
}
