import React, { useState } from 'react';
import { Alert, ScrollView, StyleSheet, Text, TouchableOpacity, View, Image } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useApp } from '../context/AppContext';
import { Button } from '../components/ui/Button';
import { Input } from '../components/ui/Input';
import { RootStackParamList } from '../navigation/types';
import { colors, radius, shadows } from '../lib/theme';

export default function AuthLogin() {
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const { login } = useApp();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async () => {
    setError('');
    if (!email.trim() || !password.trim()) {
      setError('Preenche email e palavra-passe');
      return;
    }
    try {
      setLoading(true);
      const nextUser = await login(email.trim(), password);
      if (!nextUser) {
        setError('Credenciais inválidas ou email não confirmado');
        return;
      }
    } catch (e: any) {
      const message = e?.message || 'Credenciais inválidas ou email não confirmado';
      setError(message);
      Alert.alert('Erro', message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
        <View style={styles.logoRow}>
          <Image 
            source={require('../../assets/logo.png')} 
            style={styles.logoImage} 
            resizeMode="contain"
          />
        </View>

        <Text style={styles.title}>Bem-vindo</Text>
        <Text style={styles.subtitle}>Aceda à sua conta Smart Agenda</Text>

        {!!error && (
          <View style={styles.errorBox}>
            <Text style={styles.errorText}>{error}</Text>
          </View>
        )}

        <Input
          label="Email"
          value={email}
          onChangeText={(text) => { setEmail(text); setError(''); }}
          keyboardType="email-address"
          autoCapitalize="none"
          placeholder="exemplo@email.com"
        />

        <Input
          label="Palavra-passe"
          value={password}
          onChangeText={(text) => { setPassword(text); setError(''); }}
          secureTextEntry
          placeholder="••••••••"
        />

        <Button variant="dark" onPress={handleSubmit} style={styles.submitButton} loading={loading}>
          Entrar na Conta
        </Button>

        <TouchableOpacity style={styles.guestButton} onPress={() => navigation.navigate('Explore')}>
          <Text style={styles.guestText}>Explorar sem conta</Text>
        </TouchableOpacity>

        <View style={styles.divider} />

        <View style={styles.footer}>
          <Text style={styles.footerText}>Ainda não tem conta? </Text>
          <Text style={styles.footerLink} onPress={() => navigation.navigate('Register')}>
            Criar conta grátis
          </Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {
    padding: 20,
    justifyContent: 'center',
    minHeight: '100%',
  },
  logoRow: {
    alignItems: 'center',
    marginBottom: 28,
    backgroundColor: colors.surfaceDark,
    borderRadius: radius.lg,
    paddingVertical: 18,
    paddingHorizontal: 24,
    ...shadows.card,
  },
  logoImage: {
    width: 240,
    height: 100,
  },
  title: {
    fontSize: 32,
    fontWeight: '900',
    color: colors.text,
    textAlign: 'center',
    marginBottom: 6,
  },
  subtitle: {
    fontSize: 15,
    color: colors.textMuted,
    marginBottom: 32,
    textAlign: 'center',
    fontWeight: '500',
  },
  errorBox: {
    backgroundColor: colors.dangerSoft,
    borderColor: '#fecaca',
    borderWidth: 1,
    borderRadius: radius.md,
    padding: 14,
    marginBottom: 16,
  },
  errorText: {
    color: '#991b1b',
    fontWeight: '600',
    fontSize: 13,
  },
  submitButton: {
    width: '100%',
    marginTop: 4,
    paddingVertical: 16,
  },
  guestButton: {
    alignSelf: 'center',
    marginTop: 16,
    paddingVertical: 10,
    paddingHorizontal: 16,
    borderRadius: radius.pill,
    backgroundColor: colors.surface,
    borderWidth: 1,
    borderColor: colors.border,
  },
  guestText: {
    color: colors.primaryDark,
    fontWeight: '700',
    fontSize: 14,
  },
  divider: {
    height: 1,
    backgroundColor: colors.border,
    marginVertical: 24,
  },
  footer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
  },
  footerText: {
    fontSize: 14,
    color: colors.textMuted,
  },
  footerLink: {
    fontSize: 14,
    color: colors.primaryDark,
    fontWeight: '800',
  },
});
