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

function Registration() {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [formData, setFormData] = useState({
    // Business Information (trimmed)
    businessName: '',
    domainName: '',

    // Login Details
    loginId: '',
    loginPassword: '',
    confirmLoginPassword: '',

    // Verification
    verificationEmail: '',
    verificationCode: '',

    // Agreement
    agreeToTerms: false,
    agreeToPrivacy: false
  });

  const [currentStep, setCurrentStep] = useState(1);
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isCodeSent, setIsCodeSent] = useState(false);

  // Back to 4 steps with Verification
  const totalSteps = 4;

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }));

    if (errors[name]) {
      setErrors((prev) => ({ ...prev, [name]: '' }));
    }
  };

  const passwordMeetsComplexity = (pwd) => {
    if (!pwd) return false;
    const hasUpper = /[A-Z]/.test(pwd);
    const hasLower = /[a-z]/.test(pwd);
    const hasNumber = /[0-9]/.test(pwd);
    const hasLen = pwd.length >= 8;
    return hasUpper && hasLower && hasNumber && hasLen;
  };

  const validateStep = (step) => {
    const newErrors = {};

    switch (step) {
      case 1: // Business Information
        if (!formData.businessName) newErrors.businessName = t('registration.form.required');
        if (formData.domainName) {
          const domainRegex = /^(?!-)([A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,}$/;
          if (!domainRegex.test(formData.domainName)) newErrors.domainName = t('registration.form.domainInvalid');
        }
        break;

      case 2: // Login Details
        if (!formData.loginId) newErrors.loginId = t('registration.form.required');
        if (!formData.loginPassword) newErrors.loginPassword = t('registration.form.required');
        else if (!passwordMeetsComplexity(formData.loginPassword)) newErrors.loginPassword = t('registration.form.passwordComplexity');
        if (!formData.confirmLoginPassword) newErrors.confirmLoginPassword = t('registration.form.required');
        else if (formData.confirmLoginPassword !== formData.loginPassword) newErrors.confirmLoginPassword = t('registration.form.passwordMismatch');
        break;

      case 3: // Verification
        if (!formData.verificationEmail) newErrors.verificationEmail = t('registration.form.required');
        else {
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
          if (!emailRegex.test(formData.verificationEmail)) newErrors.verificationEmail = t('registration.form.emailInvalid');
        }
        if (!formData.verificationCode) newErrors.verificationCode = t('registration.form.codeRequired');
        else if (!/^\d{6}$/.test(formData.verificationCode)) newErrors.verificationCode = t('registration.form.codeRequired');
        break;

      case 4: // Agreement
        if (!formData.agreeToTerms) newErrors.agreeToTerms = t('registration.form.required');
        if (!formData.agreeToPrivacy) newErrors.agreeToPrivacy = t('registration.form.required');
        break;
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleNext = () => {
    if (validateStep(currentStep)) {
      setCurrentStep((prev) => Math.min(prev + 1, totalSteps));
    }
  };

  const handlePrevious = () => {
    setCurrentStep((prev) => Math.max(prev - 1, 1));
  };

  const handleSendCode = async () => {
    if (!formData.verificationEmail) {
      setErrors((prev) => ({ ...prev, verificationEmail: t('registration.form.required') }));
      return;
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.verificationEmail)) {
      setErrors((prev) => ({ ...prev, verificationEmail: t('registration.form.emailInvalid') }));
      return;
    }
    
    try {
      await authAPI.verifyEmail({
        type: 'Register',
        email: formData.verificationEmail
      });
      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 handleSubmit = async (e) => {
    e.preventDefault();
    if (!validateStep(currentStep)) return;

    setIsSubmitting(true);
    try {
      const response = await authAPI.register(formData);
      console.log('Registration successful:', response.data);
      alert('Registration successful! You will receive an email with your API credentials shortly.');
      navigate('/dashboard');
    } catch (error) {
      console.error('Registration error:', error);
      const errorMessage = error.response?.data?.message || 'Registration failed. Please try again.';
      alert(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="step-content">
            <h2>{t('registration.steps.businessInfo')}</h2>
            <p>{t('registration.form.descriptions.businessInfo')}</p>

            <div className="form-row">
              <div className="form-group">
                <label htmlFor="businessName">{t('registration.form.businessName')} *</label>
                <input
                  type="text"
                  id="businessName"
                  name="businessName"
                  value={formData.businessName}
                  onChange={handleInputChange}
                  className={errors.businessName ? 'error' : ''}
                  placeholder={t('registration.form.placeholders.businessName')}
                />
                {errors.businessName && <span className="error-message">{errors.businessName}</span>}
              </div>

              <div className="form-group">
                <label htmlFor="domainName">{t('registration.form.domainName')}</label>
                <input
                  type="text"
                  id="domainName"
                  name="domainName"
                  value={formData.domainName}
                  onChange={handleInputChange}
                  placeholder={t('registration.form.placeholders.domainName')}
                />
                {errors.domainName && <span className="error-message">{errors.domainName}</span>}
              </div>
            </div>
          </div>
        );

      case 2:
        return (
          <div className="step-content">
            <h2>{t('registration.steps.loginDetails')}</h2>
            <p>{t('registration.form.descriptions.loginDetails')}</p>

            <div className="form-group">
              <label htmlFor="loginId">{t('registration.form.loginId')} *</label>
              <input
                type="text"
                id="loginId"
                name="loginId"
                value={formData.loginId}
                onChange={handleInputChange}
                className={errors.loginId ? 'error' : ''}
                placeholder={t('registration.form.placeholders.loginId')}
              />
              {errors.loginId && <span className="error-message">{errors.loginId}</span>}
            </div>

            <div className="form-row">
              <div className="form-group" style={{ position: 'relative' }}>
                <label htmlFor="loginPassword">{t('registration.form.loginPassword')} *</label>
                <input
                  type="password"
                  id="loginPassword"
                  name="loginPassword"
                  value={formData.loginPassword}
                  onChange={handleInputChange}
                  className={errors.loginPassword ? 'error' : ''}
                  placeholder={t('registration.form.placeholders.loginPassword')}
                />
                {errors.loginPassword && <span className="error-message">{errors.loginPassword}</span>}
                {!errors.loginPassword && formData.loginPassword && (
                  <span style={{ color: '#718096', fontSize: '0.85rem', display: 'block', marginTop: '0.25rem' }}>
                    {t('registration.form.passwordHint')}
                  </span>
                )}
              </div>

              <div className="form-group" style={{ position: 'relative' }}>
                <label htmlFor="confirmLoginPassword">{t('registration.form.confirmLoginPassword')} *</label>
                <input
                  type="password"
                  id="confirmLoginPassword"
                  name="confirmLoginPassword"
                  value={formData.confirmLoginPassword}
                  onChange={handleInputChange}
                  className={errors.confirmLoginPassword ? 'error' : ''}
                  placeholder={t('registration.form.placeholders.confirmLoginPassword')}
                />
                {errors.confirmLoginPassword && <span className="error-message">{errors.confirmLoginPassword}</span>}
              </div>
            </div>
          </div>
        );

      case 3:
        return (
          <div className="step-content">
            <h2>{t('registration.steps.verification')}</h2>
            <p>{t('registration.form.descriptions.verification')}</p>

            <div className="form-group">
              <label htmlFor="verificationEmail">{t('registration.form.verificationEmail')} *</label>
              <div style={{ display: 'flex', gap: '0.5rem' }}>
                <input
                  type="email"
                  id="verificationEmail"
                  name="verificationEmail"
                  value={formData.verificationEmail}
                  onChange={handleInputChange}
                  className={errors.verificationEmail ? 'error' : ''}
                  placeholder={t('registration.form.placeholders.verificationEmail')}
                />
                <button type="button" className="btn-outline" onClick={handleSendCode}>{t('common.sendCode')}</button>
              </div>
              {errors.verificationEmail && <span className="error-message">{errors.verificationEmail}</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="verificationCode">{t('registration.form.verificationCode')} *</label>
              <input
                type="text"
                id="verificationCode"
                name="verificationCode"
                value={formData.verificationCode}
                onChange={handleInputChange}
                className={errors.verificationCode ? 'error' : ''}
                placeholder={t('registration.form.placeholders.verificationCode')}
                maxLength={6}
              />
              {errors.verificationCode && <span className="error-message">{errors.verificationCode}</span>}
            </div>
          </div>
        );

      case 4:
        return (
          <div className="step-content">
            <h2>{t('registration.steps.agreement')}</h2>
            <p>{t('registration.form.descriptions.agreement')}</p>

            <div className="legal-checkboxes">
              <div className="checkbox-group">
                <label className="checkbox-label">
                  <input
                    type="checkbox"
                    name="agreeToTerms"
                    checked={formData.agreeToTerms}
                    onChange={handleInputChange}
                    className={errors.agreeToTerms ? 'error' : ''}
                  />
                  <span className="checkmark"></span>
                  {t('registration.form.agreeTos')} *
                </label>
                {errors.agreeToTerms && <span className="error-message">{errors.agreeToTerms}</span>}
              </div>

              <div className="checkbox-group">
                <label className="checkbox-label">
                  <input
                    type="checkbox"
                    name="agreeToPrivacy"
                    checked={formData.agreeToPrivacy}
                    onChange={handleInputChange}
                    className={errors.agreeToPrivacy ? 'error' : ''}
                  />
                  <span className="checkmark"></span>
                  {t('registration.form.agreePrivacy')} *
                </label>
                {errors.agreeToPrivacy && <span className="error-message">{errors.agreeToPrivacy}</span>}
              </div>
            </div>

            <div className="compliance-notice">
              <h4>{t('registration.agreementInfo.title')}</h4>
              <ul>
                <li>{t('registration.agreementInfo.reviewDays')}</li>
                <li>{t('registration.agreementInfo.apiCredentials')}</li>
              </ul>
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="registration-container">
      {/* Header */}
      <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="/api-docs" className="btn-outline">{t('navigation.apiDocs')}</Link>
              <Link to="/" className="btn-secondary">{t('common.backToHome')}</Link>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="registration-main">
        <div className="container">
          <div className="registration-card">
            {/* Progress Bar */}
            <div className="progress-bar">
              <div className="progress-steps">
                {Array.from({ length: totalSteps }, (_, index) => (
                  <div
                    key={index + 1}
                    className={`progress-step ${currentStep > index + 1 ? 'completed' : currentStep === index + 1 ? 'active' : ''}`}
                  >
                    <div className="step-number">{index + 1}</div>
                    <div className="step-label">
                      {index === 0 && t('registration.steps.businessInfo')}
                      {index === 1 && t('registration.steps.loginDetails')}
                      {index === 2 && t('registration.steps.verification')}
                      {index === 3 && t('registration.steps.agreement')}
                    </div>
                  </div>
                ))}
              </div>
              <div className="progress-line">
                <div
                  className="progress-fill"
                  style={{ width: `${((currentStep - 1) / (totalSteps - 1)) * 100}%` }}
                ></div>
              </div>
            </div>

            {/* Form */}
            <form onSubmit={handleSubmit} className="registration-form">
              {renderStepContent()}

              {/* Navigation Buttons */}
              <div className="form-navigation">
                <div className="nav-buttons">
                  {currentStep > 1 && (
                    <button type="button" onClick={handlePrevious} className="btn-outline">
                      {t('common.previous')}
                    </button>
                  )}

                  <div className="nav-spacer"></div>

                  {currentStep < totalSteps ? (
                    <button type="button" onClick={handleNext} className="btn-primary">
                      {t('registration.nextStep')}
                    </button>
                  ) : (
                    <button type="submit" className="btn-primary" disabled={isSubmitting}>
                      {isSubmitting ? 'Submitting...' : t('registration.completeRegistration')}
                    </button>
                  )}
                </div>
              </div>
            </form>
          </div>
        </div>
      </main>

      <SiteFooter />
    </div>
  );
}

export default Registration;
