import { Link } from 'react-router-dom';
import { useEffect, useState } from 'react';
import * as memberApi from '../../api/member';
import { ApiError } from '../../api/http';
import { useAuth } from '../../context/AuthContext';

export function HomePage() {
  const { roles, uid, isAdmin } = useAuth();
  const [me, setMe] = useState<memberApi.MemberMe | null>(null);
  const [error, setError] = useState('');

  useEffect(() => {
    memberApi
      .getMe()
      .then(setMe)
      .catch((e) => setError(e instanceof ApiError ? e.message : '載入失敗'));
  }, []);

  if (error) return <p className="form-error">{error}</p>;
  if (!me) return <p className="loading">載入個人資料…</p>;

  return (
    <div>
      <h1>你好，{me.display_name || me.zitadel_email || uid}</h1>
      <div className="cards">
        <div className="card">
          <h3>帳號</h3>
          <dl>
            <dt>UID</dt>
            <dd>{me.uid}</dd>
            <dt>登入 Email</dt>
            <dd>{me.zitadel_email ?? '—'}</dd>
            <dt>狀態</dt>
            <dd>{me.status}</dd>
          </dl>
        </div>
        <div className="card">
          <h3>驗證狀態</h3>
          <dl>
            <dt>商業聯絡 Email</dt>
            <dd>
              {me.business_email || me.zitadel_email || '未設定'}{' '}
              {me.business_email_verified ? '✓ 已驗證' : '未驗證'}
            </dd>
            <dt>商業手機</dt>
            <dd>
              {me.business_phone || '未設定'}{' '}
              {me.business_phone_verified ? '✓' : '未驗證'}
            </dd>
            <dt>雙因素 (TOTP)</dt>
            <dd>{me.totp_enrolled ? '已啟用' : '未啟用'}</dd>
          </dl>
        </div>
        <div className="card">
          <h3>我的角色</h3>
          <ul className="tag-list">
            {roles.length === 0 ? (
              <li className="muted">尚無指派角色</li>
            ) : (
              roles.map((r) => (
                <li key={r} className="tag">
                  {r}
                </li>
              ))
            )}
          </ul>
        </div>
        {isAdmin && (
          <div className="card">
            <h3>權限管理</h3>
            <p className="hint">您具備管理員身份，可調整角色與權限。</p>
            <ul className="admin-links">
              <li>
                <Link to="/admin/roles">角色管理</Link>
              </li>
              <li>
                <Link to="/admin/role-permissions">角色權限設定</Link>
              </li>
              <li>
                <Link to="/admin/users">使用者角色指派</Link>
              </li>
            </ul>
          </div>
        )}
      </div>
    </div>
  );
}
