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

import AwtisDetay from '../../../components/awtis/awtis-detay'
import {jwennAwtisEpiSlug} from '../../../lib/oki-api'
import {formatKuveti} from '../../../lib/kuveti'
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'

async function jwennAwtis(slug) {
  const {data} = await jwennAwtisEpiSlug(slug)

  if (!data) {
    notFound()
  }

  return data
}

export async function generateMetadata(props) {
  const params = await props.params
  const {slug} = params
  const anAwtis = await jwennAwtis(slug)

  const title = `PAWÒL-NU | ${anAwtis.alias}`
  const description = `${anAwtis.alias}${anAwtis?.biographie ? ` : ${anAwtis?.biographie.slice(0, 100)}...` : ''}`
  const url = `${siteUrl}/awtis/${slug}`

  const {photo} = anAwtis
  const kuvetiFormat = formatKuveti(photo)

  return {
    title,
    description,
    openGraph: {
      title,
      description,
      url,
      siteName: title,
      images: [
        {
          url: `${apiUrl}${kuvetiFormat?.url}`,
          width: kuvetiFormat?.width,
          height: kuvetiFormat?.height
        }
      ],
      locale: 'fr_FR',
      type: 'website'
    },
    twitter: {
      site: `@${process.env.NEXT_PUBLIC_TWITTER_USERNAME || 'OrganisationKA'}`,
      card: 'summary_large_image',
      title,
      description,
      creator: `@${process.env.NEXT_PUBLIC_TWITTER_USERNAME || 'OrganisationKA'}`,
      images: {
        url: `${apiUrl}${kuvetiFormat?.url}`,
        alt: `Photo de ${anAwtis.alias}`,
      }
    }
  }
}

export default async function AwtisPajSlug(props) {
  const params = await props.params
  const {slug} = params
  const anAwtis = await jwennAwtis(slug)

  const {photo} = anAwtis
  const kuvetiFormat = formatKuveti(photo)

  const jsonLd = {
    '@context': 'http://schema.org',
    '@type': 'Person',
    '@id': anAwtis.musicBrainzUrl || undefined,
    name: anAwtis.alias,
    url: `${siteUrl}/awtis/${slug}`,
    image: kuvetiFormat?.url ? `${apiUrl}${kuvetiFormat.url}` : undefined
  }

  return (
    <>
      <Box sx={{display: 'flex', flexDirection: 'column', minHeight: '100vh'}}>
        <Box sx={{flexGrow: 1}}>
          <AwtisDetay anAwtis={anAwtis} />
        </Box>
        <Footer />
      </Box>
      <section>
        <script
          type='application/ld+json'
          dangerouslySetInnerHTML={{__html: JSON.stringify(jsonLd)}}
        />
      </section>
    </>
  )
}
