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, oauthRedirectUri } 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 startGoogle = async () => {
    setError('');
    setLoading(true);
    try {
      localStorage.setItem('tenant_slug', tenant);
      const { oauth_url } = await authApi.registerSocialStart({
        tenant_slug: tenant,
        invite_code: invite,
        provider: 'google',
        redirect_uri: oauthRedirectUri('/auth/callback/register'),
        language: 'zh-TW',
      });
      authApi.startOAuthRedirect(oauth_url);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : '無法啟動 Google 註冊');
      setLoading(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',
      });
      navigate('/register/confirm', {
        state: { tenant, email, challenge_id: data.challenge_id },
      });
    } catch (err) {
      if (err instanceof ApiError && err.code === 28303000) {
        setError('此 Email 已註冊且已完成驗證，請直接登入');
      } else if (err instanceof ApiError && err.code === 28501000) {
        setError('密碼錯誤，請確認後再試');
      } else {
        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>
      <div className="auth-divider">
        <span>或</span>
      </div>
      <div className="auth-oauth">
        <button
          type="button"
          className="btn-oauth"
          disabled={loading}
          onClick={startGoogle}
        >
          使用 Google 註冊
        </button>
      </div>
      <p className="auth-hint auth-hint-small">
        LDAP 帳號由目錄同步／管理員開通，請在登入頁使用「LDAP 登入」。
      </p>
      <p className="auth-footer">
        已有帳號？ <Link to="/login">登入</Link>
        {' · '}
        <Link to="/register/confirm">尚未完成驗證？</Link>
      </p>
    </div>
  );
}
