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 { MaterialCommunityIcons } from '@expo/vector-icons';

const API_URL = process.env.EXPO_PUBLIC_BACKEND_URL;

export default function RegisterScreen() {
  const router = useRouter();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [mobile, setMobile] = useState('');
  const [employeeId, setEmployeeId] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [successMsg, setSuccessMsg] = useState('');

  const handleRegister = async () => {
    setError('');
    if (!name.trim()) { setError('Name is required'); return; }
    if (!email.trim() || !email.includes('@')) { setError('Valid email is required'); return; }
    if (!mobile.trim() || mobile.trim().length < 10) { setError('Valid mobile number is required (min 10 digits)'); return; }
    if (!employeeId.trim()) { setError('Employee ID is required'); return; }
    if (password.length < 6) { setError('Password must be at least 6 characters'); return; }
    if (password !== confirmPassword) { setError('Passwords do not match'); return; }

    setLoading(true);
    try {
      const res = await fetch(`${API_URL}/api/auth/register`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.trim(),
          email: email.trim().toLowerCase(),
          mobile: mobile.trim(),
          employee_id: employeeId.trim(),
          password: password,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.detail || 'Registration failed');
      } else {
        setSuccessMsg(`Registration successful! Your Employee ID is ${data.employee_id}. Redirecting to login...`);
        setTimeout(() => router.replace('/'), 2500);
      }
    } catch (e) {
      setError('Network error. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.safe}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={{ flex: 1 }}
      >
        <ScrollView contentContainerStyle={styles.scroll} keyboardShouldPersistTaps="handled">
          <TouchableOpacity testID="register-back-btn" onPress={() => router.back()} style={styles.backBtn}>
            <MaterialCommunityIcons name="arrow-left" size={24} color="#00E5FF" />
            <Text style={styles.backText}>Back to Login</Text>
          </TouchableOpacity>

          <View style={styles.headerSection}>
            <Image
              source={require('../assets/images/opel-logo.png')}
              style={styles.logo}
              resizeMode="contain"
            />
            <Text style={styles.title}>Create Account</Text>
            <Text style={styles.subtitle}>Register as a new Opel Lifts employee</Text>
          </View>

          <View style={styles.formContainer}>
            <Text style={styles.label}>FULL NAME</Text>
            <TextInput
              testID="register-name-input"
              style={styles.input}
              value={name}
              onChangeText={setName}
              placeholder="Enter your full name"
              placeholderTextColor="#6E6E6E"
              autoCapitalize="words"
            />

            <Text style={styles.label}>EMAIL ID</Text>
            <TextInput
              testID="register-email-input"
              style={styles.input}
              value={email}
              onChangeText={setEmail}
              placeholder="Enter your email"
              placeholderTextColor="#6E6E6E"
              keyboardType="email-address"
              autoCapitalize="none"
              autoCorrect={false}
            />

            <Text style={styles.label}>MOBILE NUMBER</Text>
            <TextInput
              testID="register-mobile-input"
              style={styles.input}
              value={mobile}
              onChangeText={setMobile}
              placeholder="Enter mobile number"
              placeholderTextColor="#6E6E6E"
              keyboardType="phone-pad"
              maxLength={15}
            />

            <Text style={styles.label}>EMPLOYEE ID</Text>
            <TextInput
              testID="register-empid-input"
              style={styles.input}
              value={employeeId}
              onChangeText={setEmployeeId}
              placeholder="Enter Employee ID (e.g. EMP004)"
              placeholderTextColor="#6E6E6E"
              autoCapitalize="characters"
              autoCorrect={false}
            />

            <Text style={styles.label}>PASSWORD</Text>
            <TextInput
              testID="register-password-input"
              style={styles.input}
              value={password}
              onChangeText={setPassword}
              placeholder="Create a password (min 6 chars)"
              placeholderTextColor="#6E6E6E"
              secureTextEntry
            />

            <Text style={styles.label}>CONFIRM PASSWORD</Text>
            <TextInput
              testID="register-confirm-input"
              style={styles.input}
              value={confirmPassword}
              onChangeText={setConfirmPassword}
              placeholder="Re-enter password"
              placeholderTextColor="#6E6E6E"
              secureTextEntry
            />

            {error ? <Text testID="register-error" style={styles.errorText}>{error}</Text> : null}
            {successMsg ? (
              <View testID="register-success" style={styles.successBanner}>
                <MaterialCommunityIcons name="check-circle" size={20} color="#00C853" />
                <Text style={styles.successText}>{successMsg}</Text>
              </View>
            ) : null}

            <TouchableOpacity
              testID="register-submit-btn"
              style={[styles.registerBtn, loading && styles.registerBtnDisabled]}
              onPress={handleRegister}
              disabled={loading}
              activeOpacity={0.7}
            >
              {loading ? (
                <ActivityIndicator color="#000" />
              ) : (
                <Text style={styles.registerBtnText}>REGISTER</Text>
              )}
            </TouchableOpacity>

            <TouchableOpacity
              testID="go-login-link"
              onPress={() => router.replace('/')}
              style={styles.loginLink}
            >
              <Text style={styles.loginLinkText}>
                Already have an account? <Text style={styles.loginLinkAccent}>Login</Text>
              </Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: '#050505' },
  scroll: { flexGrow: 1, padding: 24, paddingBottom: 40 },
  backBtn: { flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 24 },
  backText: { color: '#00E5FF', fontSize: 14 },
  headerSection: { alignItems: 'center', marginBottom: 32 },
  logo: { width: 80, height: 54, marginBottom: 12 },
  title: { color: '#FFF', fontSize: 26, fontWeight: '700' },
  subtitle: { color: '#6E6E6E', fontSize: 14, marginTop: 4 },
  formContainer: {},
  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: 16,
  },
  errorText: { color: '#FF3D00', fontSize: 14, marginBottom: 16, textAlign: 'center' },
  successBanner: {
    backgroundColor: '#0A2E0A', borderLeftWidth: 4, borderLeftColor: '#00C853',
    padding: 14, marginBottom: 16, borderRadius: 2,
    flexDirection: 'row', alignItems: 'center', gap: 10,
  },
  successText: { color: '#00C853', fontSize: 14, flex: 1 },
  registerBtn: {
    backgroundColor: '#00E5FF', borderRadius: 4, paddingVertical: 16,
    alignItems: 'center', marginTop: 8,
    shadowColor: '#00E5FF', shadowOpacity: 0.3, shadowRadius: 10, elevation: 5,
  },
  registerBtnDisabled: { opacity: 0.6 },
  registerBtnText: {
    color: '#000', fontWeight: '700', fontSize: 16, letterSpacing: 2,
  },
  loginLink: { alignItems: 'center', marginTop: 24, padding: 8 },
  loginLinkText: { color: '#6E6E6E', fontSize: 14 },
  loginLinkAccent: { color: '#00E5FF', fontWeight: '600' },
});
