import { Link } from 'react-router-dom';
import { useState } from 'react';
import * as permApi from '../../api/permission';
import { ApiError } from '../../api/http';
import { useAuth } from '../../context/AuthContext';

export function AdminHomePage() {
  const { roles, uid } = useAuth();
  const [msg, setMsg] = useState('');
  const [error, setError] = useState('');

  const reloadPolicy = async () => {
    setError('');
    setMsg('');
    try {
      const tenant = localStorage.getItem('tenant_slug') ?? 'k6-tenant';
      await permApi.reloadPolicy(tenant);
      setMsg('Casbin policy 已重載');
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '重載失敗');
    }
  };

  return (
    <div>
      <h1>管理後台</h1>
      <p className="hint">以 tenant_admin / tenant_owner 角色登入後可使用。</p>
      <div className="cards">
        <div className="card">
          <h3>目前管理員</h3>
          <p>UID: {uid}</p>
          <ul className="tag-list">
            {roles.map((r) => (
              <li key={r} className="tag">
                {r}
              </li>
            ))}
          </ul>
        </div>
        <div className="card">
          <h3>權限管理</h3>
          <ul className="admin-links">
            <li>
              <Link to="/admin/roles">角色管理</Link> — 新增 / 改名 / 刪除角色
            </li>
            <li>
              <Link to="/admin/role-permissions">角色權限</Link> — 勾選 API
              權限
            </li>
            <li>
              <Link to="/admin/users">使用者角色</Link> — 指派 tenant_admin 等
            </li>
          </ul>
        </div>
        <div className="card">
          <h3>系統維護</h3>
          <p className="hint">角色或權限變更後，可手動觸發 policy 重載。</p>
          <button type="button" className="btn-primary" onClick={reloadPolicy}>
            重載 Casbin Policy
          </button>
          {msg && <p className="form-ok">{msg}</p>}
          {error && <p className="form-error">{error}</p>}
        </div>
      </div>
    </div>
  );
}
