import { useLocalSearchParams, router } from 'expo-router';
import { useState } from 'react';
import { Alert, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import { ScreenHeader } from '../../src/components/ScreenHeader';
import { FormScreen } from '../../src/components/FormScreen';
import { api } from '../../src/lib/api';
import axios from 'axios';

export default function ResetPasswordScreen() {
  const params = useLocalSearchParams<{ token?: string }>();
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async () => {
    if (!params.token) {
      Alert.alert('Missing token', 'Reset token was not provided.');
      return;
    }
    if (!newPassword || !confirmPassword) {
      Alert.alert('Missing fields', 'Please enter and confirm your new password.');
      return;
    }

    try {
      setLoading(true);
      const response = await api.post('/auth/reset-password', {
        token: params.token,
        new_password: newPassword,
        confirm_password: confirmPassword,
      });
      console.log('RESET_PASSWORD_OK', response.data);
      Alert.alert('Success', response.data?.message ?? 'Password updated');
      router.replace('/auth/login');
    } catch (error: any) {
      const message = axios.isAxiosError(error)
        ? error.response?.data?.message ?? error.message ?? 'Unable to reset password.'
        : 'Unable to reset password.';
      console.log('RESET_PASSWORD_FAIL', { message, status: error?.response?.status, data: error?.response?.data });
      Alert.alert('Reset failed', message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <FormScreen contentStyle={styles.content}>
      <View style={styles.container}>
        <ScreenHeader title="Reset password" subtitle="Set a new password for your PPay account." />
        <View style={styles.card}>
          <TextInput placeholder="New password" placeholderTextColor="#80978D" style={styles.input} secureTextEntry value={newPassword} onChangeText={setNewPassword} />
          <TextInput placeholder="Confirm password" placeholderTextColor="#80978D" style={styles.input} secureTextEntry value={confirmPassword} onChangeText={setConfirmPassword} />
          <Pressable style={styles.button} onPress={handleSubmit} disabled={loading}>
            <Text style={styles.buttonText}>{loading ? 'Updating...' : 'Reset Password'}</Text>
          </Pressable>
        </View>
      </View>
    </FormScreen>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#F4FAF7', padding: 24, paddingTop: 16 },
  content: { flexGrow: 1 },
  card: { backgroundColor: '#FFFFFF', borderRadius: 28, padding: 24, borderWidth: 1, borderColor: '#D8E7DF' },
  input: { backgroundColor: '#F3F8F5', borderRadius: 16, paddingHorizontal: 16, paddingVertical: 15, fontSize: 16, marginBottom: 12, color: '#062117' },
  button: { backgroundColor: '#0F5132', borderRadius: 16, alignItems: 'center', paddingVertical: 16, marginTop: 6 },
  buttonText: { color: '#FFFFFF', fontSize: 16, fontWeight: '800' },
});
