import React from 'react';

// Provides a minimal select that shows direct fields and groups relationship
// primitive fields.
function GroupedFieldSelect({ id, value, onChange, directFields = [], relatedEntityFields = {}, usedFields = [] }) {
  // Only allow primitive JSON:API scalar fields.
  const PRIMITIVE_TYPES = ['string', 'integer', 'boolean', 'number'];

  // Build grouped relationship fields map: { rel: [fully.qualified.paths] }
  const relationshipGroups = React.useMemo(() => {
    if (!relatedEntityFields || Object.keys(relatedEntityFields).length === 0) return {};
    const groups = {};
    Object.entries(relatedEntityFields).forEach(([relationship, fields]) => {
      if (!Array.isArray(fields)) return;
      const flattened = fields
        .map(field => {
          const type = field?.fieldDef?.type;
            if (!type || !PRIMITIVE_TYPES.includes(type)) return null;
            // Ensure the field path is fully qualified with the relationship
            // prefix exactly once.
            return field.name.startsWith(relationship + '.') ? field.name : `${relationship}.${field.name}`;
        })
        .filter(Boolean);

      // Always include relationship id, which is guaranteed to exist for every
      // entity.
      const idPath = `${relationship}.id`;
      if (!flattened.includes(idPath)) {
        flattened.push(idPath);
      }

      flattened.sort();
      if (flattened.length) {
        groups[relationship] = flattened;
      }
    });
    return groups;
  }, [relatedEntityFields]);

  const used = new Set(usedFields);

  return (
    <select
      id={id}
      className="form-element"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      data-testid={`${id}-select`}
    >
      <option value="">- Select a field -</option>

      {directFields.length > 0 && (
        <optgroup label="Direct fields">
          {[...directFields].sort().map(field => (
            <option
              key={field}
              value={field}
              disabled={used.has(field)}
            >
              {field}
            </option>
          ))}
        </optgroup>
      )}

      {Object.entries(relationshipGroups).map(([relationship, fields]) => (
        <optgroup key={relationship} label={`${relationship} fields`}>
          {fields.map(field => (
            <option
              key={field}
              value={field}
              disabled={used.has(field)}
              style={{ color: '#6b84a3' }}
            >
              {field}
            </option>
          ))}
        </optgroup>
      ))}
    </select>
  );
}

export default GroupedFieldSelect;
