'use client'

import { useState, type FormEvent } from 'react'
import { Shield, ArrowLeft, Loader2, CheckCircle2, AlertTriangle } from 'lucide-react'
import { cmsApi } from '../lib/api.js'

export interface ForgotPasswordProps {
  onNavigate: (path: string) => void
}

const fieldClass =
  'w-full rounded-lg border border-border bg-input-background px-3 py-2.5 text-sm text-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none'

export function ForgotPassword({ onNavigate }: ForgotPasswordProps) {
  const [email, setEmail] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [sent, setSent] = useState(false)
  const [error, setError] = useState('')

  const canSubmit = email.trim() && !submitting

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault()
    if (!canSubmit) return

    setError('')
    setSubmitting(true)

    try {
      const result = await cmsApi('/auth/forgot-password', {
        method: 'POST',
        body: JSON.stringify({ email: email.trim() }),
      })

      if (result.error && result.status === 429) {
        setError('Too many requests. Please try again later.')
      } else {
        setSent(true)
      }
    } catch {
      setError('An unexpected error occurred. Please try again.')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="bg-muted flex min-h-screen items-center justify-center px-4">
      <div className="w-full max-w-md">
        <div className="mb-8 text-center">
          <div className="bg-primary mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-xl">
            <Shield className="text-primary-foreground h-7 w-7" />
          </div>
          <h1 className="text-foreground text-2xl font-medium">Reset Password</h1>
          <p className="text-muted-foreground mt-2">
            {sent
              ? 'Check your inbox for a reset link'
              : "Enter your email and we'll send you a reset link"}
          </p>
        </div>

        <div className="border-border bg-card space-y-5 rounded-xl border p-6 shadow-sm">
          {sent ? (
            <div className="space-y-4 text-center">
              <div className="bg-success/10 mx-auto flex h-12 w-12 items-center justify-center rounded-full">
                <CheckCircle2 className="text-success h-6 w-6" />
              </div>
              <p className="text-muted-foreground text-sm">
                If an account exists for <strong>{email}</strong>, you will receive a password reset
                email shortly.
              </p>
              <p className="text-muted-foreground text-xs">
                The link expires in 1 hour. Check your spam folder if you don't see it.
              </p>
              <button
                type="button"
                onClick={() => onNavigate('/login')}
                className="bg-primary text-primary-foreground hover:bg-primary/90 w-full rounded-lg py-2.5 font-medium transition-colors"
              >
                Back to Sign In
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-5">
              {error && (
                <div className="border-destructive/30 bg-destructive/10 flex items-start gap-3 rounded-lg border p-3">
                  <AlertTriangle className="text-destructive mt-0.5 h-5 w-5 shrink-0" />
                  <p className="text-destructive text-sm">{error}</p>
                </div>
              )}

              <div>
                <label
                  htmlFor="forgot-email"
                  className="text-foreground mb-1.5 block text-sm font-medium"
                >
                  Email Address
                </label>
                <input
                  id="forgot-email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="admin@example.com"
                  className={fieldClass}
                  required
                  autoFocus
                  autoComplete="email"
                />
              </div>

              <button
                type="submit"
                disabled={!canSubmit}
                className="bg-primary text-primary-foreground hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg py-2.5 font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
              >
                {submitting ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Sending...
                  </>
                ) : (
                  'Send Reset Link'
                )}
              </button>
            </form>
          )}

          {!sent && (
            <button
              type="button"
              onClick={() => onNavigate('/login')}
              className="text-muted-foreground hover:text-foreground flex w-full items-center justify-center gap-2 text-sm transition-colors"
            >
              <ArrowLeft className="h-4 w-4" />
              Back to Sign In
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
