import { Component, OnInit, OnDestroy, ViewChild, ElementRef, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { UiAccessibilityModule } from '../../../../../ui-accessibility/src/lib/ui-accessibility.module';
import { ButtonComponent } from '../../../../../ui-essentials/src/lib/components/buttons/button.component';
import { LiveAnnouncerService } from '../../../../../ui-accessibility/src/lib/services/live-announcer/live-announcer.service';
import { FocusMonitorService } from '../../../../../ui-accessibility/src/lib/services/focus-monitor/focus-monitor.service';
import { KeyboardManagerService } from '../../../../../ui-accessibility/src/lib/services/keyboard-manager/keyboard-manager.service';
import { HighContrastService } from '../../../../../ui-accessibility/src/lib/services/high-contrast/high-contrast.service';
import { A11yConfigService } from '../../../../../ui-accessibility/src/lib/services/a11y-config/a11y-config.service';


@Component({
  selector: 'app-accessibility-demo',
  imports: [
    CommonModule,
    FormsModule,
    UiAccessibilityModule,
    ButtonComponent
  ],
  templateUrl: './accessibility-demo.component.html',
  styleUrl: './accessibility-demo.component.scss'
})
export class AccessibilityDemoComponent implements OnInit, OnDestroy {
  private liveAnnouncer = inject(LiveAnnouncerService);
  private focusMonitor = inject(FocusMonitorService);
  private keyboardManager = inject(KeyboardManagerService);
  private highContrast = inject(HighContrastService);
  private a11yConfig = inject(A11yConfigService);

  @ViewChild('trapContainer') trapContainer!: ElementRef;
  @ViewChild('monitoredInput') monitoredInput!: ElementRef;

  // Demo state
  trapEnabled = false;
  showModal = false;
  currentPreferences: any = {};
  focusOrigin = '';
  announcementText = 'Hello, this is a test announcement!';
  selectedPoliteness: 'polite' | 'assertive' = 'polite';

  // Navigation demo items
  navigationItems = [
    { id: 1, label: 'Profile Settings', disabled: false },
    { id: 2, label: 'Account Details', disabled: false },
    { id: 3, label: 'Privacy Controls', disabled: true },
    { id: 4, label: 'Notifications', disabled: false },
    { id: 5, label: 'Security Options', disabled: false }
  ];

  // Grid navigation items
  gridItems = Array.from({ length: 12 }, (_, i) => ({
    id: i + 1,
    label: `Item ${i + 1}`,
    disabled: i === 5 // Make item 6 disabled
  }));

  ngOnInit(): void {
    this.setupKeyboardShortcuts();
    this.setupFocusMonitoring();
    this.getCurrentPreferences();
  }

  ngOnDestroy(): void {
    this.keyboardManager.unregisterAll();
  }

  private setupKeyboardShortcuts(): void {
    // Global shortcuts
    this.keyboardManager.registerGlobalShortcut('announce', {
      key: 'a',
      ctrlKey: true,
      shiftKey: true,
      description: 'Make announcement',
      handler: () => this.makeAnnouncement()
    });

    this.keyboardManager.registerGlobalShortcut('toggleModal', {
      key: 'm',
      ctrlKey: true,
      description: 'Toggle modal',
      handler: () => this.toggleModal()
    });
  }

  private setupFocusMonitoring(): void {
    // Monitor focus on the input field
    setTimeout(() => {
      if (this.monitoredInput) {
        this.focusMonitor.monitor(this.monitoredInput).subscribe(focusEvent => {
          this.focusOrigin = focusEvent.origin || 'none';
          if (focusEvent.origin) {
            this.liveAnnouncer.announce(
              `Input focused via ${focusEvent.origin}`,
              'polite'
            );
          }
        });
      }
    }, 100);
  }

  private getCurrentPreferences(): void {
    this.currentPreferences = this.highContrast.getCurrentPreferences();
  }

  // Demo actions
  makeAnnouncement(): void {
    this.liveAnnouncer.announce(this.announcementText, this.selectedPoliteness);
  }

  makeSequenceAnnouncement(): void {
    const messages = [
      'Starting process...',
      'Processing data...',
      'Validating information...',
      'Process completed successfully!'
    ];
    this.liveAnnouncer.announceSequence(messages, 'polite', 1500);
  }

  toggleFocusTrap(): void {
    this.trapEnabled = !this.trapEnabled;
    this.liveAnnouncer.announce(
      `Focus trap ${this.trapEnabled ? 'enabled' : 'disabled'}`,
      'assertive'
    );
  }

  toggleModal(): void {
    this.showModal = !this.showModal;
    if (this.showModal) {
      this.liveAnnouncer.announce('Modal opened', 'assertive');
    } else {
      this.liveAnnouncer.announce('Modal closed', 'assertive');
    }
  }

  focusViaKeyboard(): void {
    if (this.monitoredInput) {
      this.focusMonitor.focusVia(this.monitoredInput, 'keyboard');
    }
  }

  focusViaMouse(): void {
    if (this.monitoredInput) {
      this.focusMonitor.focusVia(this.monitoredInput, 'mouse');
    }
  }

  focusViaProgram(): void {
    if (this.monitoredInput) {
      this.focusMonitor.focusVia(this.monitoredInput, 'program');
    }
  }

  onNavigationChange(event: any): void {
    this.liveAnnouncer.announce(
      `Navigated to ${this.navigationItems[event.nextIndex]?.label}`,
      'polite'
    );
  }

  onGridNavigationChange(event: any): void {
    this.liveAnnouncer.announce(
      `Navigated to ${this.gridItems[event.nextIndex]?.label}`,
      'polite'
    );
  }

  announceError(): void {
    this.liveAnnouncer.announce(
      'Error: Please fix the required fields before continuing',
      'assertive'
    );
  }

  announceSuccess(): void {
    this.liveAnnouncer.announce(
      'Success: Your changes have been saved',
      'polite'
    );
  }

  announceLoading(): void {
    this.liveAnnouncer.announce(
      'Loading content, please wait...',
      'polite'
    );
  }

  refreshPreferences(): void {
    this.getCurrentPreferences();
    this.liveAnnouncer.announce('Accessibility preferences updated', 'polite');
  }

  simulateFormValidation(): void {
    // Simulate a form validation scenario
    this.liveAnnouncer.announce('Validating form...', 'polite');
    
    setTimeout(() => {
      this.liveAnnouncer.announce(
        'Form validation complete. 2 errors found.',
        'assertive'
      );
    }, 2000);
  }
}
