'use client';

import { useState, useEffect } from 'react';
import { MAX_EMAIL_LENGTH } from '@/lib/password-validation';

/**
 * Forgot Password Form
 *
 * Client component that handles the password reset request flow.
 * Shows success state with email sent confirmation and resend cooldown.
 */
export default function ForgotPasswordForm() {
  const [email, setEmail] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [submittedEmail, setSubmittedEmail] = useState('');
  const [resendCooldown, setResendCooldown] = useState(0);

  // Countdown timer for resend cooldown
  useEffect(() => {
    if (resendCooldown <= 0) return;
    const timer = setInterval(() => {
      setResendCooldown((prev) => Math.max(0, prev - 1));
    }, 1000);
    return () => clearInterval(timer);
  }, [resendCooldown]);

  const validateEmail = (email: string): string | null => {
    if (!email) {
      return 'Email is required';
    }
    if (email.length > MAX_EMAIL_LENGTH) {
      return 'Email address is too long';
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return 'Please enter a valid email address';
    }
    return null;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const emailError = validateEmail(email);
    if (emailError) {
      setError(emailError);
      return;
    }

    setIsLoading(true);
    setError('');

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

      const data = await response.json();

      if (response.status === 429 && data.error) {
        // Rate limited
        const match = data.error.match(/wait (\d+) seconds/);
        if (match) {
          setResendCooldown(parseInt(match[1]));
        } else {
          setError(data.error);
        }
        setIsLoading(false);
        return;
      }

      if (!response.ok && response.status !== 429) {
        setError(data.error || 'Failed to send reset email. Please try again.');
        setIsLoading(false);
        return;
      }

      // Success - show confirmation
      setIsSubmitted(true);
      setSubmittedEmail(email);
      setResendCooldown(60);
    } catch {
      setError('An unexpected error occurred. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleResend = async () => {
    if (resendCooldown > 0 || isLoading) return;

    setIsLoading(true);
    setError('');

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

      const data = await response.json();

      if (response.status === 429 && data.error) {
        const match = data.error.match(/wait (\d+) seconds/);
        if (match) {
          setResendCooldown(parseInt(match[1]));
        } else {
          setError(data.error);
        }
      } else if (response.ok) {
        setResendCooldown(60);
      } else {
        setError(data.error || 'Failed to resend email. Please try again.');
      }
    } catch {
      setError('Failed to resend email. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };

  const resetForm = () => {
    setIsSubmitted(false);
    setSubmittedEmail('');
    setEmail('');
    setError('');
    setResendCooldown(0);
  };

  // Show success state after submission
  if (isSubmitted) {
    return (
      <div className="space-y-4">
        {/* Success indicator */}
        <div className="flex justify-center mb-4">
          <div
            className="w-16 h-16 rounded-full flex items-center justify-center"
            style={{ backgroundColor: 'rgba(34, 197, 94, 0.1)' }}
          >
            <svg className="w-8 h-8" fill="none" stroke="#22c55e" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
              />
            </svg>
          </div>
        </div>

        <div className="p-4 bg-green-500/10 border border-green-500/20 rounded-lg">
          <h3 className="text-lg font-semibold mb-2" style={{ color: 'var(--reg-text-white)' }}>
            Check Your Email
          </h3>
          <p style={{ color: 'var(--reg-text-muted)' }}>
            If an account exists with{' '}
            <strong style={{ color: 'var(--reg-text-white)' }}>{submittedEmail}</strong>, you will
            receive a password reset link.
          </p>
        </div>

        {/* Error display */}
        {error && (
          <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
            <p className="text-red-400 text-sm">{error}</p>
          </div>
        )}

        {/* Resend button */}
        <p className="text-sm" style={{ color: 'var(--reg-text-muted)' }}>
          {"Didn't receive the email? "}
          <button
            type="button"
            onClick={handleResend}
            disabled={resendCooldown > 0 || isLoading}
            className="underline hover:no-underline disabled:opacity-50 disabled:cursor-not-allowed"
            style={{ color: '#38bdf8' }}
          >
            {isLoading
              ? 'Sending...'
              : resendCooldown > 0
                ? `Resend in ${resendCooldown}s`
                : 'Resend reset email'}
          </button>
        </p>

        {/* Use different email */}
        <button
          type="button"
          onClick={resetForm}
          className="text-sm underline hover:no-underline transition-all"
          style={{ color: 'var(--reg-text-muted)' }}
        >
          Use a different email
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4 text-left">
      {/* Error Message */}
      {error && (
        <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
          <p className="text-red-400 text-sm">{error}</p>
        </div>
      )}

      {/* Email Field */}
      <div className="space-y-1">
        <label
          htmlFor="forgot-password-email"
          className="block text-sm font-medium"
          style={{ color: 'var(--reg-text-white)' }}
        >
          Email Address
        </label>
        <input
          id="forgot-password-email"
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className="w-full h-11 px-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-white/40 focus:ring-1 focus:ring-white/40 transition-colors"
          placeholder="you@example.com"
          disabled={isLoading}
          autoComplete="email"
          autoFocus
        />
      </div>

      {/* Submit Button */}
      <button
        type="submit"
        disabled={isLoading}
        className="w-full py-4 rounded-xl font-bold uppercase tracking-tight transition-all disabled:opacity-50 disabled:cursor-not-allowed"
        style={{
          backgroundColor: 'var(--reg-accent-cyan)',
          color: 'var(--reg-bg-navy)',
        }}
      >
        {isLoading ? 'Sending...' : 'Send Reset Link'}
      </button>
    </form>
  );
}
