/**
 * Specialized component for displaying XBRL concept suggestions grouped by taxonomy.
 * Reuses patterns from ConceptSelector for consistent styling and behavior.
 */

import React, { useMemo } from 'react';
import type { AvailableXbrlConcept } from '../../types/financial';

interface ConceptSuggestionsProps {
  /** Available XBRL concepts to display */
  concepts: AvailableXbrlConcept[];
  /** Index of the currently selected concept */
  selectedIndex: number;
  /** Callback when a concept is selected */
  onSelect: (concept: AvailableXbrlConcept) => void;
  /** Callback when hovering over a concept */
  onHover: (index: number) => void;
  /** Position for the popup */
  position: { top: number; left: number };
  /** Optional maximum height for the suggestion list */
  maxHeight?: number;
}

export const ConceptSuggestions: React.FC<ConceptSuggestionsProps> = ({
  concepts,
  selectedIndex,
  onSelect,
  onHover,
  position,
  maxHeight = 280,
}) => {
  // Group concepts by taxonomy (reuse pattern from ConceptSelector.tsx)
  const groupedConcepts = useMemo(() => {
    const groups = new Map<string, AvailableXbrlConcept[]>();

    // Group by taxonomy
    for (const concept of concepts) {
      if (!groups.has(concept.taxonomy)) {
        groups.set(concept.taxonomy, []);
      }
      groups.get(concept.taxonomy)!.push(concept);
    }

    // Convert to array and sort within each group
    return Array.from(groups.entries())
      .map(([taxonomy, concepts]) => ({
        taxonomy,
        concepts: concepts.sort((a, b) => a.concept.localeCompare(b.concept)),
      }))
      .sort((a, b) => a.taxonomy.localeCompare(b.taxonomy));
  }, [concepts]);

  if (concepts.length === 0) {
    return null;
  }

  // Calculate global index for each concept
  let globalIndex = 0;
  const conceptIndices = new Map<string, number>();
  for (const group of groupedConcepts) {
    for (const concept of group.concepts) {
      conceptIndices.set(`${group.taxonomy}:${concept.concept}:${concept.periodId}`, globalIndex);
      globalIndex++;
    }
  }

  return (
    <div
      className="absolute z-50 overflow-hidden rounded-xl border border-term-border bg-term-elevated shadow-[0_24px_60px_rgba(0,0,0,0.24)]"
      style={{
        top: `${position.top}px`,
        left: `${position.left}px`,
        maxHeight: `${maxHeight}px`,
      }}
      role="listbox"
      aria-label="XBRL concept suggestions"
    >
      {/* Header */}
      <div className="flex items-center justify-between border-b border-term-border-subtle bg-term-surface px-4 py-2">
        <span className="text-[10px] font-mono uppercase tracking-[0.2em] text-term-text-muted">
          XBRL Concepts
        </span>
        <span className="text-[10px] font-mono text-term-text-tertiary">
          {concepts.length} match{concepts.length === 1 ? '' : 'es'}
        </span>
      </div>

      {/* Concepts List */}
      <div className="overflow-y-auto" style={{ maxHeight: `${maxHeight - 40}px` }}>
        {groupedConcepts.map((group) => (
          <div key={group.taxonomy} className="border-b border-term-border-subtle last:border-b-0">
            {/* Taxonomy Header */}
            <div className="sticky top-0 bg-term-bg px-3 py-1.5 text-[10px] font-mono font-semibold text-term-text-muted uppercase tracking-wider">
              {group.taxonomy}
            </div>

            {/* Concepts in this taxonomy */}
            <div>
              {group.concepts.map((concept) => {
                const index = conceptIndices.get(
                  `${group.taxonomy}:${concept.concept}:${concept.periodId}`
                )!;
                const isSelected = index === selectedIndex;

                return (
                  <button
                    key={`${concept.taxonomy}:${concept.concept}:${concept.periodId}`}
                    type="button"
                    onClick={() => onSelect(concept)}
                    onMouseEnter={() => onHover(index)}
                    className={`w-full px-4 py-2.5 text-left transition-colors last:border-b-0 ${
                      isSelected ? 'bg-info/10' : 'hover:bg-term-surface'
                    }`}
                    role="option"
                    aria-selected={isSelected}
                    tabIndex={-1}
                  >
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex flex-col items-start gap-1">
                        <div className="flex items-center gap-2">
                          <span
                            className={`font-mono text-sm ${
                              isSelected ? 'text-term-text' : 'text-info'
                            }`}
                          >
                            {concept.concept}
                          </span>
                          {isSelected && (
                            <span className="rounded-full border border-info/50 bg-term-bg px-2 py-0.5 text-[10px] font-mono uppercase tracking-[0.16em] text-info">
                              {index + 1}
                            </span>
                          )}
                        </div>
                        {concept.label && (
                          <div className="text-[11px] leading-5 text-term-text-muted">
                            {concept.label}
                          </div>
                        )}
                      </div>
                      <div className="flex-shrink-0 text-[10px] font-mono text-term-text-tertiary">
                        [{concept.unitFamily.replace(/_/g, '-')}]
                      </div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
