/*
 * File: EmailStep.tsx
 * Description: Email step component for signup flow
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */

import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
} from 'react-native';
import { theme } from '../../../../theme/theme';
import { EmailStepProps } from '../../types/signup';
import Icon from 'react-native-vector-icons/Feather';

// ============================================================================
// EMAIL STEP COMPONENT
// ============================================================================

/**
 * EmailStep Component
 * 
 * Purpose: First step of signup flow - email validation
 * 
 * Features:
 * - Email input with validation
 * - Real-time email format checking
 * - Continue button with loading state
 * - Back navigation
 * - Modern header with proper alignment
 */
const EmailStep: React.FC<EmailStepProps> = ({
  onContinue,
  onBack,
  data,
  isLoading,
}) => {
  // ============================================================================
  // STATE MANAGEMENT
  // ============================================================================
  
  const [email, setEmail] = useState(data.email || '');
  const [emailError, setEmailError] = useState('');

  // ============================================================================
  // VALIDATION FUNCTIONS
  // ============================================================================
  
  /**
   * Validate Email Format
   * 
   * Purpose: Check if email format is valid
   */
  const validateEmailFormat = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  /**
   * Handle Email Change
   * 
   * Purpose: Update email and clear errors
   */
  const handleEmailChange = (text: string) => {
    setEmail(text);
    setEmailError('');
  };

  /**
   * Handle Continue
   * 
   * Purpose: Validate email and proceed to next step
   */
  const handleContinue = () => {
    // Clear previous errors
    setEmailError('');

    // Validate email format
    if (!email.trim()) {
      setEmailError('Email is required');
      return;
    }

    if (!validateEmailFormat(email.trim())) {
      setEmailError('Please enter a valid email address');
      return;
    }

    // Call parent handler
    onContinue(email.trim());
  };

  // ============================================================================
  // RENDER
  // ============================================================================
  
  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View style={styles.header}>
          <TouchableOpacity onPress={onBack} style={styles.backButton}>
            <Icon 
              name="arrow-left" 
              size={24} 
              color={theme.colors.textPrimary} 
            />
          </TouchableOpacity>
          
          <View style={styles.headerContent}>
            <Text style={styles.title}>Create Account</Text>
            <Text style={styles.subtitle}>Step 1 of 5</Text>
          </View>
          
          <View style={styles.headerSpacer} />
        </View>

        {/* Content */}
        <View style={styles.content}>
          <Text style={styles.sectionTitle}>Enter your email address</Text>
          <Text style={styles.description}>
            We'll use this email to create your account and send you important updates.
          </Text>

          {/* Email Input */}
          <View style={styles.inputContainer}>
            <Text style={styles.inputLabel}>Email Address</Text>
            <TextInput
              style={[
                styles.input,
                emailError ? styles.inputError : null,
              ]}
              placeholder="Enter your email address"
              placeholderTextColor={theme.colors.textMuted}
              value={email}
              onChangeText={handleEmailChange}
              keyboardType="email-address"
              autoCapitalize="none"
              autoCorrect={false}
              autoComplete="email"
              textContentType="emailAddress"
              editable={!isLoading}
            />
            {emailError ? (
              <Text style={styles.errorText}>{emailError}</Text>
            ) : null}
          </View>

          {/* Continue Button */}
          <TouchableOpacity
            style={[
              styles.continueButton,
              (!email.trim() || isLoading) ? styles.continueButtonDisabled : null,
            ]}
            onPress={handleContinue}
            disabled={!email.trim() || isLoading}
          >
            <Text style={[
              styles.continueButtonText,
              (!email.trim() || isLoading) ? styles.continueButtonTextDisabled : null,
            ]}>
              {isLoading ? 'Validating...' : 'Continue'}
            </Text>
          </TouchableOpacity>

          {/* Additional Info */}
          <View style={styles.infoContainer}>
            <Text style={styles.infoText}>
              By continuing, you agree to our Terms of Service and Privacy Policy.
            </Text>
          </View>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
};

// ============================================================================
// STYLES
// ============================================================================

const styles = StyleSheet.create({
  // Main container
  container: {
    flex: 1,
    backgroundColor: theme.colors.background,
  },

  // Scroll view
  scrollView: {
    flex: 1,
  },

  // Scroll content
  scrollContent: {
    flexGrow: 1,
    paddingHorizontal: theme.spacing.sm,
  },

  // Header section
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingTop: theme.spacing.xl,
    paddingBottom: theme.spacing.lg,
    marginBottom: theme.spacing.lg,
  },

  // Back button
  backButton: {
    padding: theme.spacing.sm,
    borderRadius: theme.borderRadius.medium,
    backgroundColor: theme.colors.backgroundAlt,
  },

  // Header content
  headerContent: {
    flex: 1,
    alignItems: 'center',
  },

  // Header spacer
  headerSpacer: {
    width: 40,
  },

  // Title
  title: {
    fontSize: theme.typography.fontSize.displaySmall,
    fontFamily: theme.typography.fontFamily.bold,
    color: theme.colors.textPrimary,
    marginBottom: theme.spacing.xs,
  },

  // Subtitle
  subtitle: {
    fontSize: theme.typography.fontSize.bodyMedium,
    fontFamily: theme.typography.fontFamily.regular,
    color: theme.colors.textSecondary,
  },

  // Content section
  content: {
    flex: 1,
    justifyContent: 'center',
    paddingBottom: theme.spacing.xl,
  },

  // Section title
  sectionTitle: {
    fontSize: theme.typography.fontSize.displaySmall,
    fontFamily: theme.typography.fontFamily.bold,
    color: theme.colors.textPrimary,
    marginBottom: theme.spacing.sm,
  },

  // Description
  description: {
    fontSize: theme.typography.fontSize.bodyMedium,
    fontFamily: theme.typography.fontFamily.regular,
    color: theme.colors.textSecondary,
    marginBottom: theme.spacing.xl,
  },

  // Input container
  inputContainer: {
    marginBottom: theme.spacing.xl,
  },

  // Input label
  inputLabel: {
    fontSize: theme.typography.fontSize.bodyMedium,
    fontFamily: theme.typography.fontFamily.medium,
    color: theme.colors.textPrimary,
    marginBottom: theme.spacing.sm,
  },

  // Input field
  input: {
    borderWidth: 1,
    borderColor: theme.colors.border,
    borderRadius: theme.borderRadius.medium,
    paddingHorizontal: theme.spacing.md,
    paddingVertical: theme.spacing.md,
    fontSize: theme.typography.fontSize.bodyLarge,
    fontFamily: theme.typography.fontFamily.regular,
    color: theme.colors.textPrimary,
    backgroundColor: theme.colors.background,
  },

  // Input error state
  inputError: {
    borderColor: theme.colors.error,
  },

  // Error text
  errorText: {
    fontSize: theme.typography.fontSize.bodySmall,
    fontFamily: theme.typography.fontFamily.regular,
    color: theme.colors.error,
    marginTop: theme.spacing.xs,
  },

  // Continue button
  continueButton: {
    backgroundColor: theme.colors.primary,
    borderRadius: theme.borderRadius.medium,
    paddingVertical: theme.spacing.md,
    paddingHorizontal: theme.spacing.lg,
    alignItems: 'center',
    marginBottom: theme.spacing.lg,
    ...theme.shadows.primary,
  },

  // Continue button disabled
  continueButtonDisabled: {
    backgroundColor: theme.colors.border,
    opacity: 0.6,
  },

  // Continue button text
  continueButtonText: {
    fontSize: theme.typography.fontSize.bodyLarge,
    fontFamily: theme.typography.fontFamily.bold,
    color: theme.colors.background,
  },

  // Continue button text disabled
  continueButtonTextDisabled: {
    color: theme.colors.textMuted,
  },

  // Info container
  infoContainer: {
    alignItems: 'center',
  },

  // Info text
  infoText: {
    fontSize: theme.typography.fontSize.bodySmall,
    fontFamily: theme.typography.fontFamily.regular,
    color: theme.colors.textMuted,
    textAlign: 'center',
  },
});

export default EmailStep;

/*
 * End of File: EmailStep.tsx
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */ 