import { useState } from 'react';
import { Alert } from 'react-native';
import { router } from 'expo-router';
import { Pressable, SafeAreaView, StyleSheet, Text, TextInput, View } from 'react-native';
import { ScreenHeader } from '../../src/components/ScreenHeader';
import { api } from '../../src/lib/api';
import axios from 'axios';
import { saveSession, setSessionLocked } from '../../src/lib/session';

export default function LoginScreen() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);

  const handleLogin = async () => {
    if (!email || !password) {
      Alert.alert('Missing fields', 'Please enter your email and password.');
      return;
    }

    try {
      setLoading(true);
      const response = await api.post('/auth/login', { email, password });
      const customer = response.data?.data?.customer;
      const tokens = response.data?.data?.tokens;
      if (customer) {
        await saveSession({
          customer,
          tokens: {
            ...tokens,
            access_expires_at: new Date(Date.now() + (tokens?.expires_in ?? 900) * 1000).toISOString(),
            refresh_expires_at: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
          },
          biometric_enabled: false,
          session_locked: false,
        });
        await setSessionLocked(false);
      }
      router.replace('/(app)/dashboard');
      console.log('LOGIN_OK', response.data);
    } catch (error: any) {
      const message = axios.isAxiosError(error)
        ? error.response?.data?.message ?? error.message ?? 'Unable to sign in right now.'
        : 'Unable to sign in right now.';
      console.log('LOGIN_FAIL', {
        message,
        status: error?.response?.status,
        data: error?.response?.data,
      });
      Alert.alert('Login failed', message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content}>
        <ScreenHeader
          title="Sign in to PPayng"
          subtitle="Enter your username and password to continue."
        />
        <View style={styles.card}>
          <TextInput placeholder="Username or Email" placeholderTextColor="#80978D" style={styles.input} keyboardType="email-address" value={email} onChangeText={setEmail} autoCapitalize="none" />
          <TextInput placeholder="Password" placeholderTextColor="#80978D" style={styles.input} secureTextEntry value={password} onChangeText={setPassword} />
          <Pressable style={styles.button} onPress={handleLogin} disabled={loading}>
            <Text style={styles.buttonText}>{loading ? 'Signing in...' : 'Continue'}</Text>
          </Pressable>
          <Pressable onPress={() => router.push('/auth/forgot-password')} style={styles.linkButton}>
            <Text style={styles.linkText}>Forgot password?</Text>
          </Pressable>
          <Pressable onPress={() => router.push('/auth/register')} style={styles.linkButton}>
            <Text style={styles.linkText}>New here? Create an account</Text>
          </Pressable>
        </View>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#F4FAF7' },
  content: { flex: 1, padding: 24, paddingTop: 16 },
  card: { backgroundColor: '#FFFFFF', borderRadius: 28, padding: 24, borderWidth: 1, borderColor: '#D8E7DF' },
  input: { backgroundColor: '#F3F8F5', borderRadius: 16, paddingHorizontal: 16, paddingVertical: 15, fontSize: 16, marginBottom: 12, color: '#062117' },
  button: { backgroundColor: '#0F5132', borderRadius: 16, alignItems: 'center', paddingVertical: 16, marginTop: 6 },
  buttonText: { color: '#FFFFFF', fontSize: 16, fontWeight: '800' },
  linkButton: { alignItems: 'center', paddingVertical: 16, marginTop: 4 },
  linkText: { color: '#0F5132', fontSize: 14, fontWeight: '700' },
});
