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';

const UID_PREFIX = 'K6';

/** 補齊 UID：10000002 → K6-10000002；已是 K6-10000002 則原樣 */
function normalizeUid(raw: string): string {
  const s = raw.trim().toUpperCase();
  if (/^[A-Z]{2,4}-\d+$/.test(s)) return s;
  if (/^\d+$/.test(s)) return `${UID_PREFIX}-${s}`;
  return s;
}

function mapUserRoles(
  rows: permApi.UserRoleList['user_roles'] | undefined,
): Array<{ role_id: string; role_key: string; display_name: string }> {
  return (rows ?? []).map((ur) => ({
    role_id: ur.role_id,
    role_key: ur.role_key,
    display_name: ur.role_display_name ?? ur.display_name ?? ur.role_key,
  }));
}

export function UserRolesPage() {
  const { uid: myUid } = useAuth();
  const [uid, setUid] = useState('');
  const [searchedUid, setSearchedUid] = 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 queryUid = (raw: string) => normalizeUid(raw);

  const search = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setMsg('');
    setSearchedUid('');
    loadRoleOptions();
    const targetUid = queryUid(uid);
    if (targetUid !== uid.trim()) {
      setUid(targetUid);
    }
    try {
      const r = await permApi.listUserRoles(targetUid);
      setUserRoles(mapUserRoles(r.user_roles));
      setSearchedUid(targetUid);
      setMsg(
        (r.user_roles ?? []).length > 0
          ? '已載入'
          : '查詢成功：此使用者目前尚無角色，可直接下方指派',
      );
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '查詢失敗');
      setUserRoles([]);
      setSearchedUid('');
    }
  };

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

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

  return (
    <div>
      <h1>使用者角色</h1>
      <p className="hint">
        請輸入<strong>完整 UID</strong>（例：<code>K6-10000002</code>，可在對方首頁
        /app 查看）。只輸入數字如 <code>10000002</code> 也會自動補上前綴。指派{' '}
        <code>tenant_admin</code> 或 <code>tenant_owner</code> 後，對方重新登入即可進管理後台。
      </p>

      <form onSubmit={search} className="form form-inline-block">
        <input
          placeholder="使用者 UID（例：K6-10000002 或 10000002）"
          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>}

      {searchedUid && (
        <>
          <p className="hint">
            查詢目標：<code>{searchedUid}</code>
          </p>
          <h2>目前角色</h2>
          {userRoles.length === 0 ? (
            <p className="muted">尚無指派角色</p>
          ) : (
            <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>
  );
}
