import { useState } from 'react'
import Head from 'next/head'
import Link from 'next/link'
import Layout from '@/components/layout'
import { useAuth } from '@/lib/auth/useAuth'

export default function VerifyEmail() {
  const { user, isAuthenticated } = useAuth()
  const [email, setEmail] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError(null)

    const emailToVerify = isAuthenticated ? user?.email : email

    if (!emailToVerify) {
      setError('Email address is required')
      setIsLoading(false)
      return
    }

    try {
      const response = await fetch('/api/auth/verify-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: emailToVerify }),
      })

      const data = await response.json()

      if (!response.ok) {
        setError(data.message || 'An error occurred')
        return
      }

      setSuccess(true)
    } catch (err) {
      setError('An unexpected error occurred')
    } finally {
      setIsLoading(false)
    }
  }

  if (success) {
    return (
      <Layout>
        <Head>
          <title>Verification Email Sent | LocalGreenChain</title>
        </Head>
        <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
          <div className="max-w-md w-full space-y-8 text-center">
            <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-8 rounded-lg">
              <h2 className="text-2xl font-bold mb-2">Check Your Email</h2>
              <p className="mb-4">
                If an account exists with that email address, we've sent you a verification link.
              </p>
              <p className="text-sm text-gray-600">
                Didn't receive the email? Check your spam folder or{' '}
                <button
                  onClick={() => setSuccess(false)}
                  className="text-green-600 hover:text-green-500 underline"
                >
                  try again
                </button>
              </p>
            </div>
            <Link href="/">
              <a className="text-green-600 hover:text-green-500 font-medium">
                Go to homepage
              </a>
            </Link>
          </div>
        </div>
      </Layout>
    )
  }

  return (
    <Layout>
      <Head>
        <title>Verify Email | LocalGreenChain</title>
      </Head>

      <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-md w-full space-y-8">
          <div>
            <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
              Verify your email
            </h2>
            <p className="mt-2 text-center text-sm text-gray-600">
              {isAuthenticated
                ? 'Click the button below to resend a verification email.'
                : 'Enter your email address to receive a verification link.'}
            </p>
          </div>

          {error && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded relative">
              <span className="block sm:inline">{error}</span>
            </div>
          )}

          <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
            {isAuthenticated ? (
              <div className="bg-gray-50 border border-gray-200 px-4 py-3 rounded">
                <p className="text-sm text-gray-600">
                  Logged in as: <span className="font-medium">{user?.email}</span>
                </p>
              </div>
            ) : (
              <div>
                <label htmlFor="email" className="block text-sm font-medium text-gray-700">
                  Email address
                </label>
                <input
                  id="email"
                  name="email"
                  type="email"
                  autoComplete="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="mt-1 appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
                  placeholder="you@example.com"
                />
              </div>
            )}

            <div>
              <button
                type="submit"
                disabled={isLoading}
                className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isLoading ? 'Sending...' : 'Send verification email'}
              </button>
            </div>

            <div className="text-center">
              <Link href="/">
                <a className="text-sm text-green-600 hover:text-green-500">
                  Go to homepage
                </a>
              </Link>
            </div>
          </form>
        </div>
      </div>
    </Layout>
  )
}
