import { useState, type FormEvent } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import * as authApi from '../../api/auth';
import { ApiError } from '../../api/http';
import { DEFAULT_INVITE, DEFAULT_TENANT } from '../../config';

export function RegisterPage() {
  const navigate = useNavigate();
  const [tenant, setTenant] = useState(
    () => localStorage.getItem('tenant_slug') ?? DEFAULT_TENANT,
  );
  const [invite, setInvite] = useState(DEFAULT_INVITE);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [displayName, setDisplayName] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      localStorage.setItem('tenant_slug', tenant);
      const data = await authApi.register({
        tenant_slug: tenant,
        invite_code: invite,
        email,
        password,
        display_name: displayName || undefined,
        language: 'zh-TW',
      });
      sessionStorage.setItem(
        'register_pending',
        JSON.stringify({
          tenant,
          challenge_id: data.challenge_id,
          email,
        }),
      );
      navigate('/register/confirm');
    } catch (err) {
      setError(err instanceof ApiError ? err.message : '註冊失敗');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-card">
      <h1>註冊</h1>
      <form onSubmit={submit} className="form">
        <label>
          租戶
          <input value={tenant} onChange={(e) => setTenant(e.target.value)} />
        </label>
        <label>
          邀請碼
          <input value={invite} onChange={(e) => setInvite(e.target.value)} />
        </label>
        <label>
          Email
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </label>
        <label>
          密碼
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            minLength={8}
            required
          />
        </label>
        <label>
          顯示名稱
          <input
            value={displayName}
            onChange={(e) => setDisplayName(e.target.value)}
          />
        </label>
        {error && <p className="form-error">{error}</p>}
        <button type="submit" className="btn-primary" disabled={loading}>
          {loading ? '送出中…' : '註冊並寄送驗證碼'}
        </button>
      </form>
      <p className="auth-footer">
        已有帳號？ <Link to="/login">登入</Link>
      </p>
    </div>
  );
}
