import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  Pressable,
  ScrollView,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import GradientBackground from '@/shared/components/layout/GradientBackground';
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useDispatch, useSelector } from 'react-redux';
import { register, clearError } from '@/modules/auth/store/authSlice';
import type { RootState, AppDispatch } from '@/store/store';
import { useTheme } from '@/shared/styles/useTheme';
import { validateSignupForm } from '@/shared/utils/validation';
import { showError, showSuccess, showWarning, showInfo } from '@/shared/utils/Toast';

const SignupScreen: React.FC = () => {
  const navigation = useNavigation();
  const dispatch = useDispatch<AppDispatch>();
  const { colors, fonts } = useTheme();
  const { loading, error } = useSelector((s: RootState) => s.auth);

  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [confirmPassword, setConfirmPassword] = React.useState('');
  const [firstName, setFirstName] = React.useState('');
  const [lastName, setLastName] = React.useState('');
  const [showPassword, setShowPassword] = React.useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = React.useState(false);
  const [focused, setFocused] = React.useState<null | 'email' | 'password' | 'confirmPassword' | 'firstName' | 'lastName'>(null);
  const [validationErrors, setValidationErrors] = React.useState<{ 
    email?: string; 
    password?: string; 
    confirmPassword?: string; 
    firstName?: string; 
    lastName?: string; 
  }>({});

  const emailRef = React.useRef<TextInput>(null);
  const passwordRef = React.useRef<TextInput>(null);
  const confirmPasswordRef = React.useRef<TextInput>(null);
  const firstNameRef = React.useRef<TextInput>(null);
  const lastNameRef = React.useRef<TextInput>(null);

  // Clear validation errors when user starts typing
  const handleEmailChange = (text: string) => {
    setEmail(text);
    if (validationErrors.email) {
      setValidationErrors(prev => ({ ...prev, email: undefined }));
    }
    if (error) {
      dispatch(clearError());
    }
  };

  const handlePasswordChange = (text: string) => {
    setPassword(text);
    if (validationErrors.password) {
      setValidationErrors(prev => ({ ...prev, password: undefined }));
    }
    if (error) {
      dispatch(clearError());
    }
  };

  const handleConfirmPasswordChange = (text: string) => {
    setConfirmPassword(text);
    if (validationErrors.confirmPassword) {
      setValidationErrors(prev => ({ ...prev, confirmPassword: undefined }));
    }
    if (error) {
      dispatch(clearError());
    }
  };

  const handleFirstNameChange = (text: string) => {
    setFirstName(text);
    if (validationErrors.firstName) {
      setValidationErrors(prev => ({ ...prev, firstName: undefined }));
    }
    if (error) {
      dispatch(clearError());
    }
  };

  const handleLastNameChange = (text: string) => {
    setLastName(text);
    if (validationErrors.lastName) {
      setValidationErrors(prev => ({ ...prev, lastName: undefined }));
    }
    if (error) {
      dispatch(clearError());
    }
  };

  const handleSignup = async () => {
    // Clear previous validation errors
    setValidationErrors({});

    // Validate form inputs
    const validation = validateSignupForm(email, password, confirmPassword, firstName, lastName);
    
    if (!validation.isValid) {
      setValidationErrors(validation.errors);
      
      // Show toast messages for validation errors
      Object.values(validation.errors).forEach(error => {
        if (error) {
          showError(error);
        }
      });
      return;
    }

    try {
      // Dispatch register action
      const result = await dispatch(register({ email, password, firstName, lastName }));
      
      // Check if registration was successful
      if (register.fulfilled.match(result)) {
        // Registration successful - show success toast
        showSuccess('Registration successful! Please login to continue.');
        // Clear form
        setEmail('');
        setPassword('');
        setConfirmPassword('');
        setFirstName('');
        setLastName('');
        
        // Navigate to login screen after 1 second delay
        setTimeout(() => {
          navigation.navigate('Login' as never);
        }, 1000);
      } else if (register.rejected.match(result)) {
        // Registration failed - show error toast
        showError(result.payload as string || 'Registration failed. Please try again.');
      }
    } catch (err) {
      // Error handling is done in the slice
      console.error('Registration error:', err);
      showError('An unexpected error occurred. Please try again.');
    }
  };

  // Clear error when component mounts or when user starts typing
  React.useEffect(() => {
    if (error) {
      dispatch(clearError());
    }
  }, [dispatch]);

  // Auto-focus first name input when component mounts
  React.useEffect(() => {
    const timer = setTimeout(() => {
      firstNameRef.current?.focus();
    }, 100);
    return () => clearTimeout(timer);
  }, []);

  const isFormValid = email.trim() && password.trim() && confirmPassword.trim() && firstName.trim() && lastName.trim();

  return (
    <GradientBackground preset="warm" style={styles.gradient}>
      <KeyboardAvoidingView 
        style={styles.container} 
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        // keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 20}
      >
        <ScrollView 
          contentContainerStyle={styles.scrollContainer}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
        >
          {/* Card */}
          <View style={[styles.card, { backgroundColor: colors.surface, borderColor: colors.border }]}>
            {/* Logo placeholder */}
            <View style={[styles.logoCircle, { backgroundColor: '#F1F5F9' }]}>
              <Icon name="account-plus" size={28} color={colors.primary} />
            </View>

            <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>Create Account</Text>
            <Text style={[styles.subtitle, { color: colors.textLight, fontFamily: fonts.regular }]}>
              Fill in your details to get started
            </Text>

            {/* First Name input */}
            <View>
              <Pressable
                style={[
                  styles.inputWrapper,
                  {
                    borderColor: validationErrors.firstName 
                      ? colors.error 
                      : focused === 'firstName' 
                        ? colors.primary 
                        : colors.border,
                    backgroundColor: colors.surface,
                  },
                ]}
                onPress={() => firstNameRef.current?.focus()}
              >
                <Icon 
                  name="account-outline" 
                  size={20} 
                  color={validationErrors.firstName 
                    ? colors.error 
                    : focused === 'firstName' 
                      ? colors.primary 
                      : colors.textLight
                  } 
                />
                <TextInput
                  ref={firstNameRef}
                  placeholder="First Name"
                  placeholderTextColor={colors.textLight}
                  autoCapitalize="words"
                  autoCorrect={false}
                  autoComplete="given-name"
                  returnKeyType="next"
                  value={firstName}
                  onFocus={() => setFocused('firstName')}
                  onBlur={() => setFocused(null)}
                  onChangeText={handleFirstNameChange}
                  onSubmitEditing={() => lastNameRef.current?.focus()}
                  style={[styles.input, { color: colors.text, fontFamily: fonts.regular }]}
                />
              </Pressable>
              {validationErrors.firstName && (
                <Text style={[styles.errorText, { color: colors.error, fontFamily: fonts.regular }]}>
                  {validationErrors.firstName}
                </Text>
              )}
            </View>

            {/* Last Name input */}
            <View>
              <Pressable
                style={[
                  styles.inputWrapper,
                  {
                    borderColor: validationErrors.lastName 
                      ? colors.error 
                      : focused === 'lastName' 
                        ? colors.primary 
                        : colors.border,
                    backgroundColor: colors.surface,
                  },
                ]}
                onPress={() => lastNameRef.current?.focus()}
              >
                <Icon 
                  name="account-outline" 
                  size={20} 
                  color={validationErrors.lastName 
                    ? colors.error 
                    : focused === 'lastName' 
                      ? colors.primary 
                      : colors.textLight
                  } 
                />
                <TextInput
                  ref={lastNameRef}
                  placeholder="Last Name"
                  placeholderTextColor={colors.textLight}
                  autoCapitalize="words"
                  autoCorrect={false}
                  autoComplete="family-name"
                  returnKeyType="next"
                  value={lastName}
                  onFocus={() => setFocused('lastName')}
                  onBlur={() => setFocused(null)}
                  onChangeText={handleLastNameChange}
                  onSubmitEditing={() => emailRef.current?.focus()}
                  style={[styles.input, { color: colors.text, fontFamily: fonts.regular }]}
                />
              </Pressable>
              {validationErrors.lastName && (
                <Text style={[styles.errorText, { color: colors.error, fontFamily: fonts.regular }]}>
                  {validationErrors.lastName}
                </Text>
              )}
            </View>

            {/* Email input */}
            <View>
              <Pressable
                style={[
                  styles.inputWrapper,
                  {
                    borderColor: validationErrors.email 
                      ? colors.error 
                      : focused === 'email' 
                        ? colors.primary 
                        : colors.border,
                    backgroundColor: colors.surface,
                  },
                ]}
                onPress={() => emailRef.current?.focus()}
              >
                <Icon 
                  name="email-outline" 
                  size={20} 
                  color={validationErrors.email 
                    ? colors.error 
                    : focused === 'email' 
                      ? colors.primary 
                      : colors.textLight
                  } 
                />
                <TextInput
                  ref={emailRef}
                  placeholder="Email"
                  placeholderTextColor={colors.textLight}
                  autoCapitalize="none"
                  autoCorrect={false}
                  autoComplete="email"
                  keyboardType="email-address"
                  returnKeyType="next"
                  value={email}
                  onFocus={() => setFocused('email')}
                  onBlur={() => setFocused(null)}
                  onChangeText={handleEmailChange}
                  onSubmitEditing={() => passwordRef.current?.focus()}
                  style={[styles.input, { color: colors.text, fontFamily: fonts.regular }]}
                />
              </Pressable>
              {validationErrors.email && (
                <Text style={[styles.errorText, { color: colors.error, fontFamily: fonts.regular }]}>
                  {validationErrors.email}
                </Text>
              )}
            </View>

            {/* Password input */}
            <View>
              <Pressable
                style={[
                  styles.inputWrapper,
                  {
                    borderColor: validationErrors.password 
                      ? colors.error 
                      : focused === 'password' 
                        ? colors.primary 
                        : colors.border,
                    backgroundColor: colors.surface,
                  },
                ]}
                onPress={() => passwordRef.current?.focus()}
              >
                <Icon 
                  name="lock-outline" 
                  size={20} 
                  color={validationErrors.password 
                    ? colors.error 
                    : focused === 'password' 
                      ? colors.primary 
                      : colors.textLight
                  } 
                />
                <TextInput
                  ref={passwordRef}
                  placeholder="Password"
                  placeholderTextColor={colors.textLight}
                  secureTextEntry={!showPassword}
                  textContentType="newPassword"
                  autoComplete="new-password"
                  autoCorrect={false}
                  autoCapitalize="none"
                  value={password}
                  onFocus={() => setFocused('password')}
                  onBlur={() => setFocused(null)}
                  onChangeText={handlePasswordChange}
                  onSubmitEditing={() => confirmPasswordRef.current?.focus()}
                  style={[styles.input, { color: colors.text, fontFamily: fonts.regular }]}
                />
                <TouchableOpacity
                  style={styles.iconButton}
                  onPress={() => setShowPassword(v => !v)}
                  hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
                  accessibilityRole="button"
                  accessibilityLabel={showPassword ? 'Hide password' : 'Show password'}
                >
                  <Icon name={showPassword ? 'eye-off-outline' : 'eye-outline'} size={22} color={colors.textLight} />
                </TouchableOpacity>
              </Pressable>
              {validationErrors.password && (
                <Text style={[styles.errorText, { color: colors.error, fontFamily: fonts.regular }]}>
                  {validationErrors.password}
                </Text>
              )}
            </View>

            {/* Confirm Password input */}
            <View>
              <Pressable
                style={[
                  styles.inputWrapper,
                  {
                    borderColor: validationErrors.confirmPassword 
                      ? colors.error 
                      : focused === 'confirmPassword' 
                        ? colors.primary 
                        : colors.border,
                    backgroundColor: colors.surface,
                  },
                ]}
                onPress={() => confirmPasswordRef.current?.focus()}
              >
                <Icon 
                  name="lock-check-outline" 
                  size={20} 
                  color={validationErrors.confirmPassword 
                    ? colors.error 
                    : focused === 'confirmPassword' 
                      ? colors.primary 
                      : colors.textLight
                  } 
                />
                <TextInput
                  ref={confirmPasswordRef}
                  placeholder="Confirm Password"
                  placeholderTextColor={colors.textLight}
                  secureTextEntry={!showConfirmPassword}
                  textContentType="newPassword"
                  autoComplete="new-password"
                  autoCorrect={false}
                  autoCapitalize="none"
                  value={confirmPassword}
                  onFocus={() => setFocused('confirmPassword')}
                  onBlur={() => setFocused(null)}
                  onChangeText={handleConfirmPasswordChange}
                  style={[styles.input, { color: colors.text, fontFamily: fonts.regular }]}
                />
                <TouchableOpacity
                  style={styles.iconButton}
                  onPress={() => setShowConfirmPassword(v => !v)}
                  hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
                  accessibilityRole="button"
                  accessibilityLabel={showConfirmPassword ? 'Hide confirm password' : 'Show confirm password'}
                >
                  <Icon name={showConfirmPassword ? 'eye-off-outline' : 'eye-outline'} size={22} color={colors.textLight} />
                </TouchableOpacity>
              </Pressable>
              {validationErrors.confirmPassword && (
                <Text style={[styles.errorText, { color: colors.error, fontFamily: fonts.regular }]}>
                  {validationErrors.confirmPassword}
                </Text>
              )}
            </View>

            {/* Password requirements */}
            <View style={styles.passwordRequirements}>
              <Text style={[styles.requirementsTitle, { color: colors.textLight, fontFamily: fonts.medium }]}>
                Password must contain:
              </Text>
              <Text style={[styles.requirement, { color: colors.textLight, fontFamily: fonts.regular }]}>
                • At least 8 characters
              </Text>
              <Text style={[styles.requirement, { color: colors.textLight, fontFamily: fonts.regular }]}>
                • One uppercase letter
              </Text>
              <Text style={[styles.requirement, { color: colors.textLight, fontFamily: fonts.regular }]}>
                • One lowercase letter
              </Text>
              <Text style={[styles.requirement, { color: colors.textLight, fontFamily: fonts.regular }]}>
                • One number
              </Text>
              <Text style={[styles.requirement, { color: colors.textLight, fontFamily: fonts.regular }]}>
                • One special character
              </Text>
            </View>

            {/* Signup button */}
            <TouchableOpacity 
              activeOpacity={0.9} 
              onPress={handleSignup} 
              disabled={loading || !isFormValid} 
              style={{ marginTop: 12 }}
            >
              <LinearGradient 
                colors={loading || !isFormValid 
                  ? [colors.border, colors.border] 
                  : ["#3AA0FF", "#2D6BFF"]
                } 
                start={{ x: 0, y: 0 }} 
                end={{ x: 1, y: 0 }} 
                style={styles.signupButton}
              >
                <Text style={[styles.signupButtonText, { fontFamily: fonts.bold }]}>
                  {loading ? 'Creating Account...' : 'Create Account'}
                </Text>
              </LinearGradient>
            </TouchableOpacity>

            {/* Sign in */}
            <View style={styles.signinRow}>
              <Text style={[styles.signinText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                Already have an account? 
              </Text>
              <TouchableOpacity onPress={() => navigation.navigate('Login' as never)}>
                <Text style={[styles.link, { color: colors.primary, fontFamily: fonts.medium }]}>Sign in</Text>
              </TouchableOpacity>
            </View>

            {/* API Error */}
            {!!error && (
              <View style={styles.errorContainer}>
                <Icon name="alert-circle-outline" size={16} color={colors.error} />
                <Text style={[styles.errorText, { color: colors.error, fontFamily: fonts.regular }]}>
                  {error}
                </Text>
              </View>
            )}
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </GradientBackground>
  );
};

const styles = StyleSheet.create({
  gradient: {
    flex: 1,
  },
  container: {
    flex: 1,
  },
  scrollContainer: {
    flexGrow: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 16,
  },
  card: {
    width: '100%',
    maxWidth: 380,
    borderRadius: 16,
    padding: 16,
    borderWidth: 1,
  },
  logoCircle: {
    alignSelf: 'center',
    width: 48,
    height: 48,
    borderRadius: 12,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 8,
  },
  title: {
    fontSize: 24,
    textAlign: 'center',
  },
  subtitle: {
    textAlign: 'center',
    marginTop: 4,
    marginBottom: 12,
  },
  inputWrapper: {
    marginTop: 12,
    borderWidth: 1,
    borderRadius: 10,
    paddingHorizontal: 12,
    height: 52,
    flexDirection: 'row',
    alignItems: 'center',
  },
  input: {
    paddingVertical: 0,
    marginLeft: 8,
    flex: 1,
  },
  iconButton: {
    position: 'absolute',
    right: 8,
    top: 0,
    bottom: 0,
    width: 36,
    alignItems: 'center',
    justifyContent: 'center',
  },
  passwordRequirements: {
    marginTop: 8,
    paddingHorizontal: 8,
  },
  requirementsTitle: {
    fontSize: 12,
    marginBottom: 4,
  },
  requirement: {
    fontSize: 11,
    marginBottom: 2,
  },
  signupButton: {
    height: 48,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
  },
  signupButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
  },
  signinRow: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 16,
  },
  signinText: {
    fontSize: 12,
  },
  link: {},
  errorContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 12,
    paddingHorizontal: 8,
  },
  errorText: {
    marginLeft: 6,
    fontSize: 14,
    textAlign: 'left',
    flex: 1,
  },
});

export default SignupScreen;
