/**
 * Basic Info Step Component
 * First step of registration - collects user basic information
 */

import React from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Input, Checkbox } from '../../ui';
import { PasswordCriteria } from '../../ui/PasswordCriteria';
import { Eye, EyeOff } from 'lucide-react';
import { validateEmail } from '../../../utils/validation';

interface BasicInfoStepProps {
  formData: {
    firstName: string;
    lastName: string;
    email: string;
    password: string;
    confirmPassword: string;
    acceptTerms: boolean;
    marketingConsent: boolean;
    analyticsConsent: boolean;
    firstNameError?: string;
    lastNameError?: string;
    emailError?: string;
    passwordError?: string;
    confirmPasswordError?: string;
  };
  errors: any;
  updateField: (field: string, value: any) => void;
  onNext: () => void;
  isPilot: boolean;
  isSubmitting?: boolean;
  onLoginClick?: () => void;
}

export const BasicInfoStep: React.FC<BasicInfoStepProps> = ({
  formData,
  errors,
  updateField,
  onNext,
  isPilot,
  isSubmitting,
  onLoginClick
}) => {
  const { t } = useTranslation();
  const [showPassword, setShowPassword] = React.useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = React.useState(false);
  
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onNext();
  };

  // Real-time validation for email field
  const validateEmailField = (email: string) => {
    if (!email.trim()) {
      return { isValid: false, error: t('auth:register.email_required', 'Email is required') };
    }
    return validateEmail(email);
  };

  // Real-time validation for password field
  const validatePasswordField = (password: string) => {
    if (!password) {
      return { isValid: false, error: t('auth:register.password_required', 'Password is required') };
    }
    if (password.length < 8) {
      return { isValid: false, error: t('auth:register.password_too_short', 'Password must be at least 8 characters') };
    }
    return { isValid: true, error: '' };
  };

  // Real-time validation for confirm password
  const validateConfirmPassword = (confirmPassword: string) => {
    if (!confirmPassword) {
      return { isValid: false, error: t('auth:register.confirm_password_required', 'Please confirm your password') };
    }
    if (confirmPassword !== formData.password) {
      return { isValid: false, error: t('auth:register.passwords_dont_match', 'Passwords do not match') };
    }
    return { isValid: true, error: '' };
  };

  // Real-time validation for name fields
  const validateNameField = (name: string, fieldName: string) => {
    if (!name.trim()) {
      return { isValid: false, error: t('auth:register.name_required', 'This field is required') };
    }
    if (name.length < 2) {
      return { isValid: false, error: t('auth:register.name_too_short', 'Name must be at least 2 characters') };
    }
    return { isValid: true, error: '' };
  };

  // Calculate password strength
  const calculatePasswordStrength = (password: string) => {
    let strength = 0;
    
    // Length check
    if (password.length >= 12) strength += 2;
    else if (password.length >= 8) strength += 1;
    
    // Character variety checks
    if (/[A-Z]/.test(password)) strength += 1; // Uppercase
    if (/[0-9]/.test(password)) strength += 1; // Numbers
    if (/[^A-Za-z0-9]/.test(password)) strength += 1; // Special chars
    
    // Determine strength level
    if (strength <= 2) return t('auth:register.weak', 'Weak');
    if (strength <= 3) return t('auth:register.medium', 'Medium');
    if (strength <= 4) return t('auth:register.strong', 'Strong');
    return t('auth:register.very_strong', 'Very Strong');
  };

  // Get strength bar color
  const getStrengthColor = (index: number, password: string) => {
    const strength = calculatePasswordStrength(password);
    const strengthValue = 
      strength === t('auth:register.weak', 'Weak') ? 1 :
      strength === t('auth:register.medium', 'Medium') ? 2 :
      strength === t('auth:register.strong', 'Strong') ? 3 : 4;
    
    if (index < strengthValue) {
      if (strengthValue <= 2) return 'bg-red-500';
      if (strengthValue === 3) return 'bg-yellow-500';
      return 'bg-green-500';
    }
    return 'bg-gray-200';
  };
  
  return (
    <div className="basic-info-step w-full max-w-lg mx-auto">
      <h2 className="text-xl sm:text-2xl font-bold mb-4 sm:mb-6 text-[var(--text-primary)] text-center sm:text-left">
        {t('auth:register.basic_info_title', 'Create Your Account')}
      </h2>

      <form onSubmit={handleSubmit} className="space-y-3 sm:space-y-4">
        {/* First Name and Last Name - Stack on mobile, side by side on larger screens */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
          <div>
            <label htmlFor="firstName" className="block text-sm font-medium mb-1 text-[var(--text-primary)]">
              {t('auth:register.first_name', 'First Name')}
            </label>
            <Input
              id="firstName"
              type="text"
              value={formData.firstName}
              onChange={(e) => updateField('firstName', e.target.value)}
              onBlur={() => {
                const validation = validateNameField(formData.firstName, 'firstName');
                if (!validation.isValid) {
                  updateField('firstNameError', validation.error);
                } else {
                  updateField('firstNameError', '');
                }
              }}
              placeholder={t('auth:register.first_name_placeholder', 'John')}
              error={errors.firstName}
              className="w-full"
            />
          </div>

          <div>
            <label htmlFor="lastName" className="block text-sm font-medium mb-1 text-[var(--text-primary)]">
              {t('auth:register.last_name', 'Last Name')}
            </label>
            <Input
              id="lastName"
              type="text"
              value={formData.lastName}
              onChange={(e) => updateField('lastName', e.target.value)}
              onBlur={() => {
                const validation = validateNameField(formData.lastName, 'lastName');
                if (!validation.isValid) {
                  updateField('lastNameError', validation.error);
                } else {
                  updateField('lastNameError', '');
                }
              }}
              placeholder={t('auth:register.last_name_placeholder', 'Doe')}
              error={errors.lastName || formData.lastNameError}
              className="w-full"
            />
          </div>
        </div>
        
        {/* Email */}
        <div>
          <label htmlFor="email" className="block text-sm font-medium mb-1 text-[var(--text-primary)]">
            {t('auth:register.email', 'Email')}
          </label>
          <Input
            id="email"
            type="email"
            value={formData.email}
            onChange={(e) => updateField('email', e.target.value)}
            onBlur={() => {
              const validation = validateEmailField(formData.email);
              if (!validation.isValid) {
                updateField('emailError', validation.error);
              } else {
                updateField('emailError', '');
              }
            }}
            placeholder={t('auth:register.email_placeholder', 'your@email.com')}
            error={errors.email || formData.emailError}
            className="w-full"
          />
        </div>
        
        {/* Password */}
        <div>
          <label htmlFor="password" className="block text-sm font-medium mb-1 text-[var(--text-primary)]">
            {t('auth:register.password', 'Password')}
          </label>
          <div className="relative">
            <Input
              id="password"
              type={showPassword ? 'text' : 'password'}
              value={formData.password}
              onChange={(e) => updateField('password', e.target.value)}
              onBlur={() => {
                const validation = validatePasswordField(formData.password);
                if (!validation.isValid) {
                  updateField('passwordError', validation.error);
                } else {
                  updateField('passwordError', '');
                }
              }}
              placeholder={t('auth:register.password_placeholder', '••••••••')}
              error={errors.password || formData.passwordError}
              className="w-full"
              rightIcon={showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
              onRightIconClick={() => setShowPassword(!showPassword)}
            />
          </div>
          <PasswordCriteria password={formData.password} className="mt-2" />
          
          {/* Password Strength Meter */}
          {formData.password && (
            <div className="mt-4">
              <div className="flex justify-between text-xs text-[var(--text-tertiary)] mb-1">
                <span>{t('auth:register.password_strength', 'Password Strength')}</span>
                <span>{calculatePasswordStrength(formData.password)}</span>
              </div>
              <div className="flex space-x-1">
                {Array.from({ length: 4 }).map((_, index) => (
                  <div
                    key={index}
                    className={`h-1 flex-1 rounded-full transition-all ${
                      getStrengthColor(index, formData.password)
                    }`}
                  />
                ))}
              </div>
            </div>
          )}
        </div>
        
        {/* Confirm Password */}
        <div>
          <label htmlFor="confirmPassword" className="block text-sm font-medium mb-1 text-[var(--text-primary)]">
            {t('auth:register.confirm_password', 'Confirm Password')}
          </label>
          <div className="relative">
            <Input
              id="confirmPassword"
              type={showConfirmPassword ? 'text' : 'password'}
              value={formData.confirmPassword}
              onChange={(e) => updateField('confirmPassword', e.target.value)}
              onBlur={() => {
                const validation = validateConfirmPassword(formData.confirmPassword);
                if (!validation.isValid) {
                  updateField('confirmPasswordError', validation.error);
                } else {
                  updateField('confirmPasswordError', '');
                }
              }}
              placeholder={t('auth:register.confirm_password_placeholder', '••••••••')}
              error={errors.confirmPassword || formData.confirmPasswordError}
              isValid={formData.confirmPassword.length > 0 && formData.confirmPassword === formData.password}
              className="w-full"
              rightIcon={showConfirmPassword ? <EyeOff size={18} /> : <Eye size={18} />}
              onRightIconClick={() => setShowConfirmPassword(!showConfirmPassword)}
            />
          </div>
        </div>
        
        {/* Terms and Conditions - Mobile optimized */}
        <div className="space-y-3 pt-2">
          <Checkbox
            id="acceptTerms"
            checked={formData.acceptTerms}
            onCheckedChange={(checked) => updateField('acceptTerms', checked)}
            error={errors.acceptTerms}
            label={(
              <span className="text-sm text-[var(--text-primary)]">
                {t('auth:register.accept_terms', 'I accept the')}{' '}
                <a href="/terms" target="_blank" rel="noopener noreferrer" className="text-[var(--color-primary)] hover:underline font-medium">
                  {t('auth:register.terms_of_service', 'Terms of Service')}
                </a>{' '}
                {t('auth:register.and', 'and')}{' '}
                <a href="/privacy" target="_blank" rel="noopener noreferrer" className="text-[var(--color-primary)] hover:underline font-medium">
                  {t('auth:register.privacy_policy', 'Privacy Policy')}
                </a>
              </span>
            )}
          />

          {/* Marketing and Analytics Consent - Stack on mobile */}
          <div className="flex flex-col gap-3">
            <Checkbox
              id="marketingConsent"
              checked={formData.marketingConsent}
              onCheckedChange={(checked) => updateField('marketingConsent', checked)}
              label={(
                <span className="text-sm text-[var(--text-secondary)]">
                  {t('auth:register.marketing_consent', 'Subscribe to marketing communications (optional)')}
                </span>
              )}
            />

            <Checkbox
              id="analyticsConsent"
              checked={formData.analyticsConsent}
              onCheckedChange={(checked) => updateField('analyticsConsent', checked)}
              label={(
                <span className="text-sm text-[var(--text-secondary)]">
                  {t('auth:register.analytics_consent', 'Allow analytics cookies to improve experience')}
                </span>
              )}
            />
          </div>
        </div>

        {/* Submit Button */}
        <div className="pt-4 sm:pt-6">
          <Button
            type="submit"
            variant="primary"
            size="lg"
            isFullWidth
            disabled={isSubmitting}
            isLoading={isSubmitting}
            loadingText={t('auth:register.submitting', 'Submitting...')}
          >
            {t('auth:register.continue', 'Continue')}
          </Button>
        </div>

        {/* Login Link */}
        <div className="text-center pt-2">
          <p className="text-sm text-[var(--text-secondary)]">
            {t('auth:register.already_have_account', 'Already have an account?')}{' '}
            <button
              type="button"
              onClick={onLoginClick}
              className="text-[var(--color-primary)] hover:underline font-medium"
            >
              {t('auth:register.login', 'Log in')}
            </button>
          </p>
        </div>
        
        {/* Pilot program message removed as requested */}
        {false && isPilot && (
          <div className="mt-4 p-3 bg-[var(--color-info-50)] rounded-lg">
            <p className="text-sm text-[var(--color-info-800)]">
              🎉 {t('auth:register.pilot_program', 'You are eligible for our pilot program!')}
            </p>
          </div>
        )}
      </form>
    </div>
  );
};

export default BasicInfoStep;