import { Ionicons } from '@expo/vector-icons';
  import { LinearGradient } from 'expo-linear-gradient';
  import { router } from 'expo-router';
  import React, { useState } from 'react';
  import {
    ActivityIndicator,
    Alert,
    Image,
    KeyboardAvoidingView,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
  } from 'react-native';
  import { useSafeAreaInsets } from 'react-native-safe-area-context';
  import { useAuth } from '@/contexts/AuthContext';
  import { useColors } from '@/hooks/useColors';

  export default function LoginScreen() {
    const colors = useColors();
    const insets = useSafeAreaInsets();
    const { login } = useAuth();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [showPw, setShowPw] = useState(false);
    const [loading, setLoading] = useState(false);

    const topPad = Platform.OS === 'web' ? 67 : insets.top;
    const bottomPad = Platform.OS === 'web' ? 34 : insets.bottom;

    const handleLogin = async () => {
      if (!email.trim() || !password.trim()) {
        Alert.alert('Missing fields', 'Please enter your email and password.');
        return;
      }
      setLoading(true);
      try {
        await login(email.trim(), password);
      } catch {
        Alert.alert('Error', 'Something went wrong. Please try again.');
      } finally {
        setLoading(false);
      }
    };

    const handleGoogle = async () => {
      setLoading(true);
      try {
        await login('google@chinaskills.co.za', 'google-mock');
      } catch {
        Alert.alert('Google Sign-In', 'Google sign-in coming soon. Try the demo login for now.');
      } finally {
        setLoading(false);
      }
    };

    const handleDemo = async () => {
      setLoading(true);
      try {
        await login('demo@chinaskills.co.za', 'demo');
      } finally {
        setLoading(false);
      }
    };

    const handleForgotPassword = () => {
      Alert.alert(
        'Reset Password',
        'Enter your email address and we will send you a reset link.',
        [
          { text: 'Cancel', style: 'cancel' },
          {
            text: 'Send Reset Link',
            onPress: () => Alert.alert('Email Sent', 'Check your inbox for a password reset link.'),
          },
        ]
      );
    };

    return (
      <View style={[s.screen, { backgroundColor: colors.background }]}>
        <LinearGradient
          colors={['#FF3CAC22', '#FF6B3511', '#00000000']}
          style={[StyleSheet.absoluteFillObject, { height: 320 }]}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
        />

        <KeyboardAvoidingView
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
          style={{ flex: 1 }}
        >
          <ScrollView
            contentContainerStyle={[s.scroll, { paddingTop: topPad + 40, paddingBottom: bottomPad + 24 }]}
            keyboardShouldPersistTaps="handled"
          >
            <View style={s.logoArea}>
              <View style={s.logoClip}>
                <Image
                  source={require('../../assets/images/logo.png')}
                  style={s.logoImage}
                  resizeMode="cover"
                />
              </View>
              <Text style={[s.brandName, { color: colors.foreground }]}>
                China<Text style={{ color: '#FF6B35' }}>Skills</Text>.co.za
              </Text>
              <Text style={[s.tagline, { color: colors.mutedForeground }]}>Just learn a skill and make money for yourself</Text>
            </View>

            <View style={s.form}>
              {/* Google Sign-In */}
              <TouchableOpacity
                onPress={handleGoogle}
                style={s.googleBtn}
                disabled={loading}
                activeOpacity={0.85}
              >
                <View style={s.googleIconWrap}>
                  <Text style={s.googleG}>G</Text>
                </View>
                <Text style={s.googleBtnText}>Continue with Google</Text>
              </TouchableOpacity>

              <View style={s.dividerRow}>
                <View style={[s.divider, { backgroundColor: colors.border }]} />
                <Text style={[s.dividerText, { color: colors.mutedForeground }]}>or sign in with email</Text>
                <View style={[s.divider, { backgroundColor: colors.border }]} />
              </View>

              <Text style={[s.label, { color: colors.mutedForeground }]}>Email</Text>
              <View style={[s.inputWrap, { backgroundColor: colors.card, borderColor: colors.border }]}>
                <Ionicons name="mail-outline" size={18} color={colors.mutedForeground} />
                <TextInput
                  style={[s.input, { color: colors.foreground }]}
                  placeholder="you@example.com"
                  placeholderTextColor={colors.mutedForeground}
                  value={email}
                  onChangeText={setEmail}
                  keyboardType="email-address"
                  autoCapitalize="none"
                  autoCorrect={false}
                />
              </View>

              <View style={s.passwordHeader}>
                <Text style={[s.label, { color: colors.mutedForeground }]}>Password</Text>
                <TouchableOpacity onPress={handleForgotPassword}>
                  <Text style={s.forgotText}>Forgot password?</Text>
                </TouchableOpacity>
              </View>
              <View style={[s.inputWrap, { backgroundColor: colors.card, borderColor: colors.border }]}>
                <Ionicons name="lock-closed-outline" size={18} color={colors.mutedForeground} />
                <TextInput
                  style={[s.input, { color: colors.foreground }]}
                  placeholder="Enter password"
                  placeholderTextColor={colors.mutedForeground}
                  value={password}
                  onChangeText={setPassword}
                  secureTextEntry={!showPw}
                />
                <TouchableOpacity onPress={() => setShowPw(!showPw)}>
                  <Ionicons name={showPw ? 'eye-off-outline' : 'eye-outline'} size={18} color={colors.mutedForeground} />
                </TouchableOpacity>
              </View>

              <TouchableOpacity
                onPress={handleLogin}
                style={[s.loginBtn, { backgroundColor: colors.primary }]}
                disabled={loading}
                activeOpacity={0.85}
              >
                {loading ? (
                  <ActivityIndicator color="#fff" />
                ) : (
                  <Text style={s.loginBtnText}>Sign In</Text>
                )}
              </TouchableOpacity>

              <TouchableOpacity
                onPress={handleDemo}
                style={[s.demoBtn, { backgroundColor: '#FF3CAC18', borderColor: '#FF3CAC55' }]}
                disabled={loading}
                activeOpacity={0.85}
              >
                <Ionicons name="flash" size={16} color="#FF3CAC" />
                <Text style={[s.demoBtnText, { color: '#FF3CAC' }]}>Try Demo — skip sign in</Text>
              </TouchableOpacity>

              <View style={[s.dividerRow, { marginTop: 4 }]}>
                <View style={[s.divider, { backgroundColor: colors.border }]} />
                <Text style={[s.dividerText, { color: colors.mutedForeground }]}>or</Text>
                <View style={[s.divider, { backgroundColor: colors.border }]} />
              </View>

              <TouchableOpacity
                onPress={() => router.push('/auth/register' as any)}
                style={[s.registerBtn, { borderColor: colors.primary }]}
                activeOpacity={0.85}
              >
                <Text style={[s.registerBtnText, { color: colors.primary }]}>Create Account</Text>
              </TouchableOpacity>
            </View>

            <Text style={[s.disclaimer, { color: colors.mutedForeground }]}>
              By continuing, you agree to our Terms of Service and Privacy Policy.
            </Text>
          </ScrollView>
        </KeyboardAvoidingView>
      </View>
    );
  }

  const s = StyleSheet.create({
    screen: { flex: 1 },
    scroll: { flexGrow: 1, paddingHorizontal: 24 },
    logoArea: { alignItems: 'center', marginBottom: 36, gap: 6 },
    logoClip: { width: 110, height: 110, overflow: 'hidden' },
    logoImage: { width: 110, height: 200 },
    brandName: { fontSize: 22, fontFamily: 'Poppins_800ExtraBold', letterSpacing: -0.5, marginTop: 4 },
    tagline: { fontSize: 13, fontFamily: 'Poppins_400Regular', textAlign: 'center', color: '#888' },
    form: { gap: 10 },
    label: { fontSize: 13, fontFamily: 'Poppins_500Medium', marginLeft: 2 },
    passwordHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginLeft: 2 },
    forgotText: { fontSize: 13, fontFamily: 'Poppins_500Medium', color: '#FF6B35' },
    inputWrap: {
      flexDirection: 'row', alignItems: 'center', gap: 10,
      borderWidth: 1, borderRadius: 12, paddingHorizontal: 14, paddingVertical: 13,
      marginBottom: 8,
    },
    input: { flex: 1, fontSize: 15, fontFamily: 'Poppins_400Regular' },
    googleBtn: {
      flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 10,
      backgroundColor: '#fff', borderRadius: 14, paddingVertical: 14,
      marginBottom: 4, elevation: 2,
    },
    googleIconWrap: {
      width: 22, height: 22, borderRadius: 11, backgroundColor: '#EA4335',
      alignItems: 'center', justifyContent: 'center',
    },
    googleG: { color: '#fff', fontSize: 13, fontFamily: 'Poppins_700Bold' },
    googleBtnText: { fontSize: 15, fontFamily: 'Poppins_600SemiBold', color: '#333' },
    loginBtn: {
      borderRadius: 14, paddingVertical: 16, alignItems: 'center', marginTop: 6,
      elevation: 6,
    },
    loginBtnText: { color: '#fff', fontSize: 16, fontFamily: 'Poppins_700Bold' },
    dividerRow: { flexDirection: 'row', alignItems: 'center', gap: 12, marginVertical: 4 },
    divider: { flex: 1, height: 1 },
    dividerText: { fontSize: 12, fontFamily: 'Poppins_400Regular' },
    demoBtn: {
      flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 8,
      borderRadius: 14, paddingVertical: 14, borderWidth: 1.5, marginTop: 2,
    },
    demoBtnText: { fontSize: 15, fontFamily: 'Poppins_600SemiBold' },
    registerBtn: { borderRadius: 14, paddingVertical: 15, alignItems: 'center', borderWidth: 1.5 },
    registerBtnText: { fontSize: 15, fontFamily: 'Poppins_600SemiBold' },
    disclaimer: { fontSize: 11, fontFamily: 'Poppins_400Regular', textAlign: 'center', marginTop: 24, lineHeight: 16 },
  });
  