import React, { useState } from 'react';
import {
  View, Text, TextInput, TouchableOpacity, StyleSheet,
  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 ForgotPasswordScreen() {
  const router = useRouter();
  const [step, setStep] = useState<'request' | 'reset'>('request');
  const [employeeId, setEmployeeId] = useState('');
  const [resetToken, setResetToken] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [tokenDisplay, setTokenDisplay] = useState('');

  const handleRequest = async () => {
    if (!employeeId.trim()) { setError('Enter your Employee ID'); return; }
    setLoading(true); setError('');
    try {
      const res = await fetch(`${API_URL}/api/auth/forgot-password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ employee_id: employeeId.trim() }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.detail || 'Request failed'); }
      else {
        setTokenDisplay(data.reset_token);
        setStep('reset');
      }
    } catch (e) { setError('Network error'); }
    finally { setLoading(false); }
  };

  const handleReset = async () => {
    if (!resetToken.trim()) { setError('Enter the reset token'); return; }
    if (newPassword.length < 6) { setError('Password must be at least 6 characters'); return; }
    if (newPassword !== confirmPassword) { setError('Passwords do not match'); return; }
    setLoading(true); setError('');
    try {
      const res = await fetch(`${API_URL}/api/auth/reset-password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          employee_id: employeeId.trim(),
          reset_token: resetToken.trim(),
          new_password: newPassword,
        }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.detail || 'Reset failed'); }
      else {
        Alert.alert('Success', 'Password reset successful. Please login.', [
          { text: 'OK', onPress: () => router.replace('/') }
        ]);
      }
    } catch (e) { setError('Network error'); }
    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="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>

          <Text style={styles.title}>
            {step === 'request' ? 'Forgot Password' : 'Reset Password'}
          </Text>
          <Text style={styles.subtitle}>
            {step === 'request'
              ? 'Enter your Employee ID to get a reset token'
              : 'Enter the reset token and your new password'}
          </Text>

          {step === 'request' ? (
            <View style={styles.form}>
              <Text style={styles.label}>EMPLOYEE ID</Text>
              <TextInput
                testID="forgot-emp-id"
                style={styles.input}
                value={employeeId}
                onChangeText={setEmployeeId}
                placeholder="Enter Employee ID"
                placeholderTextColor="#6E6E6E"
                autoCapitalize="characters"
              />
              {error ? <Text style={styles.errorText}>{error}</Text> : null}
              <TouchableOpacity testID="request-reset-btn" style={styles.btn} onPress={handleRequest} disabled={loading}>
                {loading ? <ActivityIndicator color="#000" /> : <Text style={styles.btnText}>REQUEST RESET</Text>}
              </TouchableOpacity>
            </View>
          ) : (
            <View style={styles.form}>
              {tokenDisplay ? (
                <View style={styles.tokenCard}>
                  <MaterialCommunityIcons name="key" size={20} color="#00E5FF" />
                  <Text style={styles.tokenLabel}>Your Reset Token:</Text>
                  <Text testID="reset-token-display" style={styles.tokenValue} selectable>{tokenDisplay}</Text>
                  <Text style={styles.tokenHint}>In production, this would be sent via email/SMS</Text>
                </View>
              ) : null}

              <Text style={styles.label}>RESET TOKEN</Text>
              <TextInput
                testID="reset-token-input"
                style={styles.input}
                value={resetToken}
                onChangeText={setResetToken}
                placeholder="Paste reset token"
                placeholderTextColor="#6E6E6E"
              />
              <Text style={styles.label}>NEW PASSWORD</Text>
              <TextInput
                testID="new-password-input"
                style={styles.input}
                value={newPassword}
                onChangeText={setNewPassword}
                placeholder="New password"
                placeholderTextColor="#6E6E6E"
                secureTextEntry
              />
              <Text style={styles.label}>CONFIRM PASSWORD</Text>
              <TextInput
                testID="confirm-password-input"
                style={styles.input}
                value={confirmPassword}
                onChangeText={setConfirmPassword}
                placeholder="Confirm password"
                placeholderTextColor="#6E6E6E"
                secureTextEntry
              />
              {error ? <Text style={styles.errorText}>{error}</Text> : null}
              <TouchableOpacity testID="reset-password-btn" style={styles.btn} onPress={handleReset} disabled={loading}>
                {loading ? <ActivityIndicator color="#000" /> : <Text style={styles.btnText}>RESET PASSWORD</Text>}
              </TouchableOpacity>
            </View>
          )}
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: '#050505' },
  scroll: { flexGrow: 1, padding: 24 },
  backBtn: { flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 32 },
  backText: { color: '#00E5FF', fontSize: 14 },
  title: { color: '#FFF', fontSize: 28, fontWeight: '700', marginBottom: 8 },
  subtitle: { color: '#6E6E6E', fontSize: 14, marginBottom: 32 },
  form: {},
  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' },
  btn: {
    backgroundColor: '#00E5FF', borderRadius: 4, paddingVertical: 16,
    alignItems: 'center', marginTop: 8,
  },
  btnText: { color: '#000', fontWeight: '700', fontSize: 16, letterSpacing: 2 },
  tokenCard: {
    backgroundColor: '#121212', borderLeftWidth: 4, borderLeftColor: '#00E5FF',
    padding: 16, marginBottom: 24, borderRadius: 2,
  },
  tokenLabel: { color: '#B0B0B0', fontSize: 12, marginTop: 8 },
  tokenValue: { color: '#00E5FF', fontSize: 14, fontWeight: '600', marginTop: 4 },
  tokenHint: { color: '#6E6E6E', fontSize: 11, marginTop: 8, fontStyle: 'italic' },
});
