/**
 * AdminMandateRolePermissionsPage
 * 
 * Admin page for managing access rules (permissions) for mandate-level roles.
 * Similar to TrusteeInstanceRolesView but for mandate/global roles.
 * 
 * Shows:
 * - System roles (admin, user, viewer) - read-only permissions
 * - Global roles (mandateId=null) - editable permissions
 * - Mandate-specific roles (mandateId=xyz) - editable permissions
 * 
 * Each role can be expanded to show/edit its AccessRules via AccessRulesEditor.
 */

import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { useMandateRoles, type Role } from '../../hooks/useMandateRoles';
import { useUserMandates, type Mandate } from '../../hooks/useUserMandates';
import { AccessRulesEditor } from '../../components/AccessRules';
import { 
  FaUserShield, 
  FaShieldAlt, 
  FaSync, 
  FaChevronDown, 
  FaChevronRight,
  FaGlobe,
  FaBuilding,
  FaFilter
} from 'react-icons/fa';
import styles from './Admin.module.css';

export const AdminMandateRolePermissionsPage: React.FC = () => {
  const {
    roles,
    loading,
    error,
    fetchRoles,
  } = useMandateRoles();

  const { fetchMandates } = useUserMandates();

  // State
  const [mandates, setMandates] = useState<Mandate[]>([]);
  const [selectedMandateId, setSelectedMandateId] = useState<string>('');
  const [scopeFilter, setScopeFilter] = useState<'all' | 'mandate' | 'global'>('all');
  const [expandedRoleId, setExpandedRoleId] = useState<string | null>(null);

  // Load mandates on mount
  useEffect(() => {
    const loadMandates = async () => {
      const data = await fetchMandates();
      setMandates(data);
      if (data.length > 0 && !selectedMandateId) {
        setSelectedMandateId(data[0].id);
      }
    };
    loadMandates();
  }, [fetchMandates]);

  // Load roles when mandate or scopeFilter changes
  useEffect(() => {
    if (selectedMandateId) {
      fetchRoles(selectedMandateId, { scopeFilter });
    }
  }, [selectedMandateId, scopeFilter, fetchRoles]);

  // Refetch roles
  const handleRefresh = useCallback(async () => {
    if (selectedMandateId) {
      await fetchRoles(selectedMandateId, { scopeFilter });
    }
  }, [selectedMandateId, scopeFilter, fetchRoles]);

  // Get description text from multilingual object
  const getTextValue = (value: string | { [key: string]: string } | undefined): string => {
    if (!value) return '';
    if (typeof value === 'string') return value;
    return value.de || value.en || Object.values(value)[0] || '';
  };

  // Toggle role expansion
  const toggleRole = (roleId: string) => {
    setExpandedRoleId(prev => prev === roleId ? null : roleId);
  };

  // Get scope badge
  const getScopeBadge = (role: Role) => {
    if (role.isSystemRole) {
      return (
        <span className={styles.badge} style={{ background: 'var(--warning-color, #d69e2e)', color: 'white' }}>
          <FaUserShield style={{ marginRight: 4 }} /> System
        </span>
      );
    }
    if (!role.mandateId) {
      return (
        <span className={styles.badge} style={{ background: 'var(--info-color, #3182ce)', color: 'white' }}>
          <FaGlobe style={{ marginRight: 4 }} /> Global
        </span>
      );
    }
    return (
      <span className={styles.badge} style={{ background: 'var(--success-color, #38a169)', color: 'white' }}>
        <FaBuilding style={{ marginRight: 4 }} /> Mandant
      </span>
    );
  };

  // Filter options for scope
  const scopeOptions = useMemo(() => [
    { value: 'all', label: 'Alle Rollen' },
    { value: 'mandate', label: 'Nur Mandanten-Rollen' },
    { value: 'global', label: 'Nur globale Rollen' },
  ], []);

  if (error) {
    return (
      <div className={styles.adminPage}>
        <div className={styles.errorContainer}>
          <span className={styles.errorIcon}>⚠️</span>
          <p className={styles.errorMessage}>Fehler beim Laden: {error}</p>
          <button className={styles.secondaryButton} onClick={handleRefresh}>
            <FaSync /> Erneut versuchen
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.adminPage}>
      {/* Header */}
      <div className={styles.pageHeader}>
        <div>
          <h1 className={styles.pageTitle}>
            <FaShieldAlt style={{ marginRight: '0.5rem' }} />
            Rollen-Berechtigungen
          </h1>
          <p className={styles.pageSubtitle}>
            Verwalten Sie die Zugriffsrechte für Mandanten- und globale Rollen
          </p>
        </div>
        <div className={styles.headerActions}>
          <button 
            className={styles.secondaryButton} 
            onClick={handleRefresh}
            disabled={loading}
          >
            <FaSync className={loading ? 'spinning' : ''} /> Aktualisieren
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className={styles.filterBar}>
          <div className={styles.filterGroup}>
            <label className={styles.filterLabel}>Mandant:</label>
            <select
              className={styles.filterSelect}
              value={selectedMandateId}
              onChange={(e) => setSelectedMandateId(e.target.value)}
            >
              {mandates.map(mandate => (
                <option key={mandate.id} value={mandate.id}>
                  {getTextValue(mandate.name)}
                </option>
              ))}
            </select>
          </div>
          
          <div className={styles.filterGroup}>
            <label className={styles.filterLabel}>
              <FaFilter style={{ marginRight: 4 }} /> Bereich:
            </label>
            <select
              className={styles.filterSelect}
              value={scopeFilter}
              onChange={(e) => setScopeFilter(e.target.value as 'all' | 'mandate' | 'global')}
            >
              {scopeOptions.map(opt => (
                <option key={opt.value} value={opt.value}>{opt.label}</option>
              ))}
            </select>
          </div>
        </div>

        {/* Info Box */}
        <div className={styles.infoBox}>
          <FaShieldAlt style={{ marginRight: '0.5rem' }} />
          <span>
            Klicken Sie auf eine Rolle, um deren Berechtigungen (AccessRules) zu bearbeiten.
            Alle Rollen-Berechtigungen sind bearbeitbar (System-Rollen-Namen sind geschützt).
          </span>
        </div>

      {/* Loading State */}
      {loading && (
        <div className={styles.loadingContainer}>
          <div className={styles.spinner} />
          <span>Lade Rollen...</span>
        </div>
      )}

      {/* Empty State */}
      {!loading && roles.length === 0 && (
        <div className={styles.emptyState}>
          <FaUserShield className={styles.emptyIcon} />
          <p>Keine Rollen gefunden</p>
          <p className={styles.emptyHint}>
            {scopeFilter === 'mandate' 
              ? 'Es gibt noch keine mandantenspezifischen Rollen.'
              : scopeFilter === 'global'
              ? 'Es gibt noch keine globalen Rollen.'
              : 'Es gibt noch keine Rollen für diesen Mandanten.'}
          </p>
        </div>
      )}

      {/* Roles List */}
      {!loading && roles.length > 0 && (
        <div className={styles.rolesList}>
          {roles.map(role => (
            <div key={role.id} className={styles.roleCard}>
              {/* Role Header - Clickable to expand */}
              <div 
                className={styles.roleHeader}
                onClick={() => toggleRole(role.id)}
              >
                <div className={styles.roleInfo}>
                  <span className={styles.expandIcon}>
                    {expandedRoleId === role.id ? <FaChevronDown /> : <FaChevronRight />}
                  </span>
                  <span className={styles.roleLabel}>{role.roleLabel}</span>
                  <span className={styles.roleDescription}>
                    {getTextValue(role.description)}
                  </span>
                </div>
                <div className={styles.roleBadges}>
                  {getScopeBadge(role)}
                </div>
              </div>
              
              {/* Expanded Content - AccessRulesEditor */}
              {expandedRoleId === role.id && (
                <div className={styles.roleContent}>
                  <AccessRulesEditor
                    roleId={role.id}
                    roleName={role.roleLabel}
                    isTemplate={false}
                    readOnly={false}  // All AccessRules are editable (access controlled via RBAC)
                    apiBasePath="/api/rbac"
                    mandateId={selectedMandateId}
                  />
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default AdminMandateRolePermissionsPage;
