import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import LanguageSwitcher from './components/LanguageSwitcher';
import SiteFooter from './components/SiteFooter';
import { authAPI } from './services/api';

function ForgotPassword() {
  const { t } = useTranslation();
  const navigate = useNavigate();

  const [step, setStep] = useState(1); // 1: request, 2: reset
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmNewPassword, setConfirmNewPassword] = useState('');
  const [isCodeSent, setIsCodeSent] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState({});

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  const passwordMeetsComplexity = (pwd) => /[A-Z]/.test(pwd) && /[a-z]/.test(pwd) && /[0-9]/.test(pwd) && pwd.length >= 8;

  const handleSendCode = async () => {
    const err = {};
    if (!email) err.email = t('registration.form.required');
    else if (!emailRegex.test(email)) err.email = t('registration.form.emailInvalid');
    setErrors(err);
    if (Object.keys(err).length > 0) return;

    try {
      await authAPI.sendResetCode(email);
      setIsCodeSent(true);
      alert('Verification code sent to your email.');
    } catch (error) {
      const errorMessage = error.response?.data?.message || 'Failed to send verification code. Please try again.';
      alert(errorMessage);
    }
  };

  const handleNext = () => {
    const err = {};
    if (!email) err.email = t('registration.form.required');
    else if (!emailRegex.test(email)) err.email = t('registration.form.emailInvalid');
    if (!isCodeSent) err.general = t('registration.verification.codeSent');
    setErrors(err);
    if (Object.keys(err).length > 0) return;
    setStep(2);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const err = {};
    if (!code) err.code = t('registration.form.codeRequired');
    else if (!/^\d{6}$/.test(code)) err.code = t('registration.form.codeRequired');
    if (!newPassword) err.newPassword = t('registration.form.required');
    else if (!passwordMeetsComplexity(newPassword)) err.newPassword = t('registration.form.passwordComplexity');
    if (!confirmNewPassword) err.confirmNewPassword = t('registration.form.required');
    else if (confirmNewPassword !== newPassword) err.confirmNewPassword = t('registration.form.passwordMismatch');
    setErrors(err);
    if (Object.keys(err).length > 0) return;

    setIsSubmitting(true);
    try {
      await authAPI.resetPassword({
        email,
        code,
        newPassword
      });
      alert('Password reset successfully.');
      navigate('/login');
    } catch (error) {
      const errorMessage = error.response?.data?.message || 'Password reset failed. Please try again.';
      alert(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="registration-container">
      <header className="registration-header">
        <div className="container">
          <div className="header-content">
            <Link to="/" className="logo"><h2>{t('home.title')}</h2></Link>
            <div className="header-actions">
              <LanguageSwitcher />
              <Link to="/login" className="btn-secondary">{t('login.title')}</Link>
            </div>
          </div>
        </div>
      </header>

      <main className="registration-main">
        <div className="container">
          <div className="registration-card">
            <form className="registration-form" onSubmit={handleSubmit}>
              <div className="step-content">
                <h2>{step === 1 ? t('login.form.forgotPassword') : t('common.update')}</h2>
                {step === 1 ? (
                  <p>{t('registration.form.descriptions.verification')}</p>
                ) : (
                  <p>{t('settings.updateLoginPassword.title')}</p>
                )}

                {step === 1 && (
                  <>
                    <div className="form-group">
                      <label htmlFor="fp-email">{t('registration.form.verificationEmail')} *</label>
                      <div style={{ display: 'flex', gap: '0.5rem' }}>
                        <input
                          type="email"
                          id="fp-email"
                          name="fp-email"
                          value={email}
                          onChange={(e) => setEmail(e.target.value)}
                          className={errors.email ? 'error' : ''}
                          placeholder={t('registration.form.placeholders.verificationEmail')}
                        />
                        <button type="button" className="btn-outline" onClick={handleSendCode}>{t('common.sendCode')}</button>
                      </div>
                      {errors.email && <span className="error-message">{errors.email}</span>}
                      {isCodeSent && <span style={{ color: '#718096', fontSize: '0.85rem', display: 'block', marginTop: '0.25rem' }}>{t('registration.verification.codeSent')}</span>}
                    </div>

                    <div className="form-group">
                      <label htmlFor="fp-code">{t('registration.form.verificationCode')} *</label>
                      <input
                        type="text"
                        id="fp-code"
                        name="fp-code"
                        value={code}
                        onChange={(e) => setCode(e.target.value)}
                        className={errors.code ? 'error' : ''}
                        placeholder={t('registration.form.placeholders.verificationCode')}
                        maxLength={6}
                      />
                      {errors.code && <span className="error-message">{errors.code}</span>}
                    </div>

                    {errors.general && <span className="error-message">{errors.general}</span>}

                    <div className="form-navigation">
                      <div className="nav-buttons">
                        <div className="nav-spacer"></div>
                        <button type="button" className="btn-primary" onClick={handleNext}>{t('registration.nextStep')}</button>
                      </div>
                    </div>
                  </>
                )}

                {step === 2 && (
                  <>
                    <div className="form-row">
                      <div className="form-group">
                        <label htmlFor="fp-new">{t('settings.updateLoginPassword.newPassword')}</label>
                        <input
                          type="password"
                          id="fp-new"
                          name="fp-new"
                          value={newPassword}
                          onChange={(e) => setNewPassword(e.target.value)}
                          className={errors.newPassword ? 'error' : ''}
                          placeholder={t('settings.updateLoginPassword.newPassword')}
                        />
                        {errors.newPassword && <span className="error-message">{errors.newPassword}</span>}
                      </div>
                      <div className="form-group">
                        <label htmlFor="fp-confirm">{t('settings.updateLoginPassword.confirmPassword')}</label>
                        <input
                          type="password"
                          id="fp-confirm"
                          name="fp-confirm"
                          value={confirmNewPassword}
                          onChange={(e) => setConfirmNewPassword(e.target.value)}
                          className={errors.confirmNewPassword ? 'error' : ''}
                          placeholder={t('settings.updateLoginPassword.confirmPassword')}
                        />
                        {errors.confirmNewPassword && <span className="error-message">{errors.confirmNewPassword}</span>}
                      </div>
                    </div>

                    <div className="form-navigation">
                      <div className="nav-buttons">
                        <button type="button" className="btn-outline" onClick={() => setStep(1)}>{t('common.previous')}</button>
                        <div className="nav-spacer"></div>
                        <button type="submit" className="btn-primary" disabled={isSubmitting}>{isSubmitting ? t('common.loading') : t('common.update')}</button>
                      </div>
                    </div>
                  </>
                )}
              </div>
            </form>
          </div>
        </div>
      </main>

      <SiteFooter />
    </div>
  );
}

export default ForgotPassword;
