'use client';

/**
 * Register Page Component
 */

import { useState, useEffect } from 'react';
import { PasswordStrengthIndicator } from '@zen/core/shared/components';

export default function RegisterPage({ onSubmit, onNavigate, currentUser = null }) {
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [success, setSuccess] = useState('');
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    password: '',
    confirmPassword: ''
  });
  const [honeypot, setHoneypot] = useState('');
  const [formLoadedAt, setFormLoadedAt] = useState(0);

  useEffect(() => {
    setFormLoadedAt(Date.now());
  }, []);

  // Validation functions
  const validateEmail = (email) => {
    const errors = [];
    
    if (email.length > 254) {
      errors.push('L\'e-mail doit contenir 254 caractères ou moins');
    }
    
    return errors;
  };

  const validatePassword = (password) => {
    const errors = [];
    
    if (password.length < 8) {
      errors.push('Le mot de passe doit contenir au moins 8 caractères');
    }
    
    if (password.length > 128) {
      errors.push('Le mot de passe doit contenir 128 caractères ou moins');
    }
    
    if (!/[A-Z]/.test(password)) {
      errors.push('Le mot de passe doit contenir au moins une majuscule');
    }
    
    if (!/[a-z]/.test(password)) {
      errors.push('Le mot de passe doit contenir au moins une minuscule');
    }
    
    if (!/\d/.test(password)) {
      errors.push('Le mot de passe doit contenir au moins un chiffre');
    }
    
    return errors;
  };

  const validateName = (name) => {
    const errors = [];
    
    if (name.trim().length === 0) {
      errors.push('Le nom ne peut pas être vide');
    }
    
    if (name.length > 100) {
      errors.push('Le nom doit contenir 100 caractères ou moins');
    }
    
    return errors;
  };

  const isFormValid = () => {
    const emailErrors = validateEmail(formData.email);
    const passwordErrors = validatePassword(formData.password);
    const nameErrors = validateName(formData.name);
    
    return emailErrors.length === 0 &&
           passwordErrors.length === 0 && 
           nameErrors.length === 0 && 
           formData.password === formData.confirmPassword &&
           formData.email.trim().length > 0;
  };

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

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setSuccess('');
    setIsLoading(true);

    // Frontend validation
    const emailErrors = validateEmail(formData.email);
    const passwordErrors = validatePassword(formData.password);
    const nameErrors = validateName(formData.name);
    
    if (emailErrors.length > 0) {
      setError(emailErrors[0]); // Show first error
      setIsLoading(false);
      return;
    }
    
    if (passwordErrors.length > 0) {
      setError(passwordErrors[0]); // Show first error
      setIsLoading(false);
      return;
    }
    
    if (nameErrors.length > 0) {
      setError(nameErrors[0]); // Show first error
      setIsLoading(false);
      return;
    }

    // Validate password match
    if (formData.password !== formData.confirmPassword) {
      setError('Les mots de passe ne correspondent pas');
      setIsLoading(false);
      return;
    }

    const submitData = new FormData();
    submitData.append('name', formData.name);
    submitData.append('email', formData.email);
    submitData.append('password', formData.password);
    submitData.append('confirmPassword', formData.confirmPassword);
    submitData.append('_hp', honeypot);
    submitData.append('_t', String(formLoadedAt));

    try {
      const result = await onSubmit(submitData);
      
      if (result.success) {
        setSuccess(result.message);
        setIsLoading(false);
      } else {
        setError(result.error || 'Échec de l\'inscription');
        setIsLoading(false);
      }
    } catch (err) {
      console.error('Registration error:', err);
      setError('Une erreur inattendue s\'est produite');
      setIsLoading(false);
    }
  }

  const inputClasses = 'w-full px-3 py-2.5 rounded-lg text-sm focus:outline-none transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed bg-white border border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-1 focus:ring-neutral-500/20 dark:bg-neutral-900 dark:border-neutral-700/50 dark:text-white dark:placeholder-neutral-500 dark:focus:border-neutral-600 dark:focus:ring-neutral-600/20';

  return (
      <div className="bg-white/80 dark:bg-neutral-900/40 backdrop-blur-sm border border-neutral-200/80 dark:border-neutral-800/50 rounded-2xl px-4 py-6 md:px-6 md:py-8 hover:bg-neutral-50/90 hover:border-neutral-300/80 dark:hover:bg-neutral-900/50 dark:hover:border-neutral-700/50 transition-all duration-300 w-full max-w-md">
        {/* Header */}
        <div className="text-center mb-6">
          <h1 className="text-2xl font-bold text-neutral-900 dark:text-white mb-2">
            Créer un compte
          </h1>
          <p className="text-sm text-neutral-600 dark:text-neutral-400">
            Inscrivez-vous pour commencer.
          </p>
        </div>

        {/* Already Connected Message */}
        {currentUser && (
          <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg dark:bg-blue-500/10 dark:border-blue-500/20">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <div className="w-1.5 h-1.5 bg-blue-500 rounded-full flex-shrink-0"></div>
                <span className="text-xs text-blue-700 dark:text-blue-400">
                  Vous êtes connecté en tant que <span className="font-medium">{currentUser.name}</span>.{' '}
                  <a
                    href="/auth/logout"
                    className="underline hover:text-blue-600 dark:hover:text-blue-300 transition-colors duration-200"
                  >
                    Se déconnecter ?
                  </a>
                </span>
              </div>
            </div>
          </div>
        )}

        {/* Error Message */}
        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg dark:bg-red-500/10 dark:border-red-500/20">
            <div className="flex items-center space-x-2">
              <div className="w-1.5 h-1.5 bg-red-500 rounded-full flex-shrink-0"></div>
              <span className="text-xs text-red-700 dark:text-red-400">{error}</span>
            </div>
          </div>
        )}

        {/* Success Message */}
        {success && (
          <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg dark:bg-green-500/10 dark:border-green-500/20">
            <div className="flex items-center space-x-2">
              <div className="w-1.5 h-1.5 bg-green-500 rounded-full flex-shrink-0"></div>
              <span className="text-xs text-green-700 dark:text-green-400">{success}</span>
            </div>
          </div>
        )}

        {/* Registration Form */}
        <form onSubmit={handleSubmit} className={`flex flex-col gap-4 transition-opacity duration-200 ${currentUser ? 'opacity-50 pointer-events-none' : ''}`}>
          {/* Honeypot — invisible to humans, filled by bots */}
          <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', top: '-9999px', width: 0, height: 0, overflow: 'hidden' }}>
            <label htmlFor="_hp_register">Website</label>
            <input id="_hp_register" name="_hp" type="text" tabIndex={-1} autoComplete="off" value={honeypot} onChange={(e) => setHoneypot(e.target.value)} />
          </div>
          <div>
            <label htmlFor="name" className="block text-xs font-medium text-neutral-700 dark:text-white mb-1.5">
              Nom complet
            </label>
            <input
              id="name"
              name="name"
              type="text"
              required
              maxLength="100"
              value={formData.name}
              onChange={handleChange}
              disabled={success || currentUser}
              className={inputClasses}
              placeholder="John Doe"
              autoComplete="name"
            />
          </div>

          <div>
            <label htmlFor="email" className="block text-xs font-medium text-neutral-700 dark:text-white mb-1.5">
              E-mail
            </label>
            <input
              id="email"
              name="email"
              type="email"
              required
              maxLength="254"
              value={formData.email}
              onChange={handleChange}
              disabled={success || currentUser}
              className={inputClasses}
              placeholder="your@email.com"
              autoComplete="email"
            />
          </div>

          <div>
            <label htmlFor="password" className="block text-xs font-medium text-neutral-700 dark:text-white mb-1.5">
              Mot de passe
            </label>
            <input
              id="password"
              name="password"
              type="password"
              required
              minLength="8"
              maxLength="128"
              value={formData.password}
              onChange={handleChange}
              disabled={success || currentUser}
              className={inputClasses}
              placeholder="••••••••"
              autoComplete="new-password"
            />
            <PasswordStrengthIndicator password={formData.password} showRequirements={true} />
          </div>

          <div>
            <label htmlFor="confirmPassword" className="block text-xs font-medium text-neutral-700 dark:text-white mb-1.5">
              Confirmer le mot de passe
            </label>
            <input
              id="confirmPassword"
              name="confirmPassword"
              type="password"
              required
              minLength="8"
              maxLength="128"
              value={formData.confirmPassword}
              onChange={handleChange}
              disabled={success || currentUser}
              className={inputClasses}
              placeholder="••••••••"
              autoComplete="new-password"
            />
          </div>

          <button
            type="submit"
            disabled={isLoading || success || currentUser || !isFormValid()}
            className="cursor-pointer w-full bg-neutral-900 text-white mt-2 py-2.5 px-4 rounded-lg text-sm font-medium hover:bg-neutral-800 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 focus:outline-none focus:ring-1 focus:ring-neutral-900/20 dark:bg-white dark:text-black dark:hover:bg-neutral-100 dark:focus:ring-white/20"
          >
            {isLoading ? (
              <div className="flex items-center justify-center space-x-2">
                <div className="w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin dark:border-black/20 dark:border-t-black"></div>
                <span>Création du compte en cours...</span>
              </div>
            ) : (
              'Créer un compte'
            )}
          </button>
        </form>

        {/* Login Link */}
        <div className={`mt-6 text-center transition-opacity duration-200 ${currentUser ? 'opacity-50 pointer-events-none' : ''}`}>
          
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              if (!currentUser) {
                onNavigate('login');
              }
            }}
            className="group flex items-center justify-center gap-2"
          >
            <span className="text-sm text-neutral-600 dark:text-neutral-400">Vous avez déjà un compte ? </span>
            <span className="text-sm text-neutral-900 group-hover:text-neutral-600 font-medium transition-colors duration-200 dark:text-white dark:group-hover:text-neutral-300">Se connecter</span>
          </a>
        </div>
      </div>
  );
}



