import axios from 'axios';
import { useRouter } from 'expo-router';
import * as SecureStore from 'expo-secure-store';
import { StatusBar } from 'expo-status-bar';
import React, { useState } from "react";
import { ActivityIndicator, Alert, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";

const PRIMARY = '#A24BFA';
const BG = '#0c0a0a';

export default function Index() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  async function handleLogin() {
    setLoading(true);
    console.log('Login attempt:', username);
    try {
      const response = await axios.post(
        "https://mymenu.mcdonalds.hu/api/AccountApi/Login",
        {
          Data: {
            UserName: username,
            Password: password
          }
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'referer': 'https://mymenu.mcdonalds.hu/',
            'origin': 'https://mymenu.mcdonalds.hu'
          }
        }
      );
      console.log('Login response:', response.data, response.headers);
      const cookie = response.headers['set-cookie']?.join('; ');
      const userId = response.data.Data.UserID;
      const fullName = response.data.Data.FullName;
      await SecureStore.setItemAsync('cookie', cookie || '');
      await SecureStore.setItemAsync('userId', String(userId));
      await SecureStore.setItemAsync('email', username);
      await SecureStore.setItemAsync('password', password);
      await SecureStore.setItemAsync('fullName', fullName || '');
      console.log('Saved to SecureStore:', { cookie, userId, username, password, fullName });
      router.replace('/profile');
    } catch (e) {
      console.log('Login error:', e);
      Alert.alert('Hiba', 'Hibás felhasználónév vagy jelszó, vagy hálózati hiba.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <View style={styles.container}>
      <StatusBar style="light" backgroundColor={BG} />
      <View style={styles.card}>
        <Text style={styles.title}>Üdv újra</Text>
        <Text style={styles.subtitle}>Jelentkezz be a mymenu fiókodba</Text>
        <View style={{ height: 24 }} />
        <Text style={styles.label}>Felhasználónév</Text>
        <TextInput
          style={styles.input}
          placeholder="valaki@gmail.com"
          placeholderTextColor="#aaa"
          value={username}
          onChangeText={setUsername}
          autoCapitalize="none"
        />
        <View style={{ height: 16 }} />
        <Text style={styles.label}>Jelszó</Text>
        <TextInput
          style={styles.input}
          placeholder="••••••••"
          placeholderTextColor="#aaa"
          value={password}
          onChangeText={setPassword}
          secureTextEntry
        />
        <View style={{ height: 24 }} />
        <TouchableOpacity style={styles.button} onPress={handleLogin} disabled={loading}>
          {loading ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <Text style={styles.buttonText}>Bejelentkezés</Text>
          )}
        </TouchableOpacity>
      </View>
    </View>
  );
}

export const options = {
  headerShown: false,
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: BG,
    justifyContent: 'center',
    alignItems: 'center',
  },
  card: {
    width: '90%',
    maxWidth: 400,
    backgroundColor: 'rgba(24, 20, 28, 0.95)',
    borderRadius: 24,
    padding: 32,
    shadowColor: '#000',
    shadowOpacity: 0.3,
    shadowRadius: 24,
    shadowOffset: { width: 0, height: 8 },
    elevation: 8,
  },
  title: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 28,
    textAlign: 'center',
    marginBottom: 4,
  },
  subtitle: {
    color: '#bdbdbd',
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 8,
  },
  label: {
    color: '#bdbdbd',
    fontSize: 14,
    marginBottom: 4,
  },
  input: {
    backgroundColor: 'rgba(20,18,24,1)',
    borderColor: PRIMARY,
    borderWidth: 1,
    borderRadius: 12,
    color: '#fff',
    paddingHorizontal: 16,
    paddingVertical: 12,
    fontSize: 16,
  },
  button: {
    backgroundColor: PRIMARY,
    borderRadius: 12,
    paddingVertical: 14,
    alignItems: 'center',
    marginTop: 8,
    shadowColor: PRIMARY,
    shadowOpacity: 0.3,
    shadowRadius: 8,
    shadowOffset: { width: 0, height: 2 },
    elevation: 2,
  },
  buttonText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 18,
  },
});