import React, { useState, useCallback } from 'react';
import {
  View, Text, TextInput, TouchableOpacity, StyleSheet,
  ScrollView, KeyboardAvoidingView, Platform, ActivityIndicator, Alert, Image,
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons } from '@expo/vector-icons';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useTheme } from '../../theme/ThemeContext';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { login, clearError } from '../../store/slices/authSlice';
import { AuthStackParams } from '../../navigation/AuthNavigator';

type Props = { navigation: NativeStackNavigationProp<AuthStackParams, 'Login'> };

export default function LoginScreen({ navigation }: Props) {
  const { theme } = useTheme();
  const dispatch = useAppDispatch();
  const { isLoading, error } = useAppSelector((s) => s.auth);

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [errors, setErrors] = useState<{ email?: string; password?: string }>({});

  const validate = () => {
    const e: typeof errors = {};
    if (!email) e.email = 'Email is required';
    else if (!/\S+@\S+\.\S+/.test(email)) e.email = 'Enter a valid email';
    if (!password) e.password = 'Password is required';
    else if (password.length < 8) e.password = 'At least 8 characters';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleLogin = useCallback(async () => {
    if (!validate()) return;
    dispatch(clearError());
    const result = await dispatch(login({ email: email.trim(), password }));
    if (login.rejected.match(result)) {
      Alert.alert('Login Failed', result.payload as string);
    }
  }, [email, password]);

  const s = styles(theme);

  return (
    <LinearGradient
      colors={[theme.colors.background, theme.colors.background]}
      style={s.container}
    >
      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={{ flex: 1 }}>
        <ScrollView contentContainerStyle={s.scroll} keyboardShouldPersistTaps="handled">
          {/* Header */}
          <View style={s.header}>
            <View style={s.logoContainer}>
              <Image
                source={require('../../../assets/icon.png')}
                style={s.logo}
                resizeMode="contain"
              />
            </View>
            <Text style={s.brand}>Mint Vault</Text>
            <Text style={s.tagline}>Your African Finance Hub</Text>
          </View>

          {/* Form card */}
          <View style={s.card}>
            <Text style={s.title}>Welcome back</Text>
            <Text style={s.subtitle}>Sign in to continue</Text>

            {/* Email */}
            <View style={s.inputGroup}>
              <Text style={s.label}>Email</Text>
              <View style={[s.inputWrap, errors.email ? s.inputError : null]}>
                <Ionicons name="mail-outline" size={20} color={theme.colors.textSecondary} style={s.inputIcon} />
                <TextInput
                  style={s.input}
                  placeholder="you@example.com"
                  placeholderTextColor={theme.colors.textTertiary}
                  value={email}
                  onChangeText={setEmail}
                  keyboardType="email-address"
                  autoCapitalize="none"
                  autoCorrect={false}
                />
              </View>
              {errors.email && <Text style={s.errorText}>{errors.email}</Text>}
            </View>

            {/* Password */}
            <View style={s.inputGroup}>
              <Text style={s.label}>Password</Text>
              <View style={[s.inputWrap, errors.password ? s.inputError : null]}>
                <Ionicons name="lock-closed-outline" size={20} color={theme.colors.textSecondary} style={s.inputIcon} />
                <TextInput
                  style={s.input}
                  placeholder="••••••••"
                  placeholderTextColor={theme.colors.textTertiary}
                  value={password}
                  onChangeText={setPassword}
                  secureTextEntry={!showPassword}
                  autoCapitalize="none"
                />
                <TouchableOpacity onPress={() => setShowPassword((v) => !v)} style={s.eyeBtn}>
                  <Ionicons name={showPassword ? 'eye-off-outline' : 'eye-outline'} size={20} color={theme.colors.textSecondary} />
                </TouchableOpacity>
              </View>
              {errors.password && <Text style={s.errorText}>{errors.password}</Text>}
            </View>

            <TouchableOpacity
              onPress={() => navigation.navigate('ForgotPassword')}
              style={s.forgotBtn}
            >
              <Text style={s.forgotText}>Forgot password?</Text>
            </TouchableOpacity>

            {/* Login button */}
            <TouchableOpacity onPress={handleLogin} disabled={isLoading} activeOpacity={0.85}>
              <LinearGradient
                colors={[theme.colors.primary, theme.colors.primaryDark]}
                style={s.loginBtn}
                start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
              >
                {isLoading
                  ? <ActivityIndicator color="#fff" />
                  : <Text style={s.loginBtnText}>Sign In</Text>}
              </LinearGradient>
            </TouchableOpacity>

            <View style={s.divider}>
              <View style={s.dividerLine} />
              <Text style={s.dividerText}>or</Text>
              <View style={s.dividerLine} />
            </View>

            <TouchableOpacity
              onPress={() => navigation.navigate('Register')}
              style={s.registerBtn}
            >
              <Text style={s.registerBtnText}>Create an account</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </LinearGradient>
  );
}

const styles = (theme: any) =>
  StyleSheet.create({
    container: { flex: 1 },
    scroll: { flexGrow: 1, justifyContent: 'center', paddingHorizontal: 20, paddingVertical: 40 },
    header: { alignItems: 'center', marginBottom: 32 },
    logoContainer: { marginBottom: 12 },
    logo: { width: 72, height: 72, borderRadius: 16 },
    brand: { fontSize: 28, fontWeight: '800', color: theme.colors.text, letterSpacing: -0.5 },
    tagline: { fontSize: 14, color: theme.colors.textSecondary, marginTop: 4 },
    card: {
      backgroundColor: theme.colors.surface, borderRadius: 24,
      padding: 24, shadowColor: theme.colors.shadow,
      shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.08,
      shadowRadius: 16, elevation: 4,
    },
    title: { fontSize: 24, fontWeight: '700', color: theme.colors.text, marginBottom: 4 },
    subtitle: { fontSize: 14, color: theme.colors.textSecondary, marginBottom: 24 },
    inputGroup: { marginBottom: 16 },
    label: { fontSize: 13, fontWeight: '600', color: theme.colors.text, marginBottom: 6 },
    inputWrap: {
      flexDirection: 'row', alignItems: 'center',
      backgroundColor: theme.colors.surfaceAlt, borderRadius: 12,
      borderWidth: 1.5, borderColor: theme.colors.border,
    },
    inputError: { borderColor: theme.colors.error },
    inputIcon: { marginLeft: 14 },
    input: {
      flex: 1, height: 52, paddingHorizontal: 12,
      fontSize: 15, color: theme.colors.text,
    },
    eyeBtn: { padding: 14 },
    errorText: { fontSize: 12, color: theme.colors.error, marginTop: 4, marginLeft: 2 },
    forgotBtn: { alignSelf: 'flex-end', marginBottom: 20, marginTop: -4 },
    forgotText: { fontSize: 13, color: theme.colors.primary, fontWeight: '600' },
    loginBtn: {
      height: 54, borderRadius: 14, alignItems: 'center',
      justifyContent: 'center', shadowColor: theme.colors.primary,
      shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.3, shadowRadius: 8, elevation: 4,
    },
    loginBtnText: { fontSize: 16, fontWeight: '700', color: '#fff', letterSpacing: 0.3 },
    divider: { flexDirection: 'row', alignItems: 'center', marginVertical: 20 },
    dividerLine: { flex: 1, height: 1, backgroundColor: theme.colors.border },
    dividerText: { marginHorizontal: 12, fontSize: 13, color: theme.colors.textTertiary },
    registerBtn: {
      height: 54, borderRadius: 14, alignItems: 'center', justifyContent: 'center',
      borderWidth: 1.5, borderColor: theme.colors.primary,
    },
    registerBtnText: { fontSize: 16, fontWeight: '600', color: theme.colors.primary },
  });
