/**
 * Login screen — email/password + magic link.
 * Branded with tenant theme.
 */

import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTheme } from '../../themes/ThemeProvider';
import { login, getProfile } from '../../services/api';
import { setToken, setStoredUser, AuthUser } from '../../services/auth';

interface LoginScreenProps {
  onLogin: () => void;
}

export default function LoginScreen({ onLogin }: LoginScreenProps) {
  const { theme } = useTheme();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);

  const handleLogin = async () => {
    if (!email.trim() || !password.trim()) {
      Alert.alert('Required', 'Enter email and password');
      return;
    }

    setLoading(true);
    const res = await login(email.trim(), password.trim());

    if (res.success && res.data) {
      const { token } = res.data as { token: string };
      await setToken(token);

      // Fetch user profile
      const profileRes = await getProfile();
      if (profileRes.success && profileRes.data) {
        await setStoredUser(profileRes.data as AuthUser);
      }

      setLoading(false);
      onLogin();
    } else {
      setLoading(false);
      Alert.alert('Login Failed', res.error ?? 'Invalid credentials');
    }
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.colors.primary }]}>
      <KeyboardAvoidingView
        style={styles.container}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      >
        <View style={styles.header}>
          <Text style={[styles.logo, { color: theme.colors.white }]}>
            {theme.tenant?.name ?? 'Fogbreak'}
          </Text>
          <Text style={[styles.tagline, { color: theme.colors.accent }]}>
            Real Estate Operating System
          </Text>
        </View>

        <View style={[styles.form, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.formTitle, { color: theme.colors.text }]}>Sign In</Text>

          <TextInput
            style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
            value={email}
            onChangeText={setEmail}
            placeholder="Email"
            placeholderTextColor={theme.colors.textSecondary}
            keyboardType="email-address"
            autoCapitalize="none"
            autoCorrect={false}
            autoFocus
          />

          <TextInput
            style={[styles.input, { color: theme.colors.text, backgroundColor: theme.colors.inputBg, borderColor: theme.colors.border }]}
            value={password}
            onChangeText={setPassword}
            placeholder="Password"
            placeholderTextColor={theme.colors.textSecondary}
            secureTextEntry
          />

          <TouchableOpacity
            style={[styles.loginBtn, { backgroundColor: theme.colors.primary, opacity: loading ? 0.6 : 1 }]}
            onPress={handleLogin}
            disabled={loading}
          >
            <Text style={styles.loginBtnText}>{loading ? 'Signing in...' : 'Sign In'}</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.magicLink}>
            <Text style={[styles.magicLinkText, { color: theme.colors.accent }]}>
              Sign in with magic link
            </Text>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  container: { flex: 1, justifyContent: 'center', padding: 24 },
  header: { alignItems: 'center', marginBottom: 32 },
  logo: { fontSize: 36, fontWeight: '800', letterSpacing: 1 },
  tagline: { fontSize: 14, marginTop: 6, fontWeight: '500' },
  form: { borderRadius: 16, padding: 24 },
  formTitle: { fontSize: 22, fontWeight: '700', marginBottom: 20 },
  input: {
    height: 48,
    borderRadius: 10,
    borderWidth: 1,
    paddingHorizontal: 16,
    fontSize: 16,
    marginBottom: 14,
  },
  loginBtn: {
    height: 52,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 8,
  },
  loginBtnText: { color: '#FFF', fontSize: 17, fontWeight: '700' },
  magicLink: { alignItems: 'center', marginTop: 16 },
  magicLinkText: { fontSize: 14, fontWeight: '600' },
});
