import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  Image,
  ActivityIndicator,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { useTheme } from '@/constants/ThemeContext';
import { ArrowLeft, Mail, Lock, Eye, EyeOff } from 'lucide-react-native';
import { images } from '@/constants/images';
import { FacebookIcon, GoogleIcon, AppleIcon } from '@/components/SocialIcons';
import styles from '@/styles/auth/login.styles';
import authService from '@/services/auth';

export default function LoginScreen() {
  const router = useRouter();
  const { isDark } = useTheme();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleLogin = async () => {
    setError(null);

    if (!email.trim() || !password) {
      setError('Please enter both email and password.');
      return;
    }

    try {
      setLoading(true);
      const res = await authService.login(email.trim().toLowerCase(), password);

      if (res.status === 'success') {
        // If email is not verified, nudge them
        if (res.user && res.user.email_verified === false) {
          Alert.alert(
            'Email Not Verified',
            'Your email is not verified yet. Some features will be limited. Check your inbox or resend from the verification screen.',
            [
              { text: 'Continue Anyway', onPress: () => router.replace('/(tabs)' as any) },
              {
                text: 'Verify Now',
                onPress: () =>
                  router.replace({
                    pathname: '/(auth)/verify-account',
                    params: { email: res.user!.email },
                  } as any),
              },
            ]
          );
        } else {
          router.replace('/(tabs)' as any);
        }
      } else {
        setError(res.message || 'Login failed. Please check your credentials.');
      }
    } catch (e: any) {
      console.error('Login error:', e);
      setError('Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleForgotPassword = () => {
    router.push('/(auth)/forgot-password' as any);
  };

  const handleCreateAccount = () => {
    router.push('/(auth)/register' as any);
  };

  return (
    <SafeAreaView
      style={[styles.safeArea, { backgroundColor: isDark ? '#050E24' : '#FFFFFF' }]}
    >
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
      >
        <TouchableOpacity
          onPress={() => router.back()}
          style={styles.backButton}
          activeOpacity={0.7}
        >
          <ArrowLeft size={20} color={isDark ? '#FFFFFF' : '#0C1C3E'} />
          <Text style={[styles.backText, { color: isDark ? '#FFFFFF' : '#0C1C3E' }]}>
            Back
          </Text>
        </TouchableOpacity>

        <View style={styles.heroImageContainer}>
          <Image source={images.loginPic} style={styles.heroImage} resizeMode="cover" />
        </View>

        <View style={styles.headerContainer}>
          <Text style={[styles.title, { color: isDark ? '#FFFFFF' : '#0C1C3E' }]}>
            welcome back
          </Text>
          <Text style={[styles.subtitle, { color: isDark ? '#94A3B8' : '#8CA3BA' }]}>
            Login to continue your journey
          </Text>
        </View>

        <View style={styles.formContainer}>
          {error && (
            <View
              style={{
                backgroundColor: '#FEE2E2',
                padding: 12,
                borderRadius: 8,
                marginBottom: 16,
              }}
            >
              <Text style={{ color: '#991B1B', fontSize: 13 }}>{error}</Text>
            </View>
          )}

          {/* Email */}
          <View style={styles.inputGroup}>
            <View style={styles.labelRow}>
              <Text style={[styles.inputLabel, { color: isDark ? '#CBD5E1' : '#0F172A' }]}>
                Email
              </Text>
              <Mail size={15} color={isDark ? '#94A3B8' : '#475569'} style={{ marginLeft: 6 }} />
            </View>
            <View
              style={[
                styles.inputWrapper,
                {
                  backgroundColor: isDark ? '#0F172A' : '#FFFFFF',
                  borderColor: isDark ? '#1E293B' : '#CBD5E1',
                },
              ]}
            >
              <TextInput
                value={email}
                onChangeText={setEmail}
                placeholder="you@example.com"
                placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
                keyboardType="email-address"
                autoCapitalize="none"
                style={[styles.input, { color: isDark ? '#FFFFFF' : '#0F172A' }]}
              />
            </View>
          </View>

          {/* Password */}
          <View style={styles.inputGroup}>
            <View style={styles.labelRow}>
              <Text style={[styles.inputLabel, { color: isDark ? '#CBD5E1' : '#0F172A' }]}>
                Password
              </Text>
              <Lock size={15} color={isDark ? '#94A3B8' : '#475569'} style={{ marginLeft: 6 }} />
            </View>
            <View
              style={[
                styles.inputWrapper,
                {
                  backgroundColor: isDark ? '#0F172A' : '#FFFFFF',
                  borderColor: isDark ? '#1E293B' : '#CBD5E1',
                },
              ]}
            >
              <TextInput
                value={password}
                onChangeText={setPassword}
                placeholder="••••••••"
                placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
                secureTextEntry={!showPassword}
                style={[styles.input, { color: isDark ? '#FFFFFF' : '#0F172A' }]}
              />
              <TouchableOpacity onPress={() => setShowPassword(!showPassword)}>
                {showPassword ? (
                  <EyeOff size={18} color={isDark ? '#94A3B8' : '#64748B'} />
                ) : (
                  <Eye size={18} color={isDark ? '#94A3B8' : '#64748B'} />
                )}
              </TouchableOpacity>
            </View>

            <TouchableOpacity onPress={handleForgotPassword} style={styles.forgotPasswordButton}>
              <Text style={styles.forgotPasswordText}>Forgot password?</Text>
            </TouchableOpacity>
          </View>

          {/* Login Button */}
          <TouchableOpacity
            style={[styles.loginButton, loading && { opacity: 0.7 }]}
            onPress={handleLogin}
            disabled={loading}
            activeOpacity={0.88}
          >
            {loading ? (
              <ActivityIndicator color="#FFFFFF" />
            ) : (
              <Text style={styles.loginButtonText}>Login</Text>
            )}
          </TouchableOpacity>

          {/* Divider */}
          <View style={styles.dividerRow}>
            <View style={styles.dividerLine} />
            <Text style={styles.dividerText}>Or connect using</Text>
            <View style={styles.dividerLine} />
          </View>

          {/* Social — disabled for now */}
          <View style={styles.socialRow}>
            <TouchableOpacity
              style={[styles.socialButton, { opacity: 0.5 }]}
              onPress={() => Alert.alert('Coming soon', 'Social login is not available yet.')}
              activeOpacity={0.8}
            >
              <FacebookIcon />
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.socialButton, { opacity: 0.5 }]}
              onPress={() => Alert.alert('Coming soon', 'Social login is not available yet.')}
              activeOpacity={0.8}
            >
              <GoogleIcon />
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.socialButton, { opacity: 0.5 }]}
              onPress={() => Alert.alert('Coming soon', 'Social login is not available yet.')}
              activeOpacity={0.8}
            >
              <AppleIcon />
            </TouchableOpacity>
          </View>

          {/* Register redirect */}
          <TouchableOpacity
            onPress={handleCreateAccount}
            style={styles.registerRedirect}
            activeOpacity={0.7}
          >
            <Text style={styles.registerRedirectSkyText}>
              Don't have an account?{' '}
              <Text style={styles.registerRedirectNavyText}>create account</Text>
            </Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}