import { useState } from 'react';
import { router, useLocalSearchParams } from 'expo-router';
import { Text, TextInput, StyleSheet } from 'react-native';
import { useTranslation } from 'react-i18next';
import { Screen } from '../../src/components/Screen';
import { PrimaryButton } from '../../src/components/PrimaryButton';
import { StateView } from '../../src/components/StateView';
import { BackButton } from '../../src/components/BackButton';
import { api, ApiError } from '../../src/api/client';
import { color, radius, spacing, typography } from '../../src/theme';

export default function ResetPassword() {
  const { t } = useTranslation();
  const { email, code } = useLocalSearchParams<{ email?: string; code?: string }>();
  const [password, setPassword] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function onReset() {
    setError(null);
    if (!email || !code) {
      setError(t('auth.invalidCode'));
      return;
    }
    if (password.length < 8) {
      setError(t('auth.placeholderPassword'));
      return;
    }
    setSubmitting(true);
    try {
      await api.auth.resetPassword({ email, code, password });
      router.replace('/(auth)/login');
    } catch (e) {
      setError(e instanceof ApiError ? e.message : t('auth.networkError'));
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <Screen>
      <BackButton fallbackHref="/(auth)/login" />
      <Text style={styles.title}>{t('auth.resetTitle')}</Text>
      <Text style={styles.body}>{t('auth.resetBody')}</Text>
      <TextInput
        value={password}
        onChangeText={setPassword}
        placeholder={t('auth.password')}
        secureTextEntry
        style={styles.input}
      />
      {error ? <StateView tone="error" title={t('auth.signInFailed')} body={error} /> : null}
      <PrimaryButton label={submitting ? t('actions.saving') : t('auth.savePassword')} onPress={onReset} disabled={submitting} />
    </Screen>
  );
}

const styles = StyleSheet.create({
  title: { fontSize: typography.scale.h1.size, fontWeight: '700', color: color.ink[900] },
  body: { fontSize: typography.scale.body.size, color: color.ink[500] },
  input: {
    height: 52,
    borderRadius: radius.md,
    borderWidth: 1,
    borderColor: color.border,
    paddingHorizontal: spacing[4],
    backgroundColor: color.bg[0],
  },
});
