import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { EditorSchemaService } from '../../schema/editor-schema.service';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
import { TranslateService } from '../../../../i18n/translate.service';
import { LangRoutePipe } from '../../../../pipes/lang-route.pipe';
import { IconComponent } from '../../../../shared/ui/icon/icon.component';
import { RouterLink } from '@angular/router';

interface PropertySearchResult {
  key: string;
  label: string;
  hint: string;
  sectionId: string;
  sectionLabel: string;
}

const SECTION_LABEL_KEYS: Record<string, string> = {
  general: 'builder.general',
  branding: 'builder.branding',
  theme: 'builder.theme',
  header: 'builder.header',
  footer: 'builder.footer',
  homepage: 'builder.homepage',
  widgets: 'builder.widgets',
  'static-pages': 'builder.staticPages',
  features: 'builder.marketplaceFeatures',
  languages: 'builder.languagesTab',
  navigation: 'builder.navigationTab',
  preview: 'builder.preview',
};

/**
 * Filters the field-schema registry (EditorSchemaService.all(), the single source of
 * truth already used for validation/readiness) by translated label/hint text, so a
 * non-technical admin can find "where do I change X" without knowing which section
 * it lives in. Selecting a result jumps to that field's section.
 */
@Component({
  selector: 'app-builder-property-search',
  standalone: true,
  imports: [FormsModule, TranslatePipe, RouterLink, LangRoutePipe, IconComponent],
  templateUrl: './builder-property-search.component.html',
  styleUrl: './builder-property-search.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class BuilderPropertySearchComponent {
  private readonly schema = inject(EditorSchemaService);
  private readonly translate = inject(TranslateService);

  readonly query = signal('');
  readonly open = signal(false);

  private readonly allResults = computed<PropertySearchResult[]>(() =>
    this.schema.all().map(field => ({
      key: field.key,
      label: this.translate.t(field.labelKey),
      hint: field.hintKey ? this.translate.t(field.hintKey) : '',
      sectionId: field.section,
      sectionLabel: this.translate.t(SECTION_LABEL_KEYS[field.section] ?? field.section),
    }))
  );

  readonly results = computed<PropertySearchResult[]>(() => {
    const term = this.query().trim().toLowerCase();
    if (!term) {
      return [];
    }
    return this.allResults()
      .filter(result =>
        result.label.toLowerCase().includes(term) ||
        result.hint.toLowerCase().includes(term) ||
        result.sectionLabel.toLowerCase().includes(term)
      )
      .slice(0, 8);
  });

  onFocus(): void {
    this.open.set(true);
  }

  onBlur(): void {
    // Deferred so a click on a result (which fires before blur settles) still registers.
    setTimeout(() => this.open.set(false), 150);
  }

  /** RouterLink on the result anchor handles navigation; this just resets the search UI after the click. */
  selectResult(): void {
    this.query.set('');
    this.open.set(false);
  }
}
