import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { Icon } from '@/components/icons'
import { Shell } from '@/components/Shell'
import { publicConfig } from '@/lib/config'
import { pageMeta } from '@/lib/meta'
import {
  type Locale, categoryOf, 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, categories } = await loadSite(locale)
  return { settings, courses, categories, 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)
}

/**
 * One course: what it is, what it costs, what is in it, and the way in.
 *
 * Everything on it belongs to the learning platform except the picture and the free-lesson videos,
 * which are the site's. Every video is watched on the platform, never played here, so a lesson is
 * seen in its own place with its files and its practice beside it.
 */
export default async function CoursePage({ params }: Props) {
  const { locale, slug } = await params
  const [{ settings: s, courses, categories, course: c }, cat] = await Promise.all([
    find(locale, slug),
    loadPage('catalogue', locale),
  ])
  if (!c) notFound()
  const cfg = publicConfig()
  const L = cat.labels || {}
  const soon = c.status === 'soon'
  // The platform handles sign-up and payment. With no 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 cover = poster?.sizes?.wide?.url || poster?.url || c.image || null
  const money = price(c, s)
  const units = c.units || []
  // A school course's units say which came from the ministry's book; a work course has no book, so the
  // same column would claim an accreditation nobody granted — it says «core» there instead.
  const split = units.some((u) => u.source === 'added' || (u.book !== null && u.book !== undefined))
  const freeLessons = (c.freeLessons || []).filter((l) => embedUrl(l.videoUrl))
  const category = categoryOf(c, categories)

  const unitWord = (kind: string | null | undefined) =>
    kind === 'labs' ? L.labsWord : kind === 'projects' ? L.projectsWord : L.lessonsWord

  return (
    <Shell locale={locale} path={`/courses/${c.slug}`} settings={s} courses={courses} config={cfg}>
      <div className="container pagehead">
        <p>
          <a className="link" href={localHref(locale, '/courses')}>
            ↩ {L.back}
          </a>
        </p>
        {category ? <span className="eyebrow">{category.name}</span> : null}
        <h1>{c.title}</h1>
        <p>{c.tagline}</p>
        {(c.facts || []).length ? (
          <div className="tag-row" style={{ marginTop: 'var(--tk-space-4)' }}>
            {(c.facts || []).map((f) => (
              <span className="tag" key={f.id}>{f.text}</span>
            ))}
          </div>
        ) : null}
      </div>

      <section className="container">
        <div className="course-hero">
          <div>
            {cover ? (
              <div className="cover">
                <img src={cover} alt="" width={1280} height={720} />
              </div>
            ) : null}

            {(c.outcomes || []).length ? (
              <div className="panel" style={{ marginTop: 'var(--tk-space-5)' }}>
                <h2>{L.outcomes}</h2>
                <ul className="ticks">
                  {(c.outcomes || []).map((x) => (
                    <li key={x.id}>
                      <Icon name="check" />
                      <span>{x.text}</span>
                    </li>
                  ))}
                </ul>
              </div>
            ) : null}

            <div className="panel" style={{ marginTop: 'var(--tk-space-5)' }}>
              <h2>{L.audience}</h2>
              <p>{c.audience}</p>
              <ul className="facts">
                {c.instruction ? <li><b>{L.instruction}:</b> {c.instruction}</li> : null}
                {c.level ? <li><b>{L.level}:</b> {c.level}</li> : null}
              </ul>
            </div>
          </div>

          {/* The way in. It is a panel rather than a floating bar: on a phone a sticky bar over an
              Arabic page covers the text a reader is in the middle of. */}
          <aside className="panel" aria-label={cta || ''}>
            <div className="price-box">
              <span className="now">{money.now}</span>
              {money.was ? (
                <>
                  {L.priceWas ? <span className="sr-only">{L.priceWas}</span> : null}
                  <del>{money.was}</del>
                </>
              ) : null}
            </div>
            {money.ends && L.offerUntil ? (
              <p className="notice">{L.offerUntil.replace('{date}', dateText(money.ends, locale))}</p>
            ) : null}
            {c.price?.note ? <p className="notice">{c.price.note}</p> : null}

            {(c.includes || []).length ? (
              <ul className="ticks" style={{ marginBlock: 'var(--tk-space-5)' }}>
                {(c.includes || []).map((x) => (
                  <li key={x.id}>
                    <Icon name="check" />
                    <span>{x.text}</span>
                  </li>
                ))}
              </ul>
            ) : null}

            <a className="btn" style={{ width: '100%' }} href={enrolHref}
               rel={isExternal(enrolHref) ? 'noopener' : undefined}>
              {cta}
              <Icon name="arrow" />
            </a>
            {c.availability ? <p className="notice" style={{ marginTop: 'var(--tk-space-3)' }}>{c.availability}</p> : null}
          </aside>
        </div>
      </section>

      {units.length ? (
        <section className="section muted">
          <div className="container">
            <div className="section-head">
              <div>
                <h2>{L.units}</h2>
                {split ? <p>{L.unitsLead}</p> : null}
              </div>
            </div>
            <div className="units">
              {units.map((u) => (
                <div className="unit" key={u.id || u.n}>
                  <span className="n num">{u.n}</span>
                  <span className="t">
                    <strong>{u.name}</strong>
                    <span>
                      <span className="num">{u.lessons}</span> {unitWord(u.kind)}
                    </span>
                  </span>
                  <span className="tag">
                    {u.source === 'added'
                      ? (u.kind === 'lessons' ? L.added : L.addedUnit)
                      : u.book !== null && u.book !== undefined
                        ? `${L.fromBook} ${u.book}`
                        : L.fromCore}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </section>
      ) : null}

      {freeLessons.length ? (
        <section className="section" id="free-lessons">
          <div className="container">
            <div className="section-head">
              <div>
                <h2>{L.freeLessons}</h2>
                {L.freeLessonsNote ? <p>{L.freeLessonsNote}</p> : null}
              </div>
            </div>
            <div className="grid">
              {freeLessons.map((l) => {
                const img = media(l.poster)
                const href = (l.platformUrl as string) || enrolHref
                return (
                  <article className="course-card" key={l.id}>
                    <a className="course-cover" href={href} rel="noopener" aria-label={l.title as string}>
                      {img?.url ? (
                        <img src={img.sizes?.wide?.url || img.url} alt="" width={1280} height={720} loading="lazy" />
                      ) : (
                        <Icon name="play" />
                      )}
                    </a>
                    <div className="course-body">
                      {l.code ? <div className="course-category num">{l.code}</div> : null}
                      <h3>
                        <a href={href} rel="noopener">{l.title}</a>
                      </h3>
                      <div className="bottom">
                        <span className="soon">{L.watch}</span>
                        <a className="link" href={href} rel="noopener">▶</a>
                      </div>
                    </div>
                  </article>
                )
              })}
            </div>
          </div>
        </section>
      ) : null}
    </Shell>
  )
}
