'use client'

import { useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { api } from '@/lib/api'
import { Mail, Loader2, CheckCircle, AlertCircle, ArrowLeft } from 'lucide-react'
import Link from 'next/link'

export default function UnsubscribePage() {
  const searchParams = useSearchParams()
  const emailFromUrl = searchParams.get('email') || ''
  const tokenFromUrl = searchParams.get('token') || ''
  
  const [email, setEmail] = useState(emailFromUrl)
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle')
  const [message, setMessage] = useState('')

  const handleUnsubscribe = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!email || !email.includes('@')) {
      setStatus('error')
      setMessage('Please enter a valid email address')
      return
    }
    
    setStatus('loading')
    setMessage('')
    
    try {
      await api.unsubscribeNewsletter(email, tokenFromUrl || undefined)
      setStatus('success')
      setMessage('You have been successfully unsubscribed from our newsletter.')
    } catch (err: any) {
      setStatus('error')
      setMessage(err.message || 'Failed to unsubscribe. Please try again or contact support.')
    }
  }

  return (
    <div className="min-h-screen bg-background relative flex flex-col">
      {/* Ambient glow */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-1/4 left-1/2 -translate-x-1/2 w-[400px] h-[300px] bg-accent/[0.02] rounded-full blur-3xl" />
      </div>

      <Header />

      <main className="relative pt-32 sm:pt-36 pb-20 px-4 sm:px-6 flex-1 flex items-center justify-center">
        <div className="w-full max-w-md">
          {/* Back link */}
          <Link
            href="/"
            className="inline-flex items-center gap-2 text-body-sm text-foreground-muted hover:text-foreground transition-colors mb-8"
          >
            <ArrowLeft className="w-4 h-4" />
            Back to Home
          </Link>

          <div className="p-8 bg-background-secondary/50 border border-border rounded-2xl animate-fade-in">
            {/* Icon */}
            <div className="w-16 h-16 bg-background-tertiary rounded-2xl flex items-center justify-center mx-auto mb-6">
              <Mail className="w-8 h-8 text-foreground-muted" />
            </div>

            {status === 'success' ? (
              <div className="text-center">
                <div className="w-12 h-12 bg-accent/20 rounded-full flex items-center justify-center mx-auto mb-4">
                  <CheckCircle className="w-6 h-6 text-accent" />
                </div>
                <h1 className="text-heading-sm font-medium text-foreground mb-2">Unsubscribed</h1>
                <p className="text-body text-foreground-muted mb-6">{message}</p>
                <p className="text-body-sm text-foreground-subtle">
                  Changed your mind?{' '}
                  <Link href="/blog" className="text-accent hover:text-accent-hover">
                    Subscribe again
                  </Link>
                </p>
              </div>
            ) : (
              <>
                <div className="text-center mb-8">
                  <h1 className="text-heading-sm font-medium text-foreground mb-2">Unsubscribe</h1>
                  <p className="text-body text-foreground-muted">
                    Enter your email to unsubscribe from our newsletter.
                  </p>
                </div>

                <form onSubmit={handleUnsubscribe} className="space-y-4">
                  {status === 'error' && message && (
                    <div className="p-4 bg-danger-muted border border-danger/20 rounded-xl flex items-center gap-3">
                      <AlertCircle className="w-5 h-5 text-danger shrink-0" />
                      <p className="text-body-sm text-danger">{message}</p>
                    </div>
                  )}

                  <div>
                    <label className="block text-ui-sm text-foreground-muted mb-2">Email Address</label>
                    <input
                      type="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      placeholder="you@example.com"
                      required
                      className="w-full px-4 py-3 bg-background border border-border rounded-xl text-body text-foreground
                                 placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent transition-all"
                    />
                  </div>

                  <button
                    type="submit"
                    disabled={status === 'loading'}
                    className="w-full py-3.5 bg-foreground text-background text-ui font-medium rounded-xl
                               hover:bg-foreground/90 disabled:opacity-50 transition-all flex items-center justify-center gap-2"
                  >
                    {status === 'loading' ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      'Unsubscribe'
                    )}
                  </button>
                </form>

                <p className="mt-6 text-center text-body-xs text-foreground-subtle">
                  You will no longer receive marketing emails from pounce.
                  <br />
                  Transactional emails (like alerts) are not affected.
                </p>
              </>
            )}
          </div>
        </div>
      </main>

      <Footer />
    </div>
  )
}

