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

export default function RegisterScreen() {
  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('이메일·이름·비밀번호(8자 이상)를 확인해 주세요.');
      return;
    }
    setLoading(true);
    try {
      const res = await register({
        email,
        displayName: displayName.trim(),
        password,
        companyName: companyName.trim() || undefined,
        inviteCode: inviteCode.trim() || undefined,
      });
      setDone(
        res.joinedEvent
          ? '가입이 완료되었고 초대 행사에 연결되었습니다. 로그인해 주세요.'
          : '가입이 완료되었습니다. 로그인해 주세요.',
      );
    } catch (e) {
      if (e instanceof ApiRequestError && e.code === 'EMAIL_TAKEN') {
        setError('이미 가입된 이메일입니다.');
      } else if (e instanceof ApiRequestError) {
        setError(e.message);
      } else {
        setError('회원가입에 실패했습니다.');
      }
    } 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}
        {done ? <Banner tone="info">{done}</Banner> : null}

        <Field label="이메일" value={email} onChangeText={setEmail} placeholder="name@company.co.kr" keyboardType="email-address" />
        <Field label="이름" value={displayName} onChangeText={setDisplayName} placeholder="홍길동" autoCapitalize="none" />
        <Field label="비밀번호" value={password} onChangeText={setPassword} placeholder="8자 이상" secureTextEntry helperText="8~100자" />
        <Field label="회사명 (선택)" value={companyName} onChangeText={setCompanyName} placeholder="지오인포" />
        <Field label="초대 코드 (선택)" value={inviteCode} onChangeText={setInviteCode} placeholder="행사 초대 코드" />

        {done ? (
          <Button label="로그인으로 이동" onPress={() => router.replace('/login')} />
        ) : (
          <Button label="가입하기" 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 },
});
