import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import authService from '../services/authService';
import productService from '../services/productService';
import './Auth.css';

const Auth = ({ onLogin }) => {
  const [isLogin, setIsLogin] = useState(true);
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    confirmPassword: ''
  });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [emailNotVerified, setEmailNotVerified] = useState(false);
  const [showForgotPassword, setShowForgotPassword] = useState(false);
  const navigate = useNavigate();

  const handleInputChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    setEmailNotVerified(false);

    try {
      if (isLogin) {
        const response = await authService.login({
          email: formData.email,
          password: formData.password
        });
        // If backend returned a token (helpful in dev over HTTP), set it in memory
        if (response && response.token) {
          authService.setToken(response.token);
          productService.setToken(response.token);
        }

        // Inform parent to refresh profile and update UI
        onLogin();
        navigate('/');
      } else {
        if (formData.password !== formData.confirmPassword) {
          setError('Passwords do not match');
          setLoading(false);
          return;
        }
        await authService.register({
          firstName: formData.firstName,
          lastName: formData.lastName,
          email: formData.email,
          password: formData.password
        });
        setIsLogin(true);
        setError('Registration successful! Please check your email for verification and then login.');
      }
    } catch (err) {
      const errorMessage = err.response?.data?.message || 'An error occurred';
      setError(errorMessage);
      if (errorMessage === 'Please verify your email before logging in') {
        setEmailNotVerified(true);
      }
    } finally {
      setLoading(false);
    }
  };


  
  const handleResendVerification = async () => {
    setError('');
    setLoading(true);
    try {
      await authService.resendVerificationEmail({ email: formData.email });
      setError('A new verification email has been sent. Please check your inbox.');
    } catch (err) {
      setError(err.response?.data?.message || 'An error occurred while resending the verification email.');
    } finally {
      setLoading(false);
    }
  };

  const handleForgotPasswordSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await authService.forgotPassword(formData.email);
      setError('If an account with that email exists, a password reset link has been sent.');
      setShowForgotPassword(false);
    } catch (err) {
      setError(err.response?.data?.message || 'An error occurred.');
    } finally {
      setLoading(false);
    }
  };

  const toggleMode = () => {
    setIsLogin(!isLogin);
    setError('');
    setFormData({
      firstName: '',
      lastName: '',
      email: '',
      password: '',
      confirmPassword: ''
    });
    setEmailNotVerified(false);
    setShowForgotPassword(false);
  };

  if (showForgotPassword) {
    return (
      <div className="auth-container">
        <div className="auth-card">
          <div className="auth-header">
            <div className="auth-logo">
              <img src="/wraffle_logo.png" alt="Wraffle" className="auth-logo-img" />
            </div>
            <h2>Forgot Password</h2>
          </div>
          <form onSubmit={handleForgotPasswordSubmit} className="auth-form">
            <p>Enter your email address and we'll send you a link to reset your password.</p>
            <div className="form-group">
              <label htmlFor="email">Email</label>
              <input
                type="email"
                id="email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
                required
              />
            </div>
            {error && <div className="error-message">{error}</div>}
            <button type="submit" className="auth-button" disabled={loading}>
              {loading ? 'Sending...' : 'Send Reset Link'}
            </button>
          </form>
          <div className="auth-toggle">
            <p>
              Remember your password?
              <button type="button" onClick={() => setShowForgotPassword(false)} className="toggle-button">
                Login
              </button>
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="auth-container">
      <div className="auth-card">
        <div className="auth-header">
          <div className="auth-logo">
            <img src="/wraffle_logo.png" alt="Wraffle" className="auth-logo-img" />
          </div>
          <h2>{isLogin ? 'Login' : 'Sign Up'}</h2>
        </div>

        <form onSubmit={handleSubmit} className="auth-form">
          {!isLogin && (
            <div className="form-row">
              <div className="form-group">
                <label htmlFor="firstName">First Name</label>
                <input
                  type="text"
                  id="firstName"
                  name="firstName"
                  value={formData.firstName}
                  onChange={handleInputChange}
                  required={!isLogin}
                />
              </div>
              <div className="form-group">
                <label htmlFor="lastName">Last Name</label>
                <input
                  type="text"
                  id="lastName"
                  name="lastName"
                  value={formData.lastName}
                  onChange={handleInputChange}
                  required={!isLogin}
                />
              </div>
            </div>
          )}

          <div className="form-group">
            <label htmlFor="email">Email</label>
            <input
              type="email"
              id="email"
              name="email"
              value={formData.email}
              onChange={handleInputChange}
              required
            />
          </div>

          <div className="form-group">
            <label htmlFor="password">Password</label>
            <input
              type="password"
              id="password"
              name="password"
              value={formData.password}
              onChange={handleInputChange}
              required
            />
            {isLogin && (
              <div className="forgot-password-link">
                <button type="button" onClick={() => setShowForgotPassword(true)} className="toggle-button">
                  Forgot Password?
                </button>
              </div>
            )}
          </div>

          {!isLogin && (
            <div className="form-group">
              <label htmlFor="confirmPassword">Confirm Password</label>
              <input
                type="password"
                id="confirmPassword"
                name="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleInputChange}
                required={!isLogin}
              />
            </div>
          )}

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

          {emailNotVerified && (
            <div className="resend-verification">
              <p>Your email is not verified.</p>
              <button type="button" onClick={handleResendVerification} className="toggle-button" disabled={loading}>
                {loading ? 'Sending...' : 'Resend Verification Link'}
              </button>
            </div>
          )}

          <button type="submit" className="auth-button" disabled={loading}>
            {loading ? 'Please wait...' : (isLogin ? 'Login' : 'Sign Up')}
          </button>
        </form>

        <div className="auth-toggle">
          <p>
            {isLogin ? "Don't have an account?" : 'Already have an account?'}
            <button type="button" onClick={toggleMode} className="toggle-button">
              {isLogin ? 'Sign Up' : 'Login'}
            </button>
          </p>
        </div>
      </div>
    </div>
  );
};

export default Auth;
