import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { StatusBadge, UnitList } from '@/components/Course'
import { Shell } from '@/components/Shell'
import { pageMeta } from '@/lib/meta'
import { type Locale, dateText, embedUrl, isExternal, loadPage, loadSite, localHref, media, price } from '@/lib/site'

type Props = { params: Promise<{ locale: Locale; slug: string }> }

async function find(locale: Locale, slug: string) {
  const { settings, courses } = await loadSite(locale)
  return { settings, courses, course: courses.find((c) => c.slug === slug) }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale, slug } = await params
  const { settings, course } = await find(locale, slug)
  if (!course) return {}
  return pageMeta(locale, `/courses/${slug}`, `${course.titleShort || course.title} | ${settings.brandName}`, course.tagline)
}

export default async function CoursePage({ params }: Props) {
  const { locale, slug } = await params
  const [{ settings: s, courses, course: c }, cat] = await Promise.all([find(locale, slug), loadPage('catalogue', locale)])
  if (!c) notFound()
  const L = cat.labels || {}
  const soon = c.status === 'soon'
  // the platform handles sign-up and InstaPay payment; without a platform link, the interest form takes over
  const onPlatform = !soon && Boolean(c.platformUrl)
  const cta = soon ? s.cta?.notify : onPlatform ? s.cta?.subscribe || s.cta?.enrol : s.cta?.enrol
  const enrolHref = onPlatform ? (c.platformUrl as string) : localHref(locale, `/pricing?course=${c.slug}#form`)
  const poster = media(c.poster)
  const hasUnits = (c.units || []).length > 0
  const split = (c.units || []).some((u) => u.source === 'added' || (u.book !== null && u.book !== undefined))

  const money = price(c, s)
  const embed = embedUrl(c.videoUrl)
  const freeLessons = ((c.freeLessons || []) as any[]).filter((l) => embedUrl(l.videoUrl))
  const posterImg = poster?.url ? (
    <img src={poster.sizes?.wide?.url || poster.url} alt={c.title || ''} width={1280} height={720} loading="lazy" />
  ) : null

  return (
    <Shell locale={locale} path={`/courses/${c.slug}`} settings={s} courses={courses}>
      <main id="main">
        <section className="course-head">
          <div className="wrap">
            <div>
              <p className="breadcrumb">
                <a href={localHref(locale, '/courses')}>{L.back}</a>
              </p>
              <StatusBadge course={c} settings={s} />
              <h1>{c.title}</h1>
              <p className="lead">{c.tagline}</p>
              <ul className="tag-row">
                {(c.facts || []).map((f) => (
                  <li key={f.id} className="tag">
                    {f.text}
                  </li>
                ))}
              </ul>
            </div>
            <aside className="buy-card" aria-label={cta || ''}>
              <span className="price">
                {money.now}
                {money.was ? (
                  <s className="price-was" aria-label={L.priceWas || undefined}>
                    {money.was}
                  </s>
                ) : null}
              </span>
              {money.ends && L.offerUntil ? (
                <p className="price-offer">{L.offerUntil.replace('{date}', dateText(money.ends, locale))}</p>
              ) : null}
              {c.price?.amount !== null && c.price?.amount !== undefined && c.price?.note ? (
                <p className="form-note" style={{ marginTop: 0 }}>
                  {c.price.note}
                </p>
              ) : null}
              <ul>
                {(c.includes || []).map((x) => (
                  <li key={x.id}>{x.text}</li>
                ))}
              </ul>
              <a className="btn btn--primary" style={{ width: '100%' }} href={enrolHref} rel={isExternal(enrolHref) ? 'noopener' : undefined}>
                {cta}
              </a>
              <p className="form-note" style={{ marginTop: 'var(--tk-space-3)' }}>
                {c.availability}
              </p>
            </aside>
          </div>
        </section>

        <section className="section">
          <div className="wrap">
            <div className="grid grid--2">
              <div>
                <h2>{L.outcomes}</h2>
                <ul>
                  {(c.outcomes || []).map((x) => (
                    <li key={x.id}>{x.text}</li>
                  ))}
                </ul>
              </div>
              <div>
                <h2>{L.audience}</h2>
                <p>{c.audience}</p>
                <p className="muted">
                  <strong>{L.instruction}:</strong> {c.instruction}
                  <br />
                  <strong>{L.level}:</strong> {c.level}
                </p>
              </div>
            </div>
          </div>
        </section>

        {hasUnits ? (
          <section className="section-tight" style={{ background: 'var(--tk-bg-surface)', borderBlock: '1px solid var(--tk-border)' }}>
            <div className="wrap">
              <h2>{L.units}</h2>
              {split ? <p className="lead">{L.unitsLead}</p> : null}
              <UnitList course={c} labels={L} />
            </div>
          </section>
        ) : null}

        {freeLessons.length ? (
          <section className="section-tight band" id="free-lessons">
            <div className="wrap">
              <div className="center">
                <h2>{L.freeLessons}</h2>
                {L.freeLessonsNote ? <p className="lead">{L.freeLessonsNote}</p> : null}
              </div>
              <ul className="lessons grid grid--2">
                {freeLessons.map((l) => {
                  const img = media(l.poster)
                  return (
                    <li key={l.id} className="lesson">
                      <figure
                        className="poster"
                        data-embed={embedUrl(l.videoUrl) || undefined}
                        data-title={`${l.code ? l.code + ' · ' : ''}${l.title}`}
                      >
                        <a href={l.videoUrl as string} rel="noopener">
                          {img?.url ? (
                            <img src={img.sizes?.wide?.url || img.url} alt={l.title as string} width={1280} height={720} loading="lazy" />
                          ) : (
                            <span className="poster-blank" aria-hidden="true" />
                          )}
                        </a>
                        <span className="poster-play" aria-hidden="true">
                          ▶
                        </span>
                      </figure>
                      <div className="lesson-text">
                        {l.code ? <span className="lesson-n num">{l.code}</span> : null}
                        <h3 className="lesson-title">{l.title}</h3>
                      </div>
                    </li>
                  )
                })}
              </ul>
            </div>
          </section>
        ) : null}

        <section className="section-tight">
          <div className="wrap narrow center" id="preview">
            {/* the invitation to watch the first lesson belongs to a course that has one to show;
                a course still being built says only where it stands */}
            {posterImg ? (
              <>
                <h2>{L.preview}</h2>
                <p className="lead">{L.previewNote}</p>
              </>
            ) : null}
            {posterImg ? (
              <figure className="poster" data-embed={embed || undefined} data-title={c.title}>
                {c.videoUrl ? (
                  <a href={c.videoUrl} rel="noopener">
                    {posterImg}
                  </a>
                ) : (
                  posterImg
                )}
                {c.videoUrl ? (
                  <span className="poster-play" aria-hidden="true">
                    ▶
                  </span>
                ) : null}
                <figcaption>
                  {c.posterNote} · {c.availability}
                </figcaption>
              </figure>
            ) : (
              <div className="alert alert--info" style={{ textAlign: 'start' }}>
                <span aria-hidden="true">▶</span>
                <p style={{ margin: 0 }}>{c.availability}</p>
              </div>
            )}
          </div>
        </section>
      </main>
    </Shell>
  )
}
