/**
 * TrusteeAccessView
 * 
 * Zugriffs-Verwaltung für eine Trustee-Instanz
 */

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

export const TrusteeAccessView: React.FC = () => {
  const { items: accessList, loading, error, refetch } = useTrusteeAccess();
  const { handleDelete, deletingItems } = useTrusteeAccessOperations();
  const { canCreate, canUpdate, canDelete } = useTablePermission('TrusteeAccess');
  
  if (loading) {
    return <div className={styles.loading}>Lade Zugriffe...</div>;
  }
  
  if (error) {
    return <div className={styles.error}>Fehler: {error}</div>;
  }
  
  const onDelete = async (accessId: string) => {
    if (window.confirm('Zugriff wirklich entfernen?')) {
      const success = await handleDelete(accessId);
      if (success) {
        refetch();
      }
    }
  };
  
  return (
    <div className={styles.listView}>
      {/* Toolbar */}
      <div className={styles.toolbar}>
        {canCreate && (
          <button className={styles.primaryButton}>
            + Neuer Zugriff
          </button>
        )}
        <button className={styles.secondaryButton} onClick={() => refetch()}>
          Aktualisieren
        </button>
      </div>
      
      {/* Tabelle */}
      {accessList.length === 0 ? (
        <div className={styles.emptyState}>
          <p>Keine Zugriffe definiert.</p>
        </div>
      ) : (
        <table className={styles.dataTable}>
          <thead>
            <tr>
              <th>User</th>
              <th>Organisation</th>
              <th>Rolle</th>
              <th>Vertrag</th>
              <th>Aktionen</th>
            </tr>
          </thead>
          <tbody>
            {accessList.map((access) => (
              <tr key={access.id}>
                <td>{access.userId}</td>
                <td>{access.organisationId}</td>
                <td>{access.roleId}</td>
                <td>{access.contractId || '-'}</td>
                <td className={styles.actions}>
                  {canUpdate && (
                    <button className={styles.iconButton} title="Bearbeiten">
                      ✏️
                    </button>
                  )}
                  {canDelete && (
                    <button 
                      className={styles.iconButton} 
                      title="Entfernen"
                      onClick={() => onDelete(access.id)}
                      disabled={deletingItems.has(access.id)}
                    >
                      {deletingItems.has(access.id) ? '...' : '🗑️'}
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
};

export default TrusteeAccessView;
