'use client'

import { useState, type FormEvent } from 'react'
import { Check } from 'lucide-react'
import { CTAButton } from './cta-button'

type Mode = 'button' | 'input' | 'submitting' | 'success' | 'error'

type BetaSignupProps = {
  subject: string
  message: string
  buttonClassName?: string
  submitClassName?: string
  inputClassName?: string
  helperTextClassName?: string
  successClassName?: string
  errorClassName?: string
  formClassName?: string
  wrapperClassName?: string
}

export function BetaSignup({
  subject,
  message,
  buttonClassName = '',
  submitClassName = '',
  inputClassName = '',
  helperTextClassName = 'text-xs text-muted-foreground/60 font-serif',
  successClassName = 'inline-flex items-center gap-2 rounded-md border border-primary/20 bg-primary/[0.05] px-5 py-2.5 font-sans text-sm text-primary font-medium',
  errorClassName = 'text-xs text-red-400/80 font-sans text-center',
  formClassName = 'flex items-center gap-2',
  wrapperClassName = 'flex flex-col items-center gap-2',
}: BetaSignupProps) {
  const [mode, setMode] = useState<Mode>('button')
  const [email, setEmail] = useState('')
  const [error, setError] = useState('')

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (mode === 'submitting') return
    setMode('submitting')
    setError('')

    try {
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
        body: JSON.stringify({
          access_key: '85d3252e-5890-450c-aa93-12dc89c7c9b5',
          subject,
          from_name: 'Greywall waitlist',
          email,
          message,
          botcheck: '',
        }),
      })

      const data = await res.json()
      if (data.success) {
        setMode('success')
        setEmail('')
      } else {
        setMode('error')
        setError(data.message || 'Something went wrong. Try again?')
      }
    } catch {
      setMode('error')
      setError('Network error. Try again?')
    }
  }

  return (
    <div className={wrapperClassName}>
      {mode === 'button' && (
        <CTAButton onClick={() => setMode('input')} className={buttonClassName}>
          Join closed beta
          <span aria-hidden="true">→</span>
        </CTAButton>
      )}
      {(mode === 'input' || mode === 'submitting') && (
        <form onSubmit={onSubmit} className={formClassName}>
          <input
            type="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="you@company.com"
            autoFocus
            className={inputClassName}
          />
          <CTAButton type="submit" disabled={mode === 'submitting'} className={submitClassName}>
            {mode === 'submitting' ? '...' : 'Join'}
          </CTAButton>
        </form>
      )}
      {mode === 'success' && (
        <div className={successClassName}>
          <Check className="h-4 w-4" />
          You&apos;re on the list.
        </div>
      )}
      {mode === 'error' && <p className={errorClassName}>{error}</p>}
      <p className={helperTextClassName}>One note when access opens.</p>
    </div>
  )
}
