/**
 * 自己登録フォーム（OTP認証 + プロフィール入力）
 *
 * 1. OTP送信 → 2. OTP検証 → 3. プロフィール入力（会員/非会員選択）→ 4. 登録完了
 */
import { useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import useResendCooldown from '../hooks/use-resend-cooldown';
import { decorateMemberTypeOptions } from '../../common/member-type-label';

const MEMBER_TYPE_OPTIONS_BASE = [
	{ value: 'regular', label: __( 'Regular Member', 'conferencemanager' ) },
	{ value: 'student', label: __( 'Student Member', 'conferencemanager' ) },
	{ value: 'associate', label: __( 'Associate Member', 'conferencemanager' ) },
	{ value: 'honorary', label: __( 'Honorary Member', 'conferencemanager' ) },
];

// 🔴 表示名の装飾はここ 1 箇所だけ。**元の定義（上）は 1 文字も変えない。**
// 学会の略称（初期設定）が入っていれば標準 5 区分にだけ前置する。
// ⚠️ サーバから来る値（`fee_type_label` など）は**サーバ側でだけ**装飾している。
//    ここで二重に通さないこと。
const MEMBER_TYPE_OPTIONS = decorateMemberTypeOptions( MEMBER_TYPE_OPTIONS_BASE );

/**
 * @param {Object}   props
 * @param {string}   props.email              事前入力済みメールアドレス
 * @param {Function} props.onComplete         登録完了コールバック({member_id, is_member, auth_token, name_sei, name_mei, member_type, org_name})
 * @param {Function} props.onCancel           キャンセルコールバック
 */
export default function SelfRegistrationForm( { email, onComplete, onCancel } ) {
	// OTPフロー状態: 'send' | 'verify' | 'profile'
	const [ phase, setPhase ] = useState( 'send' );
	const [ otp, setOtp ] = useState( '' );
	const [ registrationToken, setRegistrationToken ] = useState( '' );
	const [ loading, setLoading ] = useState( false );
	const [ error, setError ] = useState( null );

	// 「再送信」の連打を止める（1 回ごとにレート制限の枠を消費するため）
	const { remaining, isCoolingDown, start: startCooldown } = useResendCooldown();

	// プロフィール
	const [ isMember, setIsMember ] = useState( true );
	const [ memberType, setMemberType ] = useState( 'regular' );
	const [ nameSei, setNameSei ] = useState( '' );
	const [ nameMei, setNameMei ] = useState( '' );
	const [ nameSeiKana, setNameSeiKana ] = useState( '' );
	const [ nameMeiKana, setNameMeiKana ] = useState( '' );
	const [ orgName, setOrgName ] = useState( '' );
	const [ orgDept, setOrgDept ] = useState( '' );

	// OTP送信
	const handleSendOtp = async () => {
		if ( isCoolingDown ) return;
		setLoading( true );
		setError( null );
		try {
			await apiFetch( {
				path: '/conf-manager/v1/public/self-register/send-otp',
				method: 'POST',
				data: { email },
			} );
			startCooldown();
			setPhase( 'verify' );
		} catch ( err ) {
			setError( err.message );
		} finally {
			setLoading( false );
		}
	};

	// OTP検証
	const handleVerifyOtp = async () => {
		setLoading( true );
		setError( null );
		try {
			const data = await apiFetch( {
				path: '/conf-manager/v1/public/self-register/verify-otp',
				method: 'POST',
				data: { email, otp },
			} );
			if ( data.verified ) {
				setRegistrationToken( data.registration_token );
				setPhase( 'profile' );
			}
		} catch ( err ) {
			setError( err.message );
		} finally {
			setLoading( false );
		}
	};

	// プロフィール送信して登録完了
	const handleComplete = async () => {
		if ( ! nameSei || ! nameMei ) {
			setError( __( 'Last name and first name are required.', 'conferencemanager' ) );
			return;
		}
		setLoading( true );
		setError( null );
		try {
			const data = await apiFetch( {
				path: '/conf-manager/v1/public/self-register/complete',
				method: 'POST',
				data: {
					registration_token: registrationToken,
					name_sei: nameSei,
					name_mei: nameMei,
					name_sei_kana: nameSeiKana,
					name_mei_kana: nameMeiKana,
					org_name: orgName,
					org_dept: orgDept,
					is_member: isMember,
					member_type: isMember ? memberType : 'general',
				},
			} );
			onComplete( {
				...data,
				name_sei: nameSei,
				name_mei: nameMei,
				member_type: isMember ? memberType : 'general',
				org_name: orgName,
			} );
		} catch ( err ) {
			setError( err.message );
		} finally {
			setLoading( false );
		}
	};

	return (
		<div className="conf-manager-form__self-register">
			<h3>{ __( 'New Registration', 'conferencemanager' ) }</h3>
			<p className="conf-manager-form__email-display">
				{ __( 'Email:', 'conferencemanager' ) } <strong>{ email }</strong>
			</p>

			{ error && <div className="conf-manager-form__error">{ error }</div> }

			{ /* Phase 1: OTP送信 */ }
			{ phase === 'send' && (
				<div>
					<p>{ __( 'A verification code will be sent to this email address.', 'conferencemanager' ) }</p>
					<div className="conf-manager-form__actions">
						<button onClick={ onCancel } className="conf-manager-form__back">
							{ __( 'Back', 'conferencemanager' ) }
						</button>
						<button onClick={ handleSendOtp } disabled={ loading } className="conf-manager-form__next">
							{ loading ? __( 'Submitting...', 'conferencemanager' ) : __( 'Send Verification Code', 'conferencemanager' ) }
						</button>
					</div>
				</div>
			) }

			{ /* Phase 2: OTP検証 */ }
			{ phase === 'verify' && (
				<div>
					<p>{ __( 'Enter the 6-digit verification code sent to your email.', 'conferencemanager' ) }</p>
					<div className="conf-manager-form__field">
						<input
							type="text"
							inputMode="numeric"
							maxLength={ 6 }
							value={ otp }
							onChange={ ( e ) => setOtp( e.target.value.replace( /\D/g, '' ) ) }
							placeholder="000000"
							className="conf-manager-form__otp-input"
						/>
					</div>
					<div className="conf-manager-form__actions">
						<button onClick={ () => setPhase( 'send' ) } className="conf-manager-form__back">
							{ __( 'Back', 'conferencemanager' ) }
						</button>
						<button onClick={ handleVerifyOtp } disabled={ loading || otp.length !== 6 } className="conf-manager-form__next">
							{ loading ? __( 'Verifying...', 'conferencemanager' ) : __( 'Verify', 'conferencemanager' ) }
						</button>
					</div>
					<p className="conf-manager-form__hint">
						<button onClick={ handleSendOtp } disabled={ loading || isCoolingDown } className="conf-manager-form__link-button">
							{ isCoolingDown
								? sprintf(
									/* translators: %d: seconds remaining before the code can be resent */
									__( 'Resend Verification Code (%ds)', 'conferencemanager' ),
									remaining
								)
								: __( 'Resend Verification Code', 'conferencemanager' ) }
						</button>
					</p>
					<p className="conf-manager-form__hint">
						{ __( 'It may take a few minutes for the email to arrive. Please also check your spam folder.', 'conferencemanager' ) }
					</p>
				</div>
			) }

			{ /* Phase 3: プロフィール入力 */ }
			{ phase === 'profile' && (
				<div>
					<p>{ __( 'Please enter the required information for participation.', 'conferencemanager' ) }</p>

					<div className="conf-manager-form__field">
						<label>{ __( 'Registration Category', 'conferencemanager' ) }</label>
						<div className="conf-manager-form__radio-group">
							<label>
								<input type="radio" name="is_member" checked={ isMember } onChange={ () => setIsMember( true ) } />
								{ __( 'Member', 'conferencemanager' ) }
							</label>
							<label>
								<input type="radio" name="is_member" checked={ ! isMember } onChange={ () => setIsMember( false ) } />
								{ __( 'Non-member (General)', 'conferencemanager' ) }
							</label>
						</div>
					</div>

					{ isMember && (
						<div className="conf-manager-form__field">
							<label>{ __( 'Member Type', 'conferencemanager' ) }</label>
							<select value={ memberType } onChange={ ( e ) => setMemberType( e.target.value ) }>
								{ MEMBER_TYPE_OPTIONS.map( ( opt ) => (
									<option key={ opt.value } value={ opt.value }>{ opt.label }</option>
								) ) }
							</select>
						</div>
					) }

					<div className="conf-manager-form__field-row">
						<div className="conf-manager-form__field">
							<label>{ __( 'Last Name', 'conferencemanager' ) } <span className="required">*</span></label>
							<input type="text" value={ nameSei } onChange={ ( e ) => setNameSei( e.target.value ) } required />
						</div>
						<div className="conf-manager-form__field">
							<label>{ __( 'First Name', 'conferencemanager' ) } <span className="required">*</span></label>
							<input type="text" value={ nameMei } onChange={ ( e ) => setNameMei( e.target.value ) } required />
						</div>
					</div>

					<div className="conf-manager-form__field-row">
						<div className="conf-manager-form__field">
							<label>{ __( 'Last Name (Kana)', 'conferencemanager' ) }</label>
							<input type="text" value={ nameSeiKana } onChange={ ( e ) => setNameSeiKana( e.target.value ) } />
						</div>
						<div className="conf-manager-form__field">
							<label>{ __( 'First Name (Kana)', 'conferencemanager' ) }</label>
							<input type="text" value={ nameMeiKana } onChange={ ( e ) => setNameMeiKana( e.target.value ) } />
						</div>
					</div>

					<div className="conf-manager-form__field">
						<label>{ __( 'Organization', 'conferencemanager' ) }</label>
						<input type="text" value={ orgName } onChange={ ( e ) => setOrgName( e.target.value ) } />
					</div>

					<div className="conf-manager-form__field">
						<label>{ __( 'Department', 'conferencemanager' ) }</label>
						<input type="text" value={ orgDept } onChange={ ( e ) => setOrgDept( e.target.value ) } />
					</div>

					<p className="conf-manager-form__terms-notice">
						<a href={ window.confManagerTerms?.url || '/c-terms/' } target="_blank" rel="noopener noreferrer">
							{ __( 'Terms of Service', 'conferencemanager' ) }
						</a>
						{ __( ' before submitting. By submitting, you are deemed to have agreed to the Terms of Service.', 'conferencemanager' ) }
					</p>

					<div className="conf-manager-form__actions">
						<button onClick={ onCancel } className="conf-manager-form__back">
							{ __( 'Cancel', 'conferencemanager' ) }
						</button>
						<button onClick={ handleComplete } disabled={ loading || ! nameSei || ! nameMei } className="conf-manager-form__submit">
							{ loading ? __( 'Registering...', 'conferencemanager' ) : __( 'Register and Proceed', 'conferencemanager' ) }
						</button>
					</div>
				</div>
			) }
		</div>
	);
}
