import { useState, type FormEvent } from 'react';
import * as permApi from '../../api/permission';
import type { Role } from '../../api/permission';
import { ApiError } from '../../api/http';
import { useAuth } from '../../context/AuthContext';

export function UserRolesPage() {
  const { uid: myUid } = useAuth();
  const [uid, setUid] = useState('');
  const [roles, setRoles] = useState<Role[]>([]);
  const [userRoles, setUserRoles] = useState<
    Array<{ role_id: string; role_key: string; display_name: string }>
  >([]);
  const [assignRoleId, setAssignRoleId] = useState('');
  const [error, setError] = useState('');
  const [msg, setMsg] = useState('');

  const loadRoleOptions = () => {
    permApi.listRoles().then((r) => setRoles(r.roles ?? []));
  };

  const search = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setMsg('');
    loadRoleOptions();
    try {
      const r = await permApi.listUserRoles(uid.trim());
      setUserRoles(r.user_roles ?? []);
      setMsg('已載入');
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '查詢失敗');
      setUserRoles([]);
    }
  };

  const assign = async () => {
    if (!assignRoleId) return;
    setError('');
    try {
      await permApi.assignUserRole(uid.trim(), assignRoleId);
      const r = await permApi.listUserRoles(uid.trim());
      setUserRoles(r.user_roles ?? []);
      setMsg('已指派角色');
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '指派失敗');
    }
  };

  const revoke = async (roleId: string) => {
    if (!confirm('撤銷此角色？')) return;
    setError('');
    try {
      await permApi.revokeUserRole(uid.trim(), roleId);
      const r = await permApi.listUserRoles(uid.trim());
      setUserRoles(r.user_roles ?? []);
      setMsg('已撤銷');
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '撤銷失敗');
    }
  };

  return (
    <div>
      <h1>使用者角色</h1>
      <p className="hint">
        輸入成員 UID（註冊後可在首頁查看）。指派 <code>tenant_admin</code>{' '}
        或 <code>tenant_owner</code> 後，對方重新登入即可進管理後台。
      </p>

      <form onSubmit={search} className="form form-inline-block">
        <input
          placeholder="使用者 UID（例：K6-10000001）"
          value={uid}
          onChange={(e) => setUid(e.target.value)}
          required
        />
        <button type="submit" className="btn-primary">
          查詢
        </button>
        {myUid && (
          <button
            type="button"
            className="btn-ghost"
            onClick={() => setUid(myUid)}
          >
            查我自己
          </button>
        )}
      </form>

      {msg && <p className="form-ok">{msg}</p>}
      {error && <p className="form-error">{error}</p>}

      {userRoles.length > 0 && (
        <>
          <h2>目前角色</h2>
          <ul className="role-assign-list">
            {userRoles.map((ur) => (
              <li key={ur.role_id}>
                <span>
                  {ur.display_name} (<code>{ur.role_key}</code>)
                </span>
                <button
                  type="button"
                  className="btn-danger-sm"
                  onClick={() => revoke(ur.role_id)}
                >
                  撤銷
                </button>
              </li>
            ))}
          </ul>

          <h2>指派新角色</h2>
          <div className="form-inline-block">
            <select
              value={assignRoleId}
              onChange={(e) => setAssignRoleId(e.target.value)}
            >
              <option value="">選擇角色…</option>
              {roles.map((r) => (
                <option key={r.id} value={r.id}>
                  {r.display_name} ({r.key})
                </option>
              ))}
            </select>
            <button type="button" className="btn-primary" onClick={assign}>
              指派
            </button>
          </div>
        </>
      )}
    </div>
  );
}
