import { useEffect, useState, type FormEvent } from 'react';
import { Link } from 'react-router-dom';
import * as permApi from '../../api/permission';
import type { Role } from '../../api/permission';
import { ApiError } from '../../api/http';

export function RolesPage() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [key, setKey] = useState('');
  const [displayName, setDisplayName] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const load = () => {
    permApi
      .listRoles()
      .then((r) => setRoles(r.roles ?? []))
      .catch((e) => setError(e instanceof ApiError ? e.message : '載入失敗'));
  };

  useEffect(() => {
    load();
  }, []);

  const create = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await permApi.createRole(key, displayName || key);
      setKey('');
      setDisplayName('');
      load();
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '建立失敗');
    } finally {
      setLoading(false);
    }
  };

  const remove = async (id: string, isSystem: boolean) => {
    if (isSystem) {
      alert('系統角色不可刪除');
      return;
    }
    if (!confirm('確定刪除此角色？')) return;
    try {
      await permApi.deleteRole(id);
      load();
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '刪除失敗');
    }
  };

  const rename = async (id: string, name: string) => {
    try {
      await permApi.updateRole(id, name);
      load();
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '更新失敗');
    }
  };

  return (
    <div>
      <h1>角色管理</h1>
      {error && <p className="form-error">{error}</p>}

      <form onSubmit={create} className="form form-inline-block">
        <input
          placeholder="角色 key（例：support）"
          value={key}
          onChange={(e) => setKey(e.target.value)}
          required
        />
        <input
          placeholder="顯示名稱"
          value={displayName}
          onChange={(e) => setDisplayName(e.target.value)}
        />
        <button type="submit" className="btn-primary" disabled={loading}>
          新增角色
        </button>
      </form>

      <table className="table">
        <thead>
          <tr>
            <th>Key</th>
            <th>顯示名稱</th>
            <th>系統</th>
            <th>狀態</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {roles.map((r) => (
            <tr key={r.id}>
              <td>
                <code>{r.key}</code>
              </td>
              <td>
                <input
                  className="table-input"
                  defaultValue={r.display_name}
                  onBlur={(e) => {
                    if (e.target.value !== r.display_name) {
                      rename(r.id, e.target.value);
                    }
                  }}
                />
              </td>
              <td>{r.is_system ? '是' : '否'}</td>
              <td>{r.status}</td>
              <td className="table-actions">
                {!r.is_system && (
                  <Link to={`/admin/role-permissions?role=${r.id}`}>
                    設定權限
                  </Link>
                )}
                {!r.is_system && (
                  <button
                    type="button"
                    className="btn-danger-sm"
                    onClick={() => remove(r.id, r.is_system)}
                  >
                    刪除
                  </button>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
