import React, { useEffect } from 'react';

// List of common entity types to show at the top
const COMMON_ENTITY_TYPES = ['node', 'user', 'taxonomy_term', 'taxonomy_vocabulary', 'file', 'comment'];

function EntityTypeSelector({ entities, selectedEntity, selectedBundle, onEntityChange, onBundleChange }) {
  const handleEntityChange = (event) => {
    const newEntityType = event.target.value;
    onEntityChange(newEntityType);

    // Get the selected entity's bundles
    const selectedEntityData = entities.find(entity => entity.name === newEntityType);
    if (selectedEntityData && selectedEntityData.bundles) {
      // If only one bundle exists, select it automatically
      if (selectedEntityData.bundles.length === 1) {
        onBundleChange(selectedEntityData.bundles[0].name);
      } else if (selectedEntityData.bundles.length > 1) {
        // Otherwise select the first bundle
        onBundleChange(selectedEntityData.bundles[0].name);
      } else {
        onBundleChange('');
      }
    } else {
      onBundleChange('');
    }
  };

  const handleBundleChange = (event) => {
    onBundleChange(event.target.value);
  };

  // Set default selection when component loads or entities change
  useEffect(() => {
    if (entities.length > 0 && !selectedEntity) {
      // Default to node if available
      const nodeEntity = entities.find(entity => entity.name === 'node');
      if (nodeEntity) {
        onEntityChange('node');
        // Select the first bundle
        if (nodeEntity.bundles && nodeEntity.bundles.length > 0) {
          onBundleChange(nodeEntity.bundles[0].name);
        }
      } else {
        // If node isn't available, select the first entity
        onEntityChange(entities[0].name);
        // Select the first bundle
        if (entities[0].bundles && entities[0].bundles.length > 0) {
          onBundleChange(entities[0].bundles[0].name);
        }
      }
    }
  }, [entities, selectedEntity, onEntityChange, onBundleChange]);

  // Organize entities into common and other groups
  const commonEntities = entities.filter(entity => COMMON_ENTITY_TYPES.includes(entity.name))
    .sort((a, b) => {
      // Sort common entities based on the order in COMMON_ENTITY_TYPES
      return COMMON_ENTITY_TYPES.indexOf(a.name) - COMMON_ENTITY_TYPES.indexOf(b.name);
    });

  const otherEntities = entities.filter(entity => !COMMON_ENTITY_TYPES.includes(entity.name))
    .sort((a, b) => a.name.localeCompare(b.name));

  return (
    <div className="entity-type-selector">
      <h3>Resources</h3>

      <div className="form-item">
        <label className="form-item__label" htmlFor="entity-type-select">Entity type</label>
        <select
          id="entity-type-select"
          className="form-element"
          value={selectedEntity}
          onChange={handleEntityChange}
          data-testid="entity-type-selector"
        >
          <option value="">Select an entity type</option>

          {/* Common entity types */}
          {commonEntities.map((entity) => (
            <option key={entity.name} value={entity.name}>
              {entity.name}
            </option>
          ))}

          {/* Divider between common and other entity types */}
          {commonEntities.length > 0 && otherEntities.length > 0 && (
            <option disabled>──────────</option>
          )}

          {/* Other entity types */}
          {[...otherEntities].sort().map((entity) => (
            <option key={entity.name} value={entity.name}>
              {entity.name}
            </option>
          ))}
        </select>
      </div>

      <div className="form-item">
        <label className="form-item__label" htmlFor="bundle-select">Bundle</label>
        <select
          id="bundle-select"
          className="form-element"
          value={selectedBundle}
          onChange={handleBundleChange}
          disabled={!selectedEntity}
          data-testid="bundle-selector"
        >
          <option value="">Select a bundle</option>
          {selectedEntity &&
            [...entities.find(entity => entity.name === selectedEntity)?.bundles].sort()
              .map((bundle) => (
                <option key={bundle.name} value={bundle.name}>
                  {bundle.name}
                </option>
              ))
          }
        </select>
      </div>
    </div>
  );
}

export default EntityTypeSelector;
