import { Component, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { TagInputComponent } from '../../../../../ui-essentials/src/lib/components/forms/tag-input/tag-input.component';
import { ButtonComponent } from '../../../../../ui-essentials/src/lib/components/buttons/button.component';
import { faTag, faPlus, faTimes, faRefresh } from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'ui-tag-input-demo',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TagInputComponent,
    ButtonComponent
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div style="padding: 2rem;">
      <h2>Tag Input Component Showcase</h2>
      
      <!-- Basic Tag Input Variants -->
      <section style="margin-bottom: 3rem;">
        <h3>Basic Variants</h3>
        
        <h4>Outlined (Default)</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            placeholder="Add tags (press Enter, Tab, or comma to add)"
            helpText="Separate tags with Enter, Tab, comma, semicolon, or pipe"
            [class]="'demo-tag-input'"
            (tagAdd)="handleTagAdd('outlined', $event)"
            (tagRemove)="handleTagRemove('outlined', $event)"
            (duplicateTag)="handleDuplicateTag('outlined', $event)"
            (tagValidationError)="handleValidationError('outlined', $event)">
          </ui-tag-input>
        </div>
        
        <h4>Filled</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            variant="filled"
            placeholder="Add filled style tags"
            helpText="This input uses the filled variant style"
            [class]="'demo-tag-input'"
            (tagAdd)="handleTagAdd('filled', $event)"
            (tagRemove)="handleTagRemove('filled', $event)">
          </ui-tag-input>
        </div>
      </section>

      <!-- Size Variants -->
      <section style="margin-bottom: 3rem;">
        <h3>Size Variants</h3>
        
        <h4>Small</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            size="sm"
            placeholder="Small size tags"
            helpText="Compact size for dense layouts"
            [class]="'demo-tag-input'"
            (tagAdd)="handleTagAdd('small', $event)"
            (tagRemove)="handleTagRemove('small', $event)">
          </ui-tag-input>
        </div>
        
        <h4>Medium (Default)</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            size="md"
            placeholder="Medium size tags"
            helpText="Standard size for most use cases"
            [class]="'demo-tag-input'"
            (tagAdd)="handleTagAdd('medium', $event)"
            (tagRemove)="handleTagRemove('medium', $event)">
          </ui-tag-input>
        </div>
        
        <h4>Large</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            size="lg"
            placeholder="Large size tags"
            helpText="Larger size for better accessibility"
            [class]="'demo-tag-input'"
            (tagAdd)="handleTagAdd('large', $event)"
            (tagRemove)="handleTagRemove('large', $event)">
          </ui-tag-input>
        </div>
      </section>

      <!-- Configuration Options -->
      <section style="margin-bottom: 3rem;">
        <h3>Configuration Options</h3>
        
        <h4>Max Tags (3)</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            placeholder="Maximum 3 tags allowed"
            [maxTags]="3"
            helpText="This input has a maximum of 3 tags"
            [class]="'demo-tag-input'"
            (maxTagsReached)="handleMaxTagsReached('max-tags')"
            (tagAdd)="handleTagAdd('max-tags', $event)"
            (tagRemove)="handleTagRemove('max-tags', $event)">
          </ui-tag-input>
        </div>
        
        <h4>Max Tag Length (10)</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            placeholder="Max 10 characters per tag"
            [maxTagLength]="10"
            helpText="Each tag can be at most 10 characters long"
            [class]="'demo-tag-input'"
            (tagValidationError)="handleValidationError('max-length', $event)"
            (tagAdd)="handleTagAdd('max-length', $event)"
            (tagRemove)="handleTagRemove('max-length', $event)">
          </ui-tag-input>
        </div>
        
        <h4>Allow Duplicates</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            placeholder="Duplicate tags allowed"
            [allowDuplicates]="true"
            helpText="This input allows duplicate tags"
            [class]="'demo-tag-input'"
            (tagAdd)="handleTagAdd('allow-duplicates', $event)"
            (tagRemove)="handleTagRemove('allow-duplicates', $event)">
          </ui-tag-input>
        </div>
        
        <h4>No Trimming</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            placeholder="Leading/trailing spaces preserved"
            [trimTags]="false"
            helpText="Tags preserve leading and trailing whitespace"
            [class]="'demo-tag-input'"
            (tagAdd)="handleTagAdd('no-trim', $event)"
            (tagRemove)="handleTagRemove('no-trim', $event)">
          </ui-tag-input>
        </div>
      </section>

      <!-- States -->
      <section style="margin-bottom: 3rem;">
        <h3>States</h3>
        
        <h4>Normal</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            placeholder="Normal interactive state"
            helpText="Standard interactive state"
            [class]="'demo-tag-input'"
            (tagAdd)="handleTagAdd('normal', $event)"
            (tagRemove)="handleTagRemove('normal', $event)">
          </ui-tag-input>
        </div>
        
        <h4>Disabled</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            placeholder="Disabled state"
            [disabled]="true"
            helpText="This input is disabled"
            [class]="'demo-tag-input'">
          </ui-tag-input>
        </div>
        
        <h4>Read Only</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            placeholder="Read only state"
            [readonly]="true"
            helpText="This input is read-only - tags cannot be added or removed"
            [class]="'demo-tag-input'">
          </ui-tag-input>
        </div>
        
        <h4>With Error</h4>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            placeholder="Input with error"
            errorMessage="This field is required and must contain at least one tag"
            [class]="'demo-tag-input'"
            (tagAdd)="handleTagAdd('error', $event)"
            (tagRemove)="handleTagRemove('error', $event)">
          </ui-tag-input>
        </div>
      </section>

      <!-- Form Integration -->
      <section style="margin-bottom: 3rem;">
        <h3>Form Integration</h3>
        <form [formGroup]="demoForm" (ngSubmit)="handleFormSubmit()" style="max-width: 600px;">
          <h4>Reactive Form Example</h4>
          <div style="margin-bottom: 1.5rem;">
            <ui-tag-input 
              formControlName="tags"
              placeholder="Required: Add at least 2 tags"
              helpText="This field is required and uses reactive forms validation"
              [class]="'demo-tag-input'"
              [errorMessage]="getFormFieldError('tags')"
              (tagAdd)="handleTagAdd('form', $event)"
              (tagRemove)="handleTagRemove('form', $event)">
            </ui-tag-input>
          </div>
          
          <h4>Skills (Optional)</h4>
          <div style="margin-bottom: 1.5rem;">
            <ui-tag-input 
              formControlName="skills"
              placeholder="Add your skills"
              [maxTags]="5"
              helpText="Optional field - up to 5 skills"
              [class]="'demo-tag-input'"
              (tagAdd)="handleTagAdd('skills', $event)"
              (tagRemove)="handleTagRemove('skills', $event)">
            </ui-tag-input>
          </div>
          
          <div style="display: flex; gap: 1rem; align-items: center;">
            <ui-button 
              type="submit" 
              variant="filled" 
              [disabled]="demoForm.invalid">
              Submit Form
            </ui-button>
            <ui-button 
              type="button" 
              variant="tonal" 
              [icon]="faRefresh" 
              iconPosition="left"
              (clicked)="resetForm()">
              Reset
            </ui-button>
          </div>
          
          @if (formSubmitted) {
            <div style="margin-top: 1rem; padding: 1rem; background: #e8f5e8; border-radius: 4px; border-left: 4px solid #4caf50;">
              <strong>Form Submitted!</strong><br>
              <strong>Tags:</strong> {{ formData.tags?.join(', ') || 'None' }}<br>
              <strong>Skills:</strong> {{ formData.skills?.join(', ') || 'None' }}
            </div>
          }
        </form>
      </section>

      <!-- Programmatic Control -->
      <section style="margin-bottom: 3rem;">
        <h3>Programmatic Control</h3>
        <div style="margin-bottom: 1.5rem;">
          <ui-tag-input 
            #programmaticInput
            placeholder="Controlled programmatically"
            helpText="Use the buttons below to control this input"
            [class]="'demo-tag-input'">
          </ui-tag-input>
        </div>
        
        <div style="display: flex; gap: 1rem; flex-wrap: wrap; margin-bottom: 1rem;">
          <ui-button 
            variant="outlined" 
            size="small" 
            [icon]="faPlus" 
            iconPosition="left"
            (clicked)="addPredefinedTag(programmaticInput)">
            Add Random Tag
          </ui-button>
          <ui-button 
            variant="outlined" 
            size="small" 
            (clicked)="clearProgrammaticInput(programmaticInput)">
            Clear All
          </ui-button>
          <ui-button 
            variant="outlined" 
            size="small" 
            (clicked)="addMultipleTags(programmaticInput)">
            Add Multiple
          </ui-button>
          <ui-button 
            variant="outlined" 
            size="small" 
            (clicked)="getTagsAsString(programmaticInput)">
            Get as String
          </ui-button>
        </div>
      </section>

      <!-- Usage Examples -->
      <section style="margin-bottom: 3rem;">
        <h3>Usage Examples</h3>
        <div style="background: #f8f9fa; padding: 1.5rem; border-radius: 8px; border-left: 4px solid #007bff;">
          <h4>Basic Usage:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>&lt;ui-tag-input 
  placeholder="Add tags..."
  (tagAdd)="onTagAdd($event)"
  (tagRemove)="onTagRemove($event)"&gt;
&lt;/ui-tag-input&gt;</code></pre>

          <h4>With Constraints:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>&lt;ui-tag-input 
  placeholder="Add up to 5 tags"
  [maxTags]="5"
  [maxTagLength]="20"
  [allowDuplicates]="false"
  helpText="Each tag can be up to 20 characters"
  (maxTagsReached)="onMaxTags()"
  (duplicateTag)="onDuplicate($event)"&gt;
&lt;/ui-tag-input&gt;</code></pre>

          <h4>Form Integration:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>&lt;form [formGroup]="myForm"&gt;
  &lt;ui-tag-input 
    formControlName="tags"
    placeholder="Required tags"
    [errorMessage]="getFieldError('tags')"&gt;
  &lt;/ui-tag-input&gt;
&lt;/form&gt;</code></pre>

          <h4>Custom Separators:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>&lt;ui-tag-input 
  placeholder="Use space or dash to separate"
  [separators]="[' ', '-']"
  helpText="Tags separated by space or dash"&gt;
&lt;/ui-tag-input&gt;</code></pre>
        </div>
      </section>

      <!-- Event Log -->
      <section style="margin-bottom: 3rem;">
        <h3>Event Log</h3>
        @if (lastAction) {
          <div style="margin-bottom: 1rem; padding: 1rem; background: #e3f2fd; border-radius: 4px;">
            <strong>Last action:</strong> {{ lastAction }}
          </div>
        }
        <div style="display: flex; gap: 1rem; flex-wrap: wrap;">
          <ui-button variant="tonal" (clicked)="clearEventLog()">Clear Log</ui-button>
          <ui-button variant="outlined" (clicked)="showAlert('Tag Input demo complete!')">Show Alert</ui-button>
        </div>
      </section>
    </div>
  `,
  styles: [`
    h2 {
      color: hsl(279, 14%, 11%);
      font-size: 2rem;
      margin-bottom: 2rem;
      border-bottom: 2px solid hsl(258, 100%, 47%);
      padding-bottom: 0.5rem;
    }
    
    h3 {
      color: hsl(279, 14%, 25%);
      font-size: 1.5rem;
      margin-bottom: 1rem;
    }
    
    h4 {
      color: hsl(287, 12%, 35%);
      font-size: 1.125rem;
      margin-bottom: 0.75rem;
    }
    
    section {
      border: 1px solid hsl(289, 14%, 90%);
      border-radius: 8px;
      padding: 1.5rem;
      background: hsl(286, 20%, 99%);
    }
    
    .demo-tag-input {
      width: 100%;
      max-width: 500px;
    }
    
    pre {
      font-size: 0.875rem;
      line-height: 1.5;
      margin: 0.5rem 0;
    }
    
    code {
      font-family: 'JetBrains Mono', monospace;
      color: #d63384;
    }
  `]
})
export class TagInputDemoComponent {
  lastAction: string = '';
  
  // FontAwesome icons
  faTag = faTag;
  faPlus = faPlus;
  faTimes = faTimes;
  faRefresh = faRefresh;
  
  // Form
  demoForm = new FormGroup({
    tags: new FormControl<string[]>([], [
      Validators.required,
      this.minTagsValidator(2)
    ]),
    skills: new FormControl<string[]>([])
  });
  
  formSubmitted = false;
  formData: { tags?: string[]; skills?: string[] } = {};
  
  // Predefined tags for programmatic control
  predefinedTags = [
    'JavaScript', 'TypeScript', 'Angular', 'React', 'Vue',
    'HTML', 'CSS', 'SCSS', 'Node.js', 'Python', 'Java',
    'Design', 'Frontend', 'Backend', 'Fullstack'
  ];

  // Event handlers
  handleTagAdd(source: string, tag: string): void {
    this.lastAction = `Tag added (${source}): "${tag}"`;
    console.log(`Tag added (${source}):`, tag);
  }

  handleTagRemove(source: string, event: { tag: string; index: number }): void {
    this.lastAction = `Tag removed (${source}): "${event.tag}" at index ${event.index}`;
    console.log(`Tag removed (${source}):`, event);
  }

  handleDuplicateTag(source: string, tag: string): void {
    this.lastAction = `Duplicate tag attempted (${source}): "${tag}"`;
    console.log(`Duplicate tag attempted (${source}):`, tag);
  }

  handleValidationError(source: string, error: { tag: string; error: string }): void {
    this.lastAction = `Validation error (${source}): "${error.tag}" - ${error.error}`;
    console.log(`Validation error (${source}):`, error);
  }

  handleMaxTagsReached(source: string): void {
    this.lastAction = `Maximum tags reached (${source})`;
    console.log(`Maximum tags reached (${source})`);
  }

  // Form methods
  minTagsValidator(min: number) {
    return (control: any) => {
      const tags = control.value;
      if (!tags || tags.length < min) {
        return { minTags: { required: min, actual: tags?.length || 0 } };
      }
      return null;
    };
  }

  getFormFieldError(fieldName: string): string | undefined {
    const field = this.demoForm.get(fieldName);
    if (field && field.invalid && (field.dirty || field.touched)) {
      const errors = field.errors;
      if (errors?.['required']) {
        return 'This field is required';
      }
      if (errors?.['minTags']) {
        return `At least ${errors['minTags'].required} tags are required`;
      }
    }
    return undefined;
  }

  handleFormSubmit(): void {
    if (this.demoForm.valid) {
      const formValue = this.demoForm.value;
      this.formData = {
        tags: formValue.tags || [],
        skills: formValue.skills || []
      };
      this.formSubmitted = true;
      this.lastAction = 'Form submitted successfully';
      console.log('Form submitted:', this.formData);
    } else {
      this.lastAction = 'Form submission failed - validation errors';
      console.log('Form invalid:', this.demoForm.errors);
    }
  }

  resetForm(): void {
    this.demoForm.reset();
    this.formSubmitted = false;
    this.formData = {};
    this.lastAction = 'Form reset';
    console.log('Form reset');
  }

  // Programmatic control methods
  addPredefinedTag(tagInput: TagInputComponent): void {
    const randomTag = this.predefinedTags[Math.floor(Math.random() * this.predefinedTags.length)];
    const success = tagInput.addTagProgrammatically(randomTag);
    this.lastAction = success 
      ? `Programmatically added: "${randomTag}"` 
      : `Failed to add: "${randomTag}"`;
    console.log('Add predefined tag result:', success, randomTag);
  }

  clearProgrammaticInput(tagInput: TagInputComponent): void {
    tagInput.clear();
    this.lastAction = 'Programmatically cleared all tags';
    console.log('Cleared programmatic input');
  }

  addMultipleTags(tagInput: TagInputComponent): void {
    const tagsToAdd = ['HTML', 'CSS', 'JavaScript'];
    let addedCount = 0;
    
    tagsToAdd.forEach(tag => {
      if (tagInput.addTagProgrammatically(tag)) {
        addedCount++;
      }
    });
    
    this.lastAction = `Programmatically added ${addedCount}/${tagsToAdd.length} tags`;
    console.log(`Added ${addedCount} multiple tags`);
  }

  getTagsAsString(tagInput: TagInputComponent): void {
    const tagsString = tagInput.getTagsAsString();
    this.lastAction = `Tags as string: "${tagsString}"`;
    alert(`Current tags: ${tagsString || 'None'}`);
    console.log('Tags as string:', tagsString);
  }

  // Utility methods
  clearEventLog(): void {
    this.lastAction = '';
  }

  showAlert(message: string): void {
    alert(message);
    this.lastAction = 'Alert shown';
  }
}