/*
 * 비밀번호 찾기/초기화 — 04_backend_public_auth.md §2·§3. 공개 경로.
 * 1단계: 이메일로 재설정 코드 요청(항상 200, 사용자 열거 방지).
 * 2단계: 이메일+코드+새 비밀번호로 초기화.
 */
import { router } from 'expo-router';
import React, { useState } from 'react';
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 [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('이메일을 입력해 주세요.');
      return;
    }
    setLoading(true);
    try {
      const res = await forgotPassword(email);
      setInfo(res.message);
      setStep(2);
    } catch (e) {
      setError(e instanceof ApiRequestError ? e.message : '요청에 실패했습니다.');
    } finally {
      setLoading(false);
    }
  }

  async function onReset() {
    setError(null);
    if (!code.trim() || newPassword.length < 8) {
      setError('재설정 코드와 새 비밀번호(8자 이상)를 확인해 주세요.');
      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('재설정 코드가 올바르지 않거나 만료되었습니다.');
      } else {
        setError(e instanceof ApiRequestError ? e.message : '초기화에 실패했습니다.');
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <KeyboardAvoidingView
      style={styles.flex}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ScrollView contentContainerStyle={styles.scroll} keyboardShouldPersistTaps="handled">
        <Text style={styles.title}>비밀번호 재설정</Text>
        {error ? <Banner tone="error">{error}</Banner> : null}
        {info ? <Banner tone="info">{info}</Banner> : null}

        <Field
          label="이메일"
          value={email}
          onChangeText={setEmail}
          placeholder="name@company.co.kr"
          keyboardType="email-address"
          editable={step === 1}
        />

        {step === 1 ? (
          <Button label="재설정 코드 요청" onPress={onRequest} loading={loading} />
        ) : (
          <>
            <Field
              label="재설정 코드"
              value={code}
              onChangeText={setCode}
              placeholder="6자리 코드"
              keyboardType="number-pad"
            />
            <Field
              label="새 비밀번호"
              value={newPassword}
              onChangeText={setNewPassword}
              placeholder="8자 이상"
              secureTextEntry
              helperText="8~100자"
            />
            <Button label="비밀번호 변경" 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 },
});
