import { Component, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';
import { AutocompleteComponent, AutocompleteOption } from '../../../../../ui-essentials/src/lib/components/forms/autocomplete/autocomplete.component';

@Component({
  selector: 'ui-autocomplete-demo',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, AutocompleteComponent],
  template: `
    <div class="demo-container">
      <h2>Autocomplete Demo</h2>
      
      <!-- Size Variants -->
      <section class="demo-section">
        <h3>Sizes</h3>
        <div class="demo-row">
          <div class="demo-item">
            <label>Small</label>
            <ui-autocomplete
              size="sm"
              placeholder="Small autocomplete..."
              [options]="countries"
              (valueChange)="onValueChange('small', $event)"
            />
          </div>
          <div class="demo-item">
            <label>Medium (default)</label>
            <ui-autocomplete
              size="md"
              placeholder="Medium autocomplete..."
              [options]="countries"
              (valueChange)="onValueChange('medium', $event)"
            />
          </div>
          <div class="demo-item">
            <label>Large</label>
            <ui-autocomplete
              size="lg"
              placeholder="Large autocomplete..."
              [options]="countries"
              (valueChange)="onValueChange('large', $event)"
            />
          </div>
        </div>
      </section>
      
      <!-- Variant Styles -->
      <section class="demo-section">
        <h3>Variants</h3>
        <div class="demo-row">
          <div class="demo-item">
            <label>Outlined (default)</label>
            <ui-autocomplete
              variant="outlined"
              placeholder="Outlined autocomplete..."
              [options]="countries"
              (valueChange)="onValueChange('outlined', $event)"
            />
          </div>
          <div class="demo-item">
            <label>Filled</label>
            <ui-autocomplete
              variant="filled"
              placeholder="Filled autocomplete..."
              [options]="countries"
              (valueChange)="onValueChange('filled', $event)"
            />
          </div>
        </div>
      </section>
      
      <!-- With Labels and Helper Text -->
      <section class="demo-section">
        <h3>With Labels & Helper Text</h3>
        <div class="demo-row">
          <div class="demo-item">
            <ui-autocomplete
              label="Country"
              placeholder="Select a country..."
              helperText="Choose your country of residence"
              [options]="countries"
              [required]="true"
              (valueChange)="onValueChange('labeled', $event)"
            />
          </div>
          <div class="demo-item">
            <ui-autocomplete
              label="Programming Language"
              placeholder="Search languages..."
              helperText="Find your favorite programming language"
              [options]="programmingLanguages"
              (valueChange)="onValueChange('languages', $event)"
            />
          </div>
        </div>
      </section>
      
      <!-- States -->
      <section class="demo-section">
        <h3>States</h3>
        <div class="demo-row">
          <div class="demo-item">
            <label>Disabled</label>
            <ui-autocomplete
              placeholder="Disabled autocomplete..."
              [options]="countries"
              [disabled]="true"
            />
          </div>
          <div class="demo-item">
            <label>Read-only</label>
            <ui-autocomplete
              placeholder="Read-only autocomplete..."
              [options]="countries"
              [readonly]="true"
            />
          </div>
          <div class="demo-item">
            <label>Loading</label>
            <ui-autocomplete
              placeholder="Loading autocomplete..."
              [options]="countries"
              [loading]="true"
            />
          </div>
        </div>
      </section>
      
      <!-- Error State -->
      <section class="demo-section">
        <h3>Error State</h3>
        <div class="demo-row">
          <div class="demo-item">
            <ui-autocomplete
              label="Country (Required)"
              placeholder="Select a country..."
              errorText="Please select a valid country"
              [options]="countries"
              [required]="true"
            />
          </div>
        </div>
      </section>
      
      <!-- Advanced Features -->
      <section class="demo-section">
        <h3>Advanced Features</h3>
        <div class="demo-row">
          <div class="demo-item">
            <label>With Secondary Text</label>
            <ui-autocomplete
              placeholder="Search users..."
              [options]="users"
              (valueChange)="onValueChange('users', $event)"
              (optionSelected)="onOptionSelected($event)"
            />
          </div>
          <div class="demo-item">
            <label>Custom Filter (starts with)</label>
            <ui-autocomplete
              placeholder="Type first letters..."
              [options]="countries"
              [filterFn]="startsWithFilter"
              (valueChange)="onValueChange('custom-filter', $event)"
            />
          </div>
          <div class="demo-item">
            <label>Limited Options (max 3)</label>
            <ui-autocomplete
              placeholder="Search countries (max 3)..."
              [options]="countries"
              [maxOptions]="3"
              (valueChange)="onValueChange('limited', $event)"
            />
          </div>
        </div>
      </section>
      
      <!-- Behavior Options -->
      <section class="demo-section">
        <h3>Behavior Options</h3>
        <div class="demo-row">
          <div class="demo-item">
            <label>Open on Focus</label>
            <ui-autocomplete
              placeholder="Focus to see options..."
              [options]="fruits"
              [openOnFocus]="true"
              [minQueryLength]="0"
              (valueChange)="onValueChange('open-focus', $event)"
            />
          </div>
          <div class="demo-item">
            <label>Not Clearable</label>
            <ui-autocomplete
              placeholder="No clear button..."
              [options]="fruits"
              [clearable]="false"
              (valueChange)="onValueChange('not-clearable', $event)"
            />
          </div>
          <div class="demo-item">
            <label>Min Query Length (3)</label>
            <ui-autocomplete
              placeholder="Type at least 3 characters..."
              [options]="countries"
              [minQueryLength]="3"
              helperText="Start typing to see suggestions"
              (valueChange)="onValueChange('min-query', $event)"
            />
          </div>
        </div>
      </section>
      
      <!-- Reactive Forms Integration -->
      <section class="demo-section">
        <h3>Reactive Forms Integration</h3>
        <form [formGroup]="demoForm" class="demo-form">
          <div class="demo-row">
            <div class="demo-item">
              <ui-autocomplete
                label="Favorite Country"
                placeholder="Select your favorite country..."
                helperText="This is part of a reactive form"
                [options]="countries"
                formControlName="favoriteCountry"
                [required]="true"
              />
            </div>
            <div class="demo-item">
              <ui-autocomplete
                label="Preferred Language"
                placeholder="Choose a programming language..."
                [options]="programmingLanguages"
                formControlName="preferredLanguage"
              />
            </div>
          </div>
          
          <div class="form-values">
            <h4>Form Values:</h4>
            <pre>{{ demoForm.value | json }}</pre>
            <p><strong>Form Valid:</strong> {{ demoForm.valid }}</p>
          </div>
        </form>
      </section>
      
      <!-- Event Logging -->
      <section class="demo-section">
        <h3>Event Monitoring</h3>
        <div class="demo-row">
          <div class="demo-item">
            <ui-autocomplete
              label="Event Test"
              placeholder="Type and select to see events..."
              [options]="fruits"
              (valueChange)="logEvent('valueChange', $event)"
              (queryChange)="logEvent('queryChange', $event)"
              (optionSelected)="logEvent('optionSelected', $event)"
              (focused)="logEvent('focused', $event)"
              (blurred)="logEvent('blurred', $event)"
              (dropdownOpen)="logEvent('dropdownOpen', $event)"
              (dropdownClose)="logEvent('dropdownClose', $event)"
            />
          </div>
        </div>
        
        <div class="event-log">
          <h4>Event Log:</h4>
          <div class="log-container">
            @for (event of eventLog(); track event.id) {
              <div class="log-entry">
                <span class="log-event">{{ event.type }}</span>
                <span class="log-data">{{ event.data }}</span>
                <span class="log-time">{{ event.time }}</span>
              </div>
            }
          </div>
          <button type="button" (click)="clearEventLog()" class="clear-log-btn">
            Clear Log
          </button>
        </div>
      </section>
    </div>
  `,
  styleUrl: './autocomplete-demo.component.scss'
})
export class AutocompleteDemoComponent {
  // Form for reactive forms demo
  demoForm = new FormGroup({
    favoriteCountry: new FormControl(''),
    preferredLanguage: new FormControl('')
  });

  // Event logging
  private _eventLog = signal<Array<{id: number, type: string, data: string, time: string}>>([]);
  eventLog = this._eventLog.asReadonly();
  private eventCounter = 0;

  // Sample data
  countries: AutocompleteOption[] = [
    { value: 'us', label: 'United States' },
    { value: 'ca', label: 'Canada' },
    { value: 'gb', label: 'United Kingdom' },
    { value: 'de', label: 'Germany' },
    { value: 'fr', label: 'France' },
    { value: 'it', label: 'Italy' },
    { value: 'es', label: 'Spain' },
    { value: 'jp', label: 'Japan' },
    { value: 'kr', label: 'South Korea' },
    { value: 'cn', label: 'China' },
    { value: 'in', label: 'India' },
    { value: 'au', label: 'Australia' },
    { value: 'br', label: 'Brazil' },
    { value: 'mx', label: 'Mexico' },
    { value: 'ru', label: 'Russia' },
    { value: 'za', label: 'South Africa' },
    { value: 'ng', label: 'Nigeria' },
    { value: 'eg', label: 'Egypt' }
  ];

  programmingLanguages: AutocompleteOption[] = [
    { value: 'typescript', label: 'TypeScript' },
    { value: 'javascript', label: 'JavaScript' },
    { value: 'python', label: 'Python' },
    { value: 'java', label: 'Java' },
    { value: 'csharp', label: 'C#' },
    { value: 'cpp', label: 'C++' },
    { value: 'go', label: 'Go' },
    { value: 'rust', label: 'Rust' },
    { value: 'swift', label: 'Swift' },
    { value: 'kotlin', label: 'Kotlin' },
    { value: 'php', label: 'PHP' },
    { value: 'ruby', label: 'Ruby' },
    { value: 'scala', label: 'Scala' },
    { value: 'dart', label: 'Dart' }
  ];

  users: AutocompleteOption[] = [
    { value: '1', label: 'John Doe', secondaryText: 'john.doe@example.com' },
    { value: '2', label: 'Jane Smith', secondaryText: 'jane.smith@example.com' },
    { value: '3', label: 'Bob Johnson', secondaryText: 'bob.johnson@example.com' },
    { value: '4', label: 'Alice Brown', secondaryText: 'alice.brown@example.com' },
    { value: '5', label: 'Charlie Wilson', secondaryText: 'charlie.wilson@example.com' },
    { value: '6', label: 'Diana Davis', secondaryText: 'diana.davis@example.com' },
    { value: '7', label: 'Eve Miller', secondaryText: 'eve.miller@example.com' },
    { value: '8', label: 'Frank Garcia', secondaryText: 'frank.garcia@example.com' }
  ];

  fruits: AutocompleteOption[] = [
    { value: 'apple', label: 'Apple' },
    { value: 'banana', label: 'Banana' },
    { value: 'orange', label: 'Orange' },
    { value: 'grape', label: 'Grape' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'blueberry', label: 'Blueberry' },
    { value: 'pineapple', label: 'Pineapple' },
    { value: 'mango', label: 'Mango' },
    { value: 'kiwi', label: 'Kiwi' },
    { value: 'peach', label: 'Peach' },
    { value: 'cherry', label: 'Cherry' },
    { value: 'watermelon', label: 'Watermelon' }
  ];

  // Custom filter function
  startsWithFilter = (option: AutocompleteOption, query: string): boolean => {
    return option.label.toLowerCase().startsWith(query.toLowerCase());
  };

  onValueChange(source: string, value: any): void {
    console.log(`Value changed (${source}):`, value);
  }

  onOptionSelected(option: AutocompleteOption): void {
    console.log('Option selected:', option);
  }

  logEvent(type: string, data: any): void {
    const entry = {
      id: ++this.eventCounter,
      type,
      data: typeof data === 'object' ? JSON.stringify(data) : String(data),
      time: new Date().toLocaleTimeString()
    };
    
    const currentLog = this._eventLog();
    this._eventLog.set([entry, ...currentLog.slice(0, 19)]); // Keep last 20 events
  }

  clearEventLog(): void {
    this._eventLog.set([]);
    this.eventCounter = 0;
  }
}