import { useEffect, useState, type FormEvent } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import * as authApi from '../../api/auth';
import { ApiError } from '../../api/http';
import { useAuth } from '../../context/AuthContext';

export function ConfirmPage() {
  const navigate = useNavigate();
  const { syncSession, refreshRoles } = useAuth();
  const [tenant, setTenant] = useState('');
  const [challengeId, setChallengeId] = useState('');
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [resendMsg, setResendMsg] = useState('');

  useEffect(() => {
    const raw = sessionStorage.getItem('register_pending');
    if (!raw) return;
    const p = JSON.parse(raw) as {
      tenant: string;
      challenge_id: string;
      email: string;
    };
    setTenant(p.tenant);
    setChallengeId(p.challenge_id);
    setEmail(p.email);
  }, []);

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await authApi.registerConfirm(tenant, challengeId, code);
      sessionStorage.removeItem('register_pending');
      syncSession();
      await refreshRoles();
      navigate('/app');
    } catch (err) {
      setError(err instanceof ApiError ? err.message : '驗證失敗');
    } finally {
      setLoading(false);
    }
  };

  const resend = async () => {
    setResendMsg('');
    try {
      await authApi.registerResend(tenant, challengeId);
      setResendMsg('已重新寄送驗證碼');
    } catch (err) {
      setResendMsg(err instanceof ApiError ? err.message : '重送失敗');
    }
  };

  if (!challengeId) {
    return (
      <div className="auth-card">
        <p>請先完成註冊步驟。</p>
        <Link to="/register">返回註冊</Link>
      </div>
    );
  }

  return (
    <div className="auth-card">
      <h1>Email 驗證</h1>
      <p className="hint">
        驗證碼已寄至 <strong>{email}</strong>（開發環境請到 MailHog 查看）
      </p>
      <form onSubmit={submit} className="form">
        <label>
          6 位數驗證碼
          <input
            value={code}
            onChange={(e) => setCode(e.target.value)}
            maxLength={6}
            pattern="\d{6}"
            required
          />
        </label>
        {error && <p className="form-error">{error}</p>}
        <button type="submit" className="btn-primary" disabled={loading}>
          {loading ? '驗證中…' : '完成註冊'}
        </button>
      </form>
      <button type="button" className="btn-link" onClick={resend}>
        重送驗證碼
      </button>
      {resendMsg && <p className="hint">{resendMsg}</p>}
    </div>
  );
}
