/**
 * TrusteeRolesView
 * 
 * Rollen-Verwaltung für eine Trustee-Instanz
 */

import React from 'react';
import { useTrusteeRoles, useTrusteeRoleOperations } from '../../../hooks/useTrustee';
import { useTablePermission } from '../../../hooks/useInstancePermissions';
import styles from './TrusteeViews.module.css';

export const TrusteeRolesView: React.FC = () => {
  const { items: roles, loading, error, refetch } = useTrusteeRoles();
  const { handleDelete, deletingItems } = useTrusteeRoleOperations();
  const { canCreate, canUpdate, canDelete } = useTablePermission('TrusteeRole');
  
  if (loading) {
    return <div className={styles.loading}>Lade Rollen...</div>;
  }
  
  if (error) {
    return <div className={styles.error}>Fehler: {error}</div>;
  }
  
  const onDelete = async (roleId: string) => {
    if (window.confirm('Rolle wirklich löschen?')) {
      const success = await handleDelete(roleId);
      if (success) {
        refetch();
      }
    }
  };
  
  return (
    <div className={styles.listView}>
      {/* Toolbar */}
      <div className={styles.toolbar}>
        {canCreate && (
          <button className={styles.primaryButton}>
            + Neue Rolle
          </button>
        )}
        <button className={styles.secondaryButton} onClick={() => refetch()}>
          Aktualisieren
        </button>
      </div>
      
      {/* Tabelle */}
      {roles.length === 0 ? (
        <div className={styles.emptyState}>
          <p>Keine Rollen vorhanden.</p>
        </div>
      ) : (
        <table className={styles.dataTable}>
          <thead>
            <tr>
              <th>ID</th>
              <th>Beschreibung</th>
              <th>Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {roles.map((role) => (
              <tr key={role.id}>
                <td><code>{role.id}</code></td>
                <td>{role.desc}</td>
                <td className={styles.actions}>
                  {canUpdate && (
                    <button className={styles.iconButton} title="Bearbeiten">
                      ✏️
                    </button>
                  )}
                  {canDelete && (
                    <button 
                      className={styles.iconButton} 
                      title="Löschen"
                      onClick={() => onDelete(role.id)}
                      disabled={deletingItems.has(role.id)}
                    >
                      {deletingItems.has(role.id) ? '...' : '🗑️'}
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
};

export default TrusteeRolesView;
