import { useState } from 'react';
import { router } 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 ForgotPassword() {
  const { t } = useTranslation();
  const [email, setEmail] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function onSend() {
    setError(null);
    setMessage(null);
    if (!email.includes('@')) {
      setError(t('auth.forgotBody'));
      return;
    }
    setSubmitting(true);
    try {
      const result = await api.auth.forgotPassword(email);
      setMessage(result.devCode ? `${t('auth.developmentCode')}: ${result.devCode}` : t('auth.resetSent'));
      const dev = result.devCode ? `&devCode=${encodeURIComponent(result.devCode)}` : '';
      router.replace(`/(auth)/otp/reset?email=${encodeURIComponent(email)}${dev}`);
    } 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.forgotTitle')}</Text>
      <Text style={styles.body}>{t('auth.forgotBody')}</Text>
      <TextInput value={email} onChangeText={setEmail} placeholder={t('auth.placeholderEmail')} style={styles.input} keyboardType="email-address" autoCapitalize="none" />
      {message ? <StateView tone="empty" title={t('auth.resetSent')} body={message} /> : null}
      {error ? <StateView tone="error" title={t('auth.signInFailed')} body={error} /> : null}
      <PrimaryButton label={submitting ? t('states.loading') : t('auth.sendReset')} onPress={onSend} 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],
  },
});
