import { Component, ChangeDetectionStrategy, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';
import { ColorPickerComponent } from '../../../../../ui-essentials/src/lib/components/forms/color-picker/color-picker.component';

@Component({
  selector: 'ui-color-picker-demo',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    ColorPickerComponent
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="demo-container">
      <h2>Color Picker Component Showcase</h2>
      
      <!-- Basic Color Picker -->
      <section class="demo-section">
        <h3>Basic Color Picker</h3>
        <div class="demo-row">
          <ui-color-picker 
            label="Choose a color" 
            description="Select your preferred color"
            [(ngModel)]="basicColor"
            (colorChange)="onColorChange('basic', $event)"
          />
          <div class="demo-info">
            <p><strong>Selected:</strong> {{ basicColor() }}</p>
            <div class="color-preview" [style.background-color]="basicColor()"></div>
          </div>
        </div>
      </section>

      <!-- Size Variants -->
      <section class="demo-section">
        <h3>Size Variants</h3>
        <div class="demo-grid">
          <div class="demo-item">
            <ui-color-picker 
              label="Small (sm)" 
              size="sm"
              [(ngModel)]="sizeSmall"
              (colorChange)="onColorChange('size-sm', $event)"
            />
          </div>
          <div class="demo-item">
            <ui-color-picker 
              label="Medium (md)" 
              size="md"
              [(ngModel)]="sizeMedium"
              (colorChange)="onColorChange('size-md', $event)"
            />
          </div>
          <div class="demo-item">
            <ui-color-picker 
              label="Large (lg)" 
              size="lg"
              [(ngModel)]="sizeLarge"
              (colorChange)="onColorChange('size-lg', $event)"
            />
          </div>
        </div>
      </section>

      <!-- Color Variants -->
      <section class="demo-section">
        <h3>Color Variants</h3>
        <div class="demo-grid">
          <div class="demo-item">
            <ui-color-picker 
              label="Primary" 
              variant="primary"
              [(ngModel)]="variantPrimary"
              (colorChange)="onColorChange('variant-primary', $event)"
            />
          </div>
          <div class="demo-item">
            <ui-color-picker 
              label="Secondary" 
              variant="secondary"
              [(ngModel)]="variantSecondary"
              (colorChange)="onColorChange('variant-secondary', $event)"
            />
          </div>
          <div class="demo-item">
            <ui-color-picker 
              label="Success" 
              variant="success"
              [(ngModel)]="variantSuccess"
              (colorChange)="onColorChange('variant-success', $event)"
            />
          </div>
          <div class="demo-item">
            <ui-color-picker 
              label="Danger" 
              variant="danger"
              [(ngModel)]="variantDanger"
              (colorChange)="onColorChange('variant-danger', $event)"
            />
          </div>
        </div>
      </section>

      <!-- States -->
      <section class="demo-section">
        <h3>States</h3>
        <div class="demo-grid">
          <div class="demo-item">
            <ui-color-picker 
              label="Default State" 
              [(ngModel)]="stateDefault"
              (colorChange)="onColorChange('state-default', $event)"
            />
          </div>
          <div class="demo-item">
            <ui-color-picker 
              label="Error State" 
              state="error"
              description="This field has an error"
              [(ngModel)]="stateError"
              (colorChange)="onColorChange('state-error', $event)"
            />
          </div>
          <div class="demo-item">
            <ui-color-picker 
              label="Disabled State" 
              [disabled]="true"
              [(ngModel)]="stateDisabled"
            />
          </div>
        </div>
      </section>

      <!-- Required Field -->
      <section class="demo-section">
        <h3>Required Field</h3>
        <div class="demo-row">
          <ui-color-picker 
            label="Brand Color" 
            description="Choose your brand's primary color"
            [required]="true"
            [(ngModel)]="requiredColor"
            (colorChange)="onColorChange('required', $event)"
          />
        </div>
      </section>

      <!-- Reactive Forms Integration -->
      <section class="demo-section">
        <h3>Reactive Forms Integration</h3>
        <form [formGroup]="colorForm" class="demo-form">
          <div class="demo-row">
            <ui-color-picker 
              label="Background Color" 
              description="Select background color for your theme"
              formControlName="backgroundColor"
              (colorChange)="onColorChange('form-bg', $event)"
            />
            <ui-color-picker 
              label="Text Color" 
              description="Select text color for your theme"
              formControlName="textColor"
              (colorChange)="onColorChange('form-text', $event)"
            />
          </div>
          <div class="demo-form-info">
            <h4>Form Values:</h4>
            <pre>{{ getFormValues() }}</pre>
          </div>
          <div class="demo-theme-preview">
            <h4>Theme Preview:</h4>
            <div 
              class="theme-sample"
              [style.background-color]="colorForm.get('backgroundColor')?.value || '#FFFFFF'"
              [style.color]="colorForm.get('textColor')?.value || '#000000'">
              Sample text with selected colors
            </div>
          </div>
        </form>
      </section>

      <!-- Interactive Demo -->
      <section class="demo-section">
        <h3>Interactive Demo</h3>
        <div class="demo-row">
          <ui-color-picker 
            label="Interactive Color" 
            description="Watch the events in the console"
            [(ngModel)]="interactiveColor"
            (colorChange)="onInteractiveColorChange($event)"
            (colorFocus)="onColorFocus($event)"
            (colorBlur)="onColorBlur($event)"
          />
          <div class="demo-info">
            <h4>Event Log:</h4>
            <div class="event-log">
              @for (event of eventLog(); track event.id) {
                <div class="event-entry" [class.event-entry--recent]="event.recent">
                  <span class="event-type">{{ event.type }}</span>
                  <span class="event-value">{{ event.value }}</span>
                  <span class="event-time">{{ event.time }}</span>
                </div>
              }
            </div>
            <button class="clear-log-btn" (click)="clearEventLog()">Clear Log</button>
          </div>
        </div>
      </section>

      <!-- Preset Colors Demo -->
      <section class="demo-section">
        <h3>Preset Colors</h3>
        <div class="demo-row">
          <ui-color-picker 
            label="Select or enter color" 
            [(ngModel)]="presetColor"
            (colorChange)="onColorChange('preset', $event)"
          />
          <div class="preset-colors">
            <h4>Quick Colors:</h4>
            <div class="preset-grid">
              @for (color of presetColors; track color.name) {
                <button 
                  class="preset-color-btn" 
                  [style.background-color]="color.hex"
                  [attr.title]="color.name + ' (' + color.hex + ')'"
                  (click)="selectPresetColor(color.hex)">
                  <span class="sr-only">{{ color.name }}</span>
                </button>
              }
            </div>
          </div>
        </div>
      </section>
    </div>
  `,
  styleUrl: './color-picker-demo.component.scss'
})
export class ColorPickerDemoComponent {
  // Basic demo colors
  basicColor = signal<string>('#3498db');
  
  // Size variants
  sizeSmall = signal<string>('#e74c3c');
  sizeMedium = signal<string>('#2ecc71');
  sizeLarge = signal<string>('#f39c12');
  
  // Color variants
  variantPrimary = signal<string>('#3498db');
  variantSecondary = signal<string>('#95a5a6');
  variantSuccess = signal<string>('#2ecc71');
  variantDanger = signal<string>('#e74c3c');
  
  // States
  stateDefault = signal<string>('#9b59b6');
  stateError = signal<string>('#e74c3c');
  stateDisabled = signal<string>('#bdc3c7');
  
  // Required field
  requiredColor = signal<string>('#1abc9c');
  
  // Interactive demo
  interactiveColor = signal<string>('#34495e');
  eventLog = signal<Array<{id: number, type: string, value: string, time: string, recent: boolean}>>([]);
  private eventIdCounter = 0;
  
  // Preset colors
  presetColor = signal<string>('#ff6b6b');
  presetColors = [
    { name: 'Red', hex: '#e74c3c' },
    { name: 'Orange', hex: '#f39c12' },
    { name: 'Yellow', hex: '#f1c40f' },
    { name: 'Green', hex: '#2ecc71' },
    { name: 'Blue', hex: '#3498db' },
    { name: 'Purple', hex: '#9b59b6' },
    { name: 'Pink', hex: '#e91e63' },
    { name: 'Teal', hex: '#1abc9c' },
    { name: 'Gray', hex: '#95a5a6' },
    { name: 'Black', hex: '#2c3e50' },
    { name: 'White', hex: '#ecf0f1' },
    { name: 'Brown', hex: '#8d4925' }
  ];
  
  // Reactive forms
  colorForm = new FormGroup({
    backgroundColor: new FormControl('#ffffff'),
    textColor: new FormControl('#333333')
  });

  onColorChange(source: string, color: string): void {
    console.log(`Color changed (${source}):`, color);
  }

  onInteractiveColorChange(color: string): void {
    this.addEventToLog('change', color);
  }

  onColorFocus(event: FocusEvent): void {
    this.addEventToLog('focus', 'Color picker focused');
  }

  onColorBlur(event: FocusEvent): void {
    this.addEventToLog('blur', 'Color picker blurred');
  }

  private addEventToLog(type: string, value: string): void {
    const newEvent = {
      id: this.eventIdCounter++,
      type,
      value,
      time: new Date().toLocaleTimeString(),
      recent: true
    };
    
    const currentLog = this.eventLog();
    const updatedLog = [newEvent, ...currentLog.slice(0, 9)].map((event, index) => ({
      ...event,
      recent: index === 0
    }));
    
    this.eventLog.set(updatedLog);
    
    // Remove recent flag after animation
    setTimeout(() => {
      const logWithoutRecent = this.eventLog().map(event => ({
        ...event,
        recent: false
      }));
      this.eventLog.set(logWithoutRecent);
    }, 1000);
  }

  clearEventLog(): void {
    this.eventLog.set([]);
    this.eventIdCounter = 0;
  }

  selectPresetColor(color: string): void {
    this.presetColor.set(color);
  }

  getFormValues(): string {
    return JSON.stringify(this.colorForm.value, null, 2);
  }
}