import { headers as getHeaders } from 'next/headers'
import Image from 'next/image'
import { getPayload } from 'payload'
import React from 'react'
import { fileURLToPath } from 'url'
import { notFound } from 'next/navigation'

import config from '@/payload.config'
import { isValidLocale, localeNames, type Locale } from '@/lib/i18n'
import '../styles.css'

interface HomePageProps {
  params: Promise<{ locale: string }>
}

export default async function HomePage({ params }: HomePageProps) {
  const { locale } = await params

  if (!isValidLocale(locale)) {
    notFound()
  }

  const headers = await getHeaders()
  const payloadConfig = await config
  const payload = await getPayload({ config: payloadConfig })
  const { user } = await payload.auth({ headers })

  const fileURL = `vscode://file/${fileURLToPath(import.meta.url)}`

  // Localized content
  const content = {
    de: {
      welcome: 'Willkommen zu Ihrem neuen Projekt.',
      welcomeBack: 'Willkommen zurück,',
      adminPanel: 'Zum Admin-Panel',
      documentation: 'Dokumentation',
      updatePage: 'Diese Seite bearbeiten in',
    },
    en: {
      welcome: 'Welcome to your new project.',
      welcomeBack: 'Welcome back,',
      adminPanel: 'Go to admin panel',
      documentation: 'Documentation',
      updatePage: 'Update this page by editing',
    },
  }

  const t = content[locale as Locale]

  return (
    <div className="home">
      <div className="content">
        <picture>
          <source srcSet="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-favicon.svg" />
          <Image
            alt="Payload Logo"
            height={65}
            src="https://raw.githubusercontent.com/payloadcms/payload/main/packages/ui/src/assets/payload-favicon.svg"
            width={65}
          />
        </picture>
        {!user && <h1>{t.welcome}</h1>}
        {user && (
          <h1>
            {t.welcomeBack} {user.email}
          </h1>
        )}
        <div className="links">
          <a
            className="admin"
            href={payloadConfig.routes.admin}
            rel="noopener noreferrer"
            target="_blank"
          >
            {t.adminPanel}
          </a>
          <a
            className="docs"
            href="https://payloadcms.com/docs"
            rel="noopener noreferrer"
            target="_blank"
          >
            {t.documentation}
          </a>
        </div>
        <div className="locale-info" style={{ marginTop: '1rem' }}>
          <p>
            Current locale: <strong>{localeNames[locale as Locale].native}</strong>
          </p>
        </div>
      </div>
      <div className="footer">
        <p>{t.updatePage}</p>
        <a className="codeLink" href={fileURL}>
          <code>app/(frontend)/[locale]/page.tsx</code>
        </a>
      </div>
    </div>
  )
}
