import { useState, useEffect } from "react"
import { useAuth } from "../context/AuthContext"
import { useNavigate, useSearchParams } from "react-router-dom"

export default function VerifyEmail() {
  const { verifyEmail } = useAuth()
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  
  const [email, setEmail] = useState("")
  const [code, setCode] = useState("")
  const [error, setError] = useState("")
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    const emailParam = searchParams.get("email")
    if (emailParam) {
      setEmail(emailParam)
    }
  }, [searchParams])

  async function handleSubmit(e) {
    e.preventDefault()
    setError("")
    setLoading(true)

    if (code.length !== 6) {
      setError("Please enter a valid 6-digit verification code.")
      setLoading(false)
      return
    }

    try {
      await verifyEmail(email, code)
      navigate("/login", { 
        state: { success: "Email verified successfully! You can now sign in." } 
      })
    } catch (err) {
      setError(err.response?.data?.detail || "Verification failed. Please check the code.")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="page-container">
      <div className="glass-card">
        <h2>Verify Email</h2>
        <p className="card-subtitle">
          We sent a 6-digit verification code. Please check your email inbox (or FastAPI terminal logs).
        </p>

        {error && <div className="alert alert-error">{error}</div>}

        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label htmlFor="verify-email">Email Address</label>
            <input
              id="verify-email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="name@example.com"
              required
            />
          </div>

          <div className="form-group">
            <label htmlFor="otp-code">Verification Code</label>
            <input
              id="otp-code"
              type="text"
              maxLength={6}
              value={code}
              onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
              placeholder="Enter 6-digit OTP code"
              style={{ letterSpacing: "4px", textAlign: "center", fontSize: "1.2rem", fontWeight: "700" }}
              required
            />
          </div>

          <button className="btn" type="submit" disabled={loading} style={{ marginTop: "1rem" }}>
            {loading ? "Verifying..." : "Verify & Activate"}
          </button>
        </form>
      </div>
    </div>
  )
}
