import { ContactBlock } from '@/components/Contact'
import type { Metadata } from 'next'
import { Shell } from '@/components/Shell'
import { pageMeta } from '@/lib/meta'
import { type Locale, dateText, loadPage, loadSite, price } from '@/lib/site'
import { submitLead } from './actions'

type Props = { params: Promise<{ locale: Locale }>; searchParams: Promise<Record<string, 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)
}

export default async function Pricing({ params, searchParams }: Props) {
  const { locale } = await params
  const q = await searchParams
  // the catalogue holds the wording shared by every page that prints a price
  const [{ settings: s, courses }, p, cat] = await Promise.all([
    loadSite(locale), loadPage('pricing', locale), loadPage('catalogue', locale)])
  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}>
      <main id="main" className="section">
        <div className="wrap">
          <h1>{p.h1}</h1>
          <p className="lead">{p.lead}</p>
          <h2 style={{ marginTop: 'var(--tk-space-7)' }}>{p.plansTitle}</h2>
          <div className="grid grid--3">
            {(p.plans || []).map((plan) => (
              <article key={plan.id} className="card">
                <h3>{plan.name}</h3>
                <p className="muted">{plan.text}</p>
                <ul>
                  {(plan.items || []).map((i) => (
                    <li key={i.id}>{i.text}</li>
                  ))}
                </ul>
                <span className="price">
                  {plan.price || money.now}
                  {!plan.price && money.was ? <s className="price-was">{money.was}</s> : null}
                </span>
                {!plan.price && money.ends && cat.labels?.offerUntil ? (
                  <p className="price-offer">{cat.labels.offerUntil.replace('{date}', dateText(money.ends, locale))}</p>
                ) : null}
                {!plan.price && first?.price?.amount != null && first.price.note ? (
                  <p className="form-note" style={{ marginTop: 'var(--tk-space-2)' }}>
                    {first.price.note}
                  </p>
                ) : null}
              </article>
            ))}
          </div>

          <div className="narrow" style={{ marginTop: 'var(--tk-space-8)' }} id="form">
            <h2>{p.formTitle}</h2>
            <p className="lead">{p.formLead}</p>
            {q.sent ? (
              <div className="alert alert--info" role="status" style={{ marginTop: 'var(--tk-space-5)' }}>
                <span aria-hidden="true">✓</span>
                <p style={{ margin: 0 }}>{p.sent}</p>
              </div>
            ) : (
              <form className="form" action={submitLead} style={{ marginTop: 'var(--tk-space-5)' }}>
                {q.error ? (
                  <div className="alert alert--warn" role="alert">
                    <span aria-hidden="true">!</span>
                    <p style={{ margin: 0 }}>{p.invalid}</p>
                  </div>
                ) : null}
                <input type="hidden" name="locale" value={locale} />
                <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="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">
                  <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">
                  <label htmlFor="note">{f.note}</label>
                  <textarea id="note" name="note" rows={3} maxLength={2000} />
                </div>
                <p className="form-note">{p.privacy}</p>
                <div>
                  <button className="btn btn--primary" type="submit">
                    {p.submit}
                  </button>
                </div>
              </form>
            )}

            {/* the form is not the only way in: some people would rather send a message */}
            <ContactBlock settings={s} className="contact--card" />
          </div>
        </div>
      </main>
    </Shell>
  )
}
