import React, { useState, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Image,
} from 'react-native';
import { router } from 'expo-router';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { ErrorMessage } from '@/components/ui/ErrorMessage';
import { AppColors, BorderRadius, FontSizes, Spacing } from '@/constants/theme';

export default function LoginScreen() {
  const { requestOtp, isLoading, error, clearError } = useAuth();
  const [email, setEmail] = useState('');
  const [validationError, setValidationError] = useState<string | null>(null);

  const validateEmail = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const handleContinue = useCallback(async () => {
    clearError();
    setValidationError(null);

    const trimmedEmail = email.trim().toLowerCase();

    if (!trimmedEmail) {
      setValidationError('Email is required');
      return;
    }

    if (!validateEmail(trimmedEmail)) {
      setValidationError('Please enter a valid email address');
      return;
    }

    const result = await requestOtp(trimmedEmail);

    if (result.success) {
      // Navigate to OTP verification screen
      router.push({
        pathname: '/(auth)/verify-otp',
        params: {
          email: trimmedEmail,
          skipOtp: result.skipOtp ? '1' : '0'
        }
      });
    }
  }, [email, requestOtp, clearError]);

  const displayError = validationError || error?.message;

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        {/* Logo / Header */}
        <View style={styles.header}>
          <Image
            source={require('@/assets/images/icon.png')}
            style={styles.logo}
            resizeMode="contain"
          />
          <Text style={styles.title}>Welcome to WellNuo</Text>
          <Text style={styles.subtitle}>
            Enter your email to sign in or create an account
          </Text>
        </View>

        {/* Form */}
        <View style={styles.form}>
          {displayError && (
            <ErrorMessage
              message={displayError}
              onDismiss={() => {
                clearError();
                setValidationError(null);
              }}
            />
          )}

          <Input
            label="Email"
            placeholder="Enter your email"
            leftIcon="mail-outline"
            value={email}
            onChangeText={(text) => {
              setEmail(text);
              setValidationError(null);
            }}
            autoCapitalize="none"
            autoCorrect={false}
            keyboardType="email-address"
            editable={!isLoading}
            onSubmitEditing={handleContinue}
            returnKeyType="done"
          />

          <Button
            title="Continue"
            onPress={handleContinue}
            loading={isLoading}
            fullWidth
            size="lg"
            style={styles.button}
          />
        </View>

        {/* Info */}
        <View style={styles.infoContainer}>
          <Text style={styles.infoText}>
            We'll send you a verification code to confirm your email
          </Text>
        </View>

        {/* Version Info */}
        <Text style={styles.version}>WellNuo v1.0.0</Text>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.background,
  },
  scrollContent: {
    flexGrow: 1,
    paddingHorizontal: Spacing.lg,
    paddingTop: Spacing.xxl + Spacing.xl,
    paddingBottom: Spacing.xl,
  },
  header: {
    alignItems: 'center',
    marginBottom: Spacing.xl,
  },
  logo: {
    width: 180,
    height: 100,
    marginBottom: Spacing.lg,
  },
  title: {
    fontSize: FontSizes['2xl'],
    fontWeight: '700',
    color: AppColors.textPrimary,
    marginBottom: Spacing.xs,
  },
  subtitle: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textAlign: 'center',
    paddingHorizontal: Spacing.md,
  },
  form: {
    marginBottom: Spacing.xl,
  },
  button: {
    marginTop: Spacing.md,
  },
  infoContainer: {
    alignItems: 'center',
    marginBottom: Spacing.xl,
  },
  infoText: {
    fontSize: FontSizes.sm,
    color: AppColors.textMuted,
    textAlign: 'center',
  },
  version: {
    textAlign: 'center',
    fontSize: FontSizes.xs,
    color: AppColors.textMuted,
    marginTop: 'auto',
  },
});
