/*
 * 비밀번호 찾기/초기화 — 04_backend_public_auth.md §2·§3. 공개 경로.
 * 1단계: 이메일로 재설정 코드 요청(항상 200, 사용자 열거 방지).
 * 2단계: 이메일+코드+새 비밀번호로 초기화.
 */
import { router } from 'expo-router';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { KeyboardAvoidingView, Platform, ScrollView, StyleSheet, Text } from 'react-native';
import { Banner } from '../components/Banner';
import { Button } from '../components/Button';
import { Field } from '../components/Field';
import { ApiRequestError } from '../lib/api';
import { forgotPassword, resetPassword } from '../lib/auth';
import { colors, spacing, type } from '../theme';

export default function ForgotPasswordScreen() {
  const { t } = useTranslation();
  const [step, setStep] = useState<1 | 2>(1);
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [info, setInfo] = useState<string | null>(null);

  async function onRequest() {
    setError(null);
    setInfo(null);
    if (!email.trim()) {
      setError(t('forgot.errEmail'));
      return;
    }
    setLoading(true);
    try {
      const res = await forgotPassword(email);
      setInfo(res.message);
      setStep(2);
    } catch (e) {
      setError(e instanceof ApiRequestError ? e.message : t('forgot.errRequest'));
    } finally {
      setLoading(false);
    }
  }

  async function onReset() {
    setError(null);
    if (!code.trim() || newPassword.length < 8) {
      setError(t('forgot.errFields'));
      return;
    }
    setLoading(true);
    try {
      const res = await resetPassword(email, code, newPassword);
      setInfo(res.message);
      setTimeout(() => router.replace('/login'), 800);
    } catch (e) {
      if (e instanceof ApiRequestError && e.code === 'OTP_INVALID') {
        setError(t('forgot.errCode'));
      } else {
        setError(e instanceof ApiRequestError ? e.message : t('forgot.errReset'));
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <KeyboardAvoidingView
      style={styles.flex}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ScrollView contentContainerStyle={styles.scroll} keyboardShouldPersistTaps="handled">
        <Text style={styles.title}>{t('forgot.title')}</Text>
        {error ? <Banner tone="error">{error}</Banner> : null}
        {info ? <Banner tone="info">{info}</Banner> : null}

        <Field
          label={t('forgot.email')}
          value={email}
          onChangeText={setEmail}
          placeholder={t('forgot.emailPlaceholder')}
          keyboardType="email-address"
          editable={step === 1}
        />

        {step === 1 ? (
          <Button label={t('forgot.request')} onPress={onRequest} loading={loading} />
        ) : (
          <>
            <Field
              label={t('forgot.code')}
              value={code}
              onChangeText={setCode}
              placeholder={t('forgot.codePlaceholder')}
              keyboardType="number-pad"
            />
            <Field
              label={t('forgot.newPassword')}
              value={newPassword}
              onChangeText={setNewPassword}
              placeholder={t('forgot.newPasswordPlaceholder')}
              secureTextEntry
              helperText={t('forgot.newPasswordHelper')}
            />
            <Button label={t('forgot.submit')} onPress={onReset} loading={loading} />
          </>
        )}
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1, backgroundColor: colors.neutral050 },
  scroll: { padding: spacing.md, gap: spacing.md, paddingBottom: spacing.xl },
  title: { fontSize: type.h2.fontSize, fontWeight: '700', color: colors.neutral900 },
});
