import React, { useState } from 'react';
import {
  View, Text, TextInput, TouchableOpacity, StyleSheet,
  Image, KeyboardAvoidingView, Platform, ActivityIndicator,
  ScrollView, Alert,
} from 'react-native';
import { useRouter } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { storage } from '../utils/storage';

const API_URL = process.env.EXPO_PUBLIC_BACKEND_URL;

export default function LoginScreen() {
  const router = useRouter();
  const [employeeId, setEmployeeId] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleLogin = async () => {
    if (!employeeId.trim() || !password.trim()) {
      setError('Please enter Employee ID and Password');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const res = await fetch(`${API_URL}/api/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ employee_id: employeeId.trim(), password: password }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.detail || 'Login failed');
        setLoading(false);
        return;
      }
      await storage.setItemAsync('token', data.token);
      await storage.setItemAsync('employee', JSON.stringify(data.employee));
      if (data.employee.role === 'admin') {
        router.replace('/admin');
      } else {
        router.replace('/dashboard');
      }
    } catch (e: any) {
      setError('Network error. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.safe}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.flex}
      >
        <ScrollView contentContainerStyle={styles.scroll} keyboardShouldPersistTaps="handled">
          <View style={styles.logoContainer}>
            <Image
              source={require('../assets/images/opel-logo.png')}
              style={styles.logo}
              resizeMode="contain"
            />
            <Text style={styles.brandName}>OPEL LIFTS</Text>
            <Text style={styles.tagline}>Attendance Management System</Text>
          </View>

          <View style={styles.formContainer}>
            <Text style={styles.label}>EMPLOYEE ID</Text>
            <TextInput
              testID="employee-id-input"
              style={styles.input}
              value={employeeId}
              onChangeText={setEmployeeId}
              placeholder="Enter Employee ID"
              placeholderTextColor="#6E6E6E"
              autoCapitalize="characters"
              autoCorrect={false}
            />

            <Text style={styles.label}>PASSWORD</Text>
            <TextInput
              testID="password-input"
              style={styles.input}
              value={password}
              onChangeText={setPassword}
              placeholder="Enter Password"
              placeholderTextColor="#6E6E6E"
              secureTextEntry
            />

            {error ? <Text testID="login-error" style={styles.errorText}>{error}</Text> : null}

            <TouchableOpacity
              testID="login-button"
              style={[styles.loginBtn, loading && styles.loginBtnDisabled]}
              onPress={handleLogin}
              disabled={loading}
              activeOpacity={0.7}
            >
              {loading ? (
                <ActivityIndicator color="#000" />
              ) : (
                <Text style={styles.loginBtnText}>LOGIN</Text>
              )}
            </TouchableOpacity>

            <TouchableOpacity
              testID="forgot-password-link"
              onPress={() => router.push('/forgot-password')}
              style={styles.forgotBtn}
            >
              <Text style={styles.forgotText}>Forgot Password?</Text>
            </TouchableOpacity>

            <TouchableOpacity
              testID="register-link"
              onPress={() => router.push('/register')}
              style={styles.registerLink}
            >
              <Text style={styles.registerLinkText}>
                New Employee? <Text style={styles.registerLinkAccent}>Register Here</Text>
              </Text>
            </TouchableOpacity>
          </View>

          <View style={styles.footer}>
            <Text style={styles.footerText}>Opel Lifts - The Specialifts</Text>
            <Text style={styles.footerText}>20+ Years of Experience</Text>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: '#050505' },
  flex: { flex: 1 },
  scroll: { flexGrow: 1, justifyContent: 'center', padding: 24 },
  logoContainer: { alignItems: 'center', marginBottom: 40 },
  logo: { width: 120, height: 80, marginBottom: 12 },
  brandName: {
    color: '#E5E7EB', fontSize: 28, fontWeight: '900',
    letterSpacing: 4,
  },
  tagline: { color: '#6E6E6E', fontSize: 14, marginTop: 4, letterSpacing: 1 },
  formContainer: { marginBottom: 32 },
  label: {
    color: '#B0B0B0', fontSize: 12, fontWeight: '600',
    letterSpacing: 1, marginBottom: 8,
  },
  input: {
    backgroundColor: '#121212', borderWidth: 1, borderColor: '#333',
    borderRadius: 4, padding: 16, color: '#FFF', fontSize: 16,
    marginBottom: 20,
  },
  errorText: { color: '#FF3D00', fontSize: 14, marginBottom: 16, textAlign: 'center' },
  loginBtn: {
    backgroundColor: '#00E5FF', borderRadius: 4, paddingVertical: 16,
    alignItems: 'center', shadowColor: '#00E5FF', shadowOpacity: 0.3,
    shadowRadius: 10, elevation: 5, marginTop: 8,
  },
  loginBtnDisabled: { opacity: 0.6 },
  loginBtnText: {
    color: '#000', fontWeight: '700', fontSize: 16,
    letterSpacing: 2,
  },
  forgotBtn: { alignItems: 'center', marginTop: 20, padding: 8 },
  forgotText: { color: '#00E5FF', fontSize: 14 },
  registerLink: { alignItems: 'center', marginTop: 12, padding: 8 },
  registerLinkText: { color: '#6E6E6E', fontSize: 14 },
  registerLinkAccent: { color: '#00E5FF', fontWeight: '600' },
  footer: { alignItems: 'center', marginTop: 20 },
  footerText: { color: '#475569', fontSize: 12, marginTop: 2 },
});
