'use client'

import { useState, FormEvent } from 'react'
import { Puzzle, Gavel, Coins, Building2, Check } from 'lucide-react'

const plugins = [
  {
    icon: Puzzle,
    title: 'Custom policy plugins',
    desc: 'Heuristics as code. Allow or deny on whatever context you care about.',
  },
  {
    icon: Gavel,
    title: 'Model Council',
    desc: 'A panel of models votes on ambiguous requests. Guardrails without the friction.',
  },
  {
    icon: Coins,
    title: 'Token-saving MITM',
    desc: 'Cache, redact, and rewrite LLM traffic. Smaller bills.',
  },
  {
    icon: Building2,
    title: 'Enterprise controls',
    desc: 'SSO, audit trails, team rulesets, managed deployments.',
  },
]

type Status = 'idle' | 'submitting' | 'success' | 'error'

export function Waitlist() {
  const [email, setEmail] = useState('')
  const [useCase, setUseCase] = useState('')
  const [status, setStatus] = useState<Status>('idle')
  const [error, setError] = useState('')

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (status === 'submitting') return
    setStatus('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: 'Greywall enterprise / plugin SDK waitlist',
          from_name: 'Greywall waitlist',
          email,
          message: useCase || '(no use case provided)',
          botcheck: '',
        }),
      })
      const data = await res.json()
      if (data.success) {
        setStatus('success')
        setEmail('')
        setUseCase('')
      } else {
        setStatus('error')
        setError(data.message || 'Something went wrong. Try again?')
      }
    } catch {
      setStatus('error')
      setError('Network error. Try again?')
    }
  }

  return (
    <section id="waitlist" className="py-24 px-4 sm:px-6 border-t border-border/30">
      <div className="mx-auto max-w-5xl">
        <div className="max-w-2xl mb-10">
          <div className="flex items-center gap-2 mb-4">
            <Puzzle className="h-4 w-4 text-primary" />
            <span className="text-xs font-sans uppercase tracking-wider text-primary font-medium">
              Plugin SDK &middot; Beta
            </span>
          </div>
          <h2 className="font-serif text-3xl sm:text-4xl font-semibold tracking-tight mb-4">
            Extend Greyproxy.
          </h2>
          <p className="text-muted-foreground font-serif text-lg leading-relaxed">
            We&apos;re building a plugin SDK on top of Greyproxy, and we&apos;ll help you
            build the plugins you need on top of it.
          </p>
        </div>

        {/* Plugin cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 mb-6">
          {plugins.map((p) => (
            <div
              key={p.title}
              className="p-4 sm:p-6 rounded-lg border border-border/40 bg-card/30"
            >
              <div className="flex items-center gap-3 mb-3">
                <p.icon className="h-5 w-5 text-primary" />
                <h3 className="font-sans font-semibold text-sm">{p.title}</h3>
              </div>
              <p className="text-sm text-muted-foreground font-serif leading-relaxed">
                {p.desc}
              </p>
            </div>
          ))}
        </div>

        {/* Freedom guarantee */}
        <div className="mb-12 p-5 rounded-lg border border-primary/15 bg-primary/[0.03]">
          <p className="text-sm text-muted-foreground font-serif leading-relaxed">
            <span className="text-primary font-medium">Core stays free and open source.</span>{' '}
            Sandbox, Greyproxy, and the dashboard stay Apache 2.0 forever. Plugin SDK and
            enterprise ride on top.
          </p>
        </div>

        {/* Waitlist form */}
        <div className="mx-auto max-w-2xl rounded-lg border border-border/40 bg-card/30 p-6 sm:p-8">
          {status === 'success' ? (
            <div className="text-center py-6">
              <div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-primary/10 mb-4">
                <Check className="h-6 w-6 text-primary" />
              </div>
              <h3 className="font-serif text-xl font-semibold mb-2">You&apos;re on the list.</h3>
              <p className="text-sm text-muted-foreground font-serif">
                We&apos;ll reach out as the plugin SDK takes shape. Thanks for helping us build it.
              </p>
            </div>
          ) : (
            <form onSubmit={onSubmit} className="space-y-4">
              <div>
                <label
                  htmlFor="wl-email"
                  className="block text-xs font-sans font-medium text-muted-foreground mb-2 uppercase tracking-wider"
                >
                  Work email
                </label>
                <input
                  id="wl-email"
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@company.com"
                  className="w-full rounded-md border border-border/40 bg-background/40 px-4 py-3 text-sm font-sans text-foreground placeholder:text-muted-foreground/60 focus:outline-none focus:border-primary/40 transition-colors"
                />
              </div>
              <div>
                <label
                  htmlFor="wl-usecase"
                  className="block text-xs font-sans font-medium text-muted-foreground mb-2 uppercase tracking-wider"
                >
                  What would you build?{' '}
                  <span className="normal-case text-muted-foreground/60 font-normal">
                    (optional, we can help)
                  </span>
                </label>
                <textarea
                  id="wl-usecase"
                  value={useCase}
                  onChange={(e) => setUseCase(e.target.value)}
                  rows={3}
                  placeholder="A plugin that... / a policy for... / our team needs..."
                  className="w-full rounded-md border border-border/40 bg-background/40 px-4 py-3 text-sm font-sans text-foreground placeholder:text-muted-foreground/60 focus:outline-none focus:border-primary/40 transition-colors resize-y"
                />
              </div>
              {/* Honeypot: bots fill hidden fields, humans don't */}
              <input
                type="checkbox"
                name="botcheck"
                className="hidden"
                style={{ display: 'none' }}
                tabIndex={-1}
                autoComplete="off"
              />
              <button
                type="submit"
                disabled={status === 'submitting'}
                className="w-full inline-flex items-center justify-center gap-2 px-6 py-3 rounded-md bg-primary text-primary-foreground font-sans text-sm font-medium hover:bg-primary/90 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {status === 'submitting' ? 'Submitting…' : 'Join the waitlist'}
              </button>
              {status === 'error' && (
                <p className="text-xs text-red-400/80 font-sans text-center">{error}</p>
              )}
            </form>
          )}
        </div>
      </div>
    </section>
  )
}
