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, loadPage, loadSite, whatsapp } from '@/lib/site'
import { submitLead } from '../pricing/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('contactpage', locale)
  return pageMeta(locale, '/contact', p.seo?.title, p.seo?.description)
}

/**
 * «اتصل بنا»: the ways to reach us, and one short form that does.
 *
 * The form still posts to the same server action as before and is saved as an interest request, which
 * is where the team already looks — only its clothes changed. The three spam defences are untouched:
 * the honeypot field, the time trap inside the action, and Turnstile when its keys are configured.
 */
export default async function ContactPage({ params, searchParams }: Props) {
  const { locale } = await params
  const q = await searchParams
  const [{ settings: s, courses }, p, pricing] = await Promise.all([
    loadSite(locale),
    loadPage('contactpage', locale),
    loadPage('pricing', locale),
  ])
  const cfg = publicConfig()
  const f = pricing.fields || {}
  const wa = whatsapp(s.contact?.whatsapp, s.contact?.waText || undefined)
  const email = s.contact?.email || cfg.email

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

      <section className="container">
        <div className="two-col">
          <div className="panel">
            <h2>{p.waysTitle}</h2>
            {s.contact?.lead ? <p>{s.contact.lead}</p> : null}
            <div className="contact-items">
              {email ? (
                <a className="contact-item" href={`mailto:${email}`}>
                  <span className="mini-icon"><Icon name="mail" /></span>
                  <div>
                    <span>{f.email}</span>
                    <strong>{email}</strong>
                  </div>
                </a>
              ) : null}
              {wa ? (
                <a className="contact-item" href={wa.href} target="_blank" rel="noopener noreferrer">
                  <span className="mini-icon"><Icon name="chat" /></span>
                  <div>
                    <span>WhatsApp</span>
                    <strong>{wa.label}</strong>
                  </div>
                </a>
              ) : null}
              {s.contact?.phone ? (
                <a className="contact-item" href={`tel:${s.contact.phone.replace(/[^\d+]/g, '')}`}>
                  <span className="mini-icon"><Icon name="phone" /></span>
                  <div>
                    <span>{f.phone}</span>
                    <strong>{s.contact.phone}</strong>
                  </div>
                </a>
              ) : null}
              {s.contact?.youtube ? (
                <a className="contact-item" href={s.contact.youtube} target="_blank" rel="noopener noreferrer">
                  <span className="mini-icon"><Icon name="youtube" /></span>
                  <div>
                    <span>{s.cta?.youtube}</span>
                    <strong>YouTube ↗</strong>
                  </div>
                </a>
              ) : null}
            </div>
            {p.reassure?.title || p.reassure?.text ? (
              <>
                <h3 style={{ marginTop: 'var(--tk-space-6)' }}>{p.reassure?.title}</h3>
                <p>{p.reassure?.text}</p>
              </>
            ) : null}
          </div>

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

            {q.sent ? (
              <div className="msg ok" role="status">
                {pricing.sent}
              </div>
            ) : (
              <form action={submitLead}>
                {q.error ? (
                  <div className="msg bad" role="alert">
                    {/* A visitor who simply did not tick the box is told that, not that their details
                        are wrong: sending them back to re-check a correct email is how you lose them. */}
                    {q.error === 'bot' ? botMessage(locale) : q.error === 'busy' ? tooManyMessage(locale) : pricing.invalid}
                  </div>
                ) : null}
                <input type="hidden" name="locale" value={locale} />
                <input type="hidden" name="from" value="contact" />
                {/* 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 wide">
                    <label htmlFor="note">{f.note}</label>
                    <textarea id="note" name="note" rows={5} maxLength={2000} />
                  </div>
                </div>
                <NotABot siteKey={turnstileSiteKey()} locale={locale} />
                <p className="form-note">{pricing.privacy}</p>
                <div className="actions" style={{ marginTop: 'var(--tk-space-4)' }}>
                  <button className="btn" type="submit">
                    {pricing.submit}
                    <Icon name="arrow" />
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </section>
    </Shell>
  )
}
