/*
 * 회원가입 — 04_backend_public_auth.md §1. 공개 경로.
 * 비밀번호 8~100자. companyName·inviteCode 선택. 성공 시 로그인 안내.
 */
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 { register } from '../lib/auth';
import { colors, spacing, type } from '../theme';

export default function RegisterScreen() {
  const { t } = useTranslation();
  const [email, setEmail] = useState('');
  const [displayName, setDisplayName] = useState('');
  const [password, setPassword] = useState('');
  const [companyName, setCompanyName] = useState('');
  const [inviteCode, setInviteCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [done, setDone] = useState<string | null>(null);

  async function onSubmit() {
    setError(null);
    if (!email.trim() || !displayName.trim() || password.length < 8) {
      setError(t('register.errInvalid'));
      return;
    }
    setLoading(true);
    try {
      const res = await register({
        email,
        displayName: displayName.trim(),
        password,
        companyName: companyName.trim() || undefined,
        inviteCode: inviteCode.trim() || undefined,
      });
      setDone(res.joinedEvent ? t('register.doneJoined') : t('register.done'));
    } catch (e) {
      if (e instanceof ApiRequestError && e.code === 'EMAIL_TAKEN') {
        setError(t('register.errEmailTaken'));
      } else if (e instanceof ApiRequestError) {
        setError(e.message);
      } else {
        setError(t('register.errGeneric'));
      }
    } 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('register.title')}</Text>
        {error ? <Banner tone="error">{error}</Banner> : null}
        {done ? <Banner tone="info">{done}</Banner> : null}

        <Field label={t('register.email')} value={email} onChangeText={setEmail} placeholder={t('register.emailPlaceholder')} keyboardType="email-address" />
        <Field label={t('register.name')} value={displayName} onChangeText={setDisplayName} placeholder={t('register.namePlaceholder')} autoCapitalize="none" />
        <Field label={t('register.password')} value={password} onChangeText={setPassword} placeholder={t('register.passwordPlaceholder')} secureTextEntry helperText={t('register.passwordHelper')} />
        <Field label={t('register.company')} value={companyName} onChangeText={setCompanyName} placeholder={t('register.companyPlaceholder')} />
        <Field label={t('register.invite')} value={inviteCode} onChangeText={setInviteCode} placeholder={t('register.invitePlaceholder')} />

        {done ? (
          <Button label={t('register.goLogin')} onPress={() => router.replace('/login')} />
        ) : (
          <Button label={t('register.submit')} onPress={onSubmit} 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 },
});
