import type { Metadata } from 'next'
import { Icon } from '@/components/icons'
import { NotABot } from '@/components/NotABot'
import { Shell } from '@/components/Shell'
import { botMessage, tooManyMessage, turnstileSiteKey } from '@/lib/antiSpam'
import { publicConfig } from '@/lib/config'
import { pageMeta } from '@/lib/meta'
import { type Locale, dateText, loadPage, loadSite, localHref, price } from '@/lib/site'
import { submitLead } from './actions'

type Props = { params: Promise<{ locale: Locale }>; searchParams: Promise<Record<string, string | undefined>> }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale } = await params
  const p = await loadPage('pricing', locale)
  return pageMeta(locale, '/pricing', p.seo?.title, p.seo?.description)
}

/**
 * What it costs, and the form that registers interest.
 *
 * A plan with no price of its own prints the first course's, offer and all, so the page cannot
 * disagree with the course page about what a student pays. The form posts to the same server action
 * as before and keeps all three spam defences: the honeypot, the time trap, and Turnstile when keys
 * are set.
 */
export default async function Pricing({ params, searchParams }: Props) {
  const { locale } = await params
  const q = await searchParams
  const [{ settings: s, courses }, p, cat] = await Promise.all([
    loadSite(locale),
    loadPage('pricing', locale),
    loadPage('catalogue', locale),
  ])
  const cfg = publicConfig()
  const f = p.fields || {}
  const chosen = typeof q.course === 'string' && courses.some((c) => c.slug === q.course) ? q.course : courses[0]?.slug
  const first = courses[0]
  const money = first ? price(first, s) : { now: '', was: null, ends: null }

  return (
    <Shell locale={locale} path="/pricing" settings={s} courses={courses} config={cfg}>
      <div className="container pagehead">
        <h1>{p.h1}</h1>
        <p>{p.lead}</p>
      </div>

      <section className="container">
        {(p.plans || []).length ? (
          <>
            <div className="section-head">
              <div><h2>{p.plansTitle}</h2></div>
            </div>
            <div className="plans">
              {(p.plans || []).map((plan) => (
                <div className="plan" key={plan.id}>
                  <h3>{plan.name}</h3>
                  <p>{plan.text}</p>
                  {(plan.items || []).length ? (
                    <ul className="ticks" style={{ marginBottom: 'var(--tk-space-5)' }}>
                      {(plan.items || []).map((i) => (
                        <li key={i.id}>
                          <Icon name="check" />
                          <span>{i.text}</span>
                        </li>
                      ))}
                    </ul>
                  ) : null}
                  <div style={{ marginTop: 'auto' }}>
                    <span className="amount">{plan.price || money.now}</span>
                    {!plan.price && money.was ? <del className="muted"> {money.was}</del> : null}
                    {!plan.price && money.ends && cat.labels?.offerUntil ? (
                      <p className="notice">{cat.labels.offerUntil.replace('{date}', dateText(money.ends, locale))}</p>
                    ) : null}
                    {!plan.price && first?.price?.amount != null && first.price.note ? (
                      <p className="notice">{first.price.note}</p>
                    ) : null}
                  </div>
                </div>
              ))}
            </div>
          </>
        ) : null}

        <div className="section" id="form">
          <div className="panel">
            <h2>{p.formTitle}</h2>
            <p>{p.formLead}</p>

            {q.sent ? (
              <div className="msg ok" role="status">{p.sent}</div>
            ) : (
              <form action={submitLead}>
                {q.error ? (
                  <div className="msg bad" role="alert">
                    {q.error === 'bot' ? botMessage(locale) : q.error === 'busy' ? tooManyMessage(locale) : p.invalid}
                  </div>
                ) : null}
                <input type="hidden" name="locale" value={locale} />
                {/* a field nobody sees; the machines that fill it are the ones we drop */}
                <div className="field" aria-hidden="true" style={{ position: 'absolute', insetInlineStart: '-9999px' }}>
                  <label htmlFor="website">Website</label>
                  <input id="website" name="website" tabIndex={-1} autoComplete="off" />
                </div>
                <div className="form-grid">
                  <div className="field">
                    <label htmlFor="name">{f.name}</label>
                    <input id="name" name="name" autoComplete="name" required minLength={2} maxLength={120} />
                  </div>
                  <div className="field">
                    <label htmlFor="email">{f.email}</label>
                    <input id="email" name="email" type="email" autoComplete="email" required maxLength={200} dir="ltr" />
                  </div>
                  <div className="field">
                    <label htmlFor="phone">{f.phone}</label>
                    <input id="phone" name="phone" type="tel" autoComplete="tel" inputMode="tel" maxLength={20} dir="ltr" />
                  </div>
                  <div className="field">
                    <label htmlFor="role">{f.role}</label>
                    <select id="role" name="role">
                      {(p.roles || []).map((r) => (
                        <option key={r.id}>{r.label}</option>
                      ))}
                    </select>
                  </div>
                  <div className="field wide">
                    <label htmlFor="course">{f.course}</label>
                    <select id="course" name="course" defaultValue={chosen}>
                      {courses.map((c) => (
                        <option key={c.id} value={c.slug}>{c.title}</option>
                      ))}
                    </select>
                  </div>
                  <div className="field wide">
                    <label htmlFor="note">{f.note}</label>
                    <textarea id="note" name="note" rows={4} maxLength={2000} />
                  </div>
                </div>
                <NotABot siteKey={turnstileSiteKey()} locale={locale} />
                <p className="form-note">{p.privacy}</p>
                <div className="actions" style={{ marginTop: 'var(--tk-space-4)' }}>
                  <button className="btn" type="submit">
                    {p.submit}
                    <Icon name="arrow" />
                  </button>
                </div>
              </form>
            )}

            {/* the form is not the only way in: some people would rather send a message */}
            <p className="notice" style={{ marginTop: 'var(--tk-space-5)' }}>
              <a className="link" href={localHref(locale, '/contact')}>{s.nav?.find((n) => (n.href || '').includes('contact'))?.label} ↗</a>
            </p>
          </div>
        </div>
      </section>
    </Shell>
  )
}
