import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { FloatingToolbarComponent, ToolbarAction, FloatingToolbarConfig } from '../../../../../ui-essentials/src/lib/components/overlays/floating-toolbar/floating-toolbar.component';

@Component({
  selector: 'ui-floating-toolbar-demo',
  standalone: true,
  imports: [CommonModule, FormsModule, FloatingToolbarComponent],
  template: `
    <div class="demo-container">
      <h2>Floating Toolbar Demo</h2>
      
      <!-- Size Variants -->
      <section class="demo-section">
        <h3>Size Variants</h3>
        <div class="demo-row">
          @for (size of sizes; track size) {
            <div class="demo-item">
              <button 
                class="demo-trigger-button"
                #triggerButton
                (click)="showToolbar('size-' + size, triggerButton, { size: size })"
              >
                {{ size }} Toolbar
              </button>
            </div>
          }
        </div>
      </section>

      <!-- Variant Styles -->
      <section class="demo-section">
        <h3>Style Variants</h3>
        <div class="demo-row">
          @for (variant of variants; track variant) {
            <div class="demo-item">
              <button 
                class="demo-trigger-button"
                #triggerButton
                (click)="showToolbar('variant-' + variant, triggerButton, { variant: variant })"
              >
                {{ variant | titlecase }} Style
              </button>
            </div>
          }
        </div>
      </section>

      <!-- Position Variants -->
      <section class="demo-section">
        <h3>Position Variants</h3>
        <div class="demo-row demo-row--center">
          <div class="demo-position-container">
            @for (position of positions; track position) {
              <button 
                class="demo-position-button demo-position-button--{{ position }}"
                #triggerButton
                (click)="showToolbar('position-' + position, triggerButton, { position: position })"
              >
                {{ position }}
              </button>
            }
          </div>
        </div>
      </section>

      <!-- Context-Sensitive Actions -->
      <section class="demo-section">
        <h3>Context-Sensitive Actions</h3>
        <div class="demo-row">
          <div class="demo-context-area" #textContext>
            <p>
              Select this text to see a text editing toolbar with cut, copy, paste, and formatting options.
              The toolbar will appear automatically when you make a selection.
            </p>
          </div>
          <div class="demo-context-area" #imageContext>
            <img 
              src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZGRkIi8+CiAgPHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPkltYWdlPC90ZXh0Pgo8L3N2Zz4K"
              alt="Demo Image"
              (contextmenu)="showContextualToolbar($event, imageActions, 'image')"
            />
            <p class="demo-hint">Right-click the image for image editing options</p>
          </div>
        </div>
      </section>

      <!-- Auto-Hide Behavior -->
      <section class="demo-section">
        <h3>Auto-Hide Behavior</h3>
        <div class="demo-row">
          <button 
            class="demo-trigger-button"
            #autoHideButton
            (click)="showAutoHideToolbar(autoHideButton)"
          >
            Show Auto-Hide Toolbar (3 seconds)
          </button>
        </div>
      </section>

      <!-- Custom Actions Demo -->
      <section class="demo-section">
        <h3>Custom Actions</h3>
        <div class="demo-row">
          <button 
            class="demo-trigger-button"
            #customButton
            (click)="showCustomActionsToolbar(customButton)"
          >
            Custom Actions Toolbar
          </button>
        </div>
        
        <div class="demo-output">
          <h4>Action Log:</h4>
          <div class="demo-log">
            @for (logEntry of actionLog; track $index) {
              <div class="demo-log-entry">{{ logEntry }}</div>
            }
            @if (actionLog.length === 0) {
              <div class="demo-log-empty">No actions performed yet...</div>
            }
          </div>
        </div>
      </section>

      <!-- Interactive Examples -->
      <section class="demo-section">
        <h3>Interactive Examples</h3>
        
        <!-- Editable Text Area -->
        <div class="demo-subsection">
          <h4>Editable Text with Formatting Toolbar</h4>
          <div 
            class="demo-editor"
            contenteditable="true"
            #editableArea
            (mouseup)="handleTextSelection(editableArea)"
            (keyup)="handleTextSelection(editableArea)"
          >
            <p>This is an editable text area. Select text to see formatting options in the floating toolbar.</p>
            <p><strong>Bold text</strong>, <em>italic text</em>, and <u>underlined text</u> are supported.</p>
          </div>
        </div>
        
        <!-- Data Table with Row Actions -->
        <div class="demo-subsection">
          <h4>Data Table with Row Actions</h4>
          <table class="demo-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              @for (user of sampleUsers; track user.id) {
                <tr 
                  #tableRow 
                  class="demo-table-row"
                  [class.demo-table-row--selected]="selectedUserId === user.id"
                  (click)="selectUser(user.id, tableRow)"
                >
                  <td>{{ user.name }}</td>
                  <td>{{ user.email }}</td>
                  <td>{{ user.status }}</td>
                  <td>
                    <button 
                      class="demo-table-action"
                      (click)="showUserActions($event, tableRow, user)"
                    >
                      ⋮
                    </button>
                  </td>
                </tr>
              }
            </tbody>
          </table>
        </div>
      </section>

      <!-- Configuration Demo -->
      <section class="demo-section">
        <h3>Configuration Options</h3>
        <div class="demo-controls">
          <div class="demo-control-group">
            <label>
              <input 
                type="checkbox" 
                [(ngModel)]="demoConfig.backdrop"
                (change)="updateDemoConfig()"
              />
              Show Backdrop
            </label>
            
            <label>
              <input 
                type="checkbox" 
                [(ngModel)]="demoConfig.autoHide"
                (change)="updateDemoConfig()"
              />
              Auto Hide
            </label>
            
            <label>
              <input 
                type="checkbox" 
                [(ngModel)]="demoConfig.escapeClosable"
                (change)="updateDemoConfig()"
              />
              ESC to Close
            </label>
          </div>
          
          <button 
            class="demo-trigger-button"
            #configButton
            (click)="showConfigurableToolbar(configButton)"
          >
            Test Configuration
          </button>
        </div>
      </section>
    </div>

    <!-- Floating Toolbars -->
    <ui-floating-toolbar
      #floatingToolbar
      [actions]="currentActions"
      [size]="getConfigValue('size')"
      [variant]="getConfigValue('variant')"
      [position]="getConfigValue('position')"
      [visible]="getConfigValue('visible')"
      [autoHide]="getConfigValue('autoHide')"
      [hideDelay]="getConfigValue('hideDelay')"
      [backdrop]="getConfigValue('backdrop')"
      [escapeClosable]="getConfigValue('escapeClosable')"
      [label]="getConfigValue('label')"
      [showLabel]="getConfigValue('showLabel')"
      [showShortcuts]="getConfigValue('showShortcuts')"
      (actionClicked)="onActionClicked($event)"
      (visibleChange)="onToolbarVisibilityChange($event)"
      (hidden)="onToolbarHidden()"
    ></ui-floating-toolbar>

    <!-- Text Selection Toolbar -->
    <ui-floating-toolbar
      #textSelectionToolbar
      [actions]="textActions"
      size="sm"
      variant="contextual"
      position="top"
      [visible]="false"
      trigger="selection"
      [autoHide]="false"
      label="Text Formatting"
      [showShortcuts]="true"
      (actionClicked)="onTextActionClicked($event)"
    ></ui-floating-toolbar>
  `,
  styleUrl: './floating-toolbar-demo.component.scss'
})
export class FloatingToolbarDemoComponent implements AfterViewInit {
  @ViewChild('floatingToolbar') floatingToolbar!: FloatingToolbarComponent;
  @ViewChild('textSelectionToolbar') textSelectionToolbar!: FloatingToolbarComponent;

  // Demo Data
  sizes = ['sm', 'md', 'lg'] as const;
  variants = ['default', 'elevated', 'floating', 'compact', 'contextual'] as const;
  positions = ['top', 'bottom', 'left', 'right'] as const;
  
  sampleUsers = [
    { id: 1, name: 'Alice Johnson', email: 'alice@example.com', status: 'Active' },
    { id: 2, name: 'Bob Smith', email: 'bob@example.com', status: 'Pending' },
    { id: 3, name: 'Carol Davis', email: 'carol@example.com', status: 'Inactive' },
  ];

  // Demo State
  actionLog: string[] = [];
  selectedUserId: number | null = null;
  currentConfig: FloatingToolbarConfig = {
    visible: false,
    size: 'md',
    variant: 'default',
    position: 'top',
    autoHide: false,
    hideDelay: 3000,
    backdrop: false,
    escapeClosable: true,
    label: '',
    showLabel: false,
    showShortcuts: false
  };
  
  demoConfig = {
    backdrop: false,
    autoHide: false,
    escapeClosable: true
  };

  currentActions: ToolbarAction[] = [];

  // Action Sets
  basicActions: ToolbarAction[] = [
    {
      id: 'edit',
      label: 'Edit',
      icon: 'fas fa-edit',
      callback: (action, event) => this.logAction('Edit clicked')
    },
    {
      id: 'delete',
      label: 'Delete',
      icon: 'fas fa-trash',
      callback: (action, event) => this.logAction('Delete clicked')
    },
    {
      id: 'share',
      label: 'Share',
      icon: 'fas fa-share',
      callback: (action, event) => this.logAction('Share clicked')
    }
  ];

  textActions: ToolbarAction[] = [
    {
      id: 'cut',
      label: 'Cut',
      icon: 'fas fa-cut',
      shortcut: 'Ctrl+X',
      callback: (action, event) => this.executeTextAction('cut')
    },
    {
      id: 'copy',
      label: 'Copy',
      icon: 'fas fa-copy',
      shortcut: 'Ctrl+C',
      callback: (action, event) => this.executeTextAction('copy')
    },
    {
      id: 'paste',
      label: 'Paste',
      icon: 'fas fa-paste',
      shortcut: 'Ctrl+V',
      callback: (action, event) => this.executeTextAction('paste')
    },
    {
      id: 'divider1',
      label: '',
      divider: true
    },
    {
      id: 'bold',
      label: 'Bold',
      icon: 'fas fa-bold',
      shortcut: 'Ctrl+B',
      callback: (action, event) => this.executeTextAction('bold')
    },
    {
      id: 'italic',
      label: 'Italic',
      icon: 'fas fa-italic',
      shortcut: 'Ctrl+I',
      callback: (action, event) => this.executeTextAction('italic')
    },
    {
      id: 'underline',
      label: 'Underline',
      icon: 'fas fa-underline',
      shortcut: 'Ctrl+U',
      callback: (action, event) => this.executeTextAction('underline')
    }
  ];

  imageActions: ToolbarAction[] = [
    {
      id: 'resize',
      label: 'Resize',
      icon: 'fas fa-expand-arrows-alt',
      callback: (action, event) => this.logAction('Resize image')
    },
    {
      id: 'crop',
      label: 'Crop',
      icon: 'fas fa-crop',
      callback: (action, event) => this.logAction('Crop image')
    },
    {
      id: 'filters',
      label: 'Filters',
      icon: 'fas fa-filter',
      callback: (action, event) => this.logAction('Apply filters')
    },
    {
      id: 'divider2',
      label: '',
      divider: true
    },
    {
      id: 'download',
      label: 'Download',
      icon: 'fas fa-download',
      callback: (action, event) => this.logAction('Download image')
    }
  ];

  customActions: ToolbarAction[] = [
    {
      id: 'action1',
      label: 'Action 1',
      icon: 'fas fa-star',
      tooltip: 'This is action 1',
      callback: (action, event) => this.logAction('Custom Action 1 executed')
    },
    {
      id: 'action2',
      label: 'Action 2',
      icon: 'fas fa-heart',
      tooltip: 'This is action 2 with a longer tooltip',
      disabled: false,
      callback: (action, event) => this.logAction('Custom Action 2 executed')
    },
    {
      id: 'divider3',
      label: '',
      divider: true
    },
    {
      id: 'action3',
      label: 'Disabled Action',
      icon: 'fas fa-ban',
      disabled: true,
      tooltip: 'This action is disabled',
      callback: (action, event) => this.logAction('This should not execute')
    },
    {
      id: 'action4',
      label: 'Toggle Action',
      icon: 'fas fa-toggle-on',
      callback: (action, event) => this.toggleAction(action)
    }
  ];

  userActions: ToolbarAction[] = [
    {
      id: 'view',
      label: 'View Details',
      icon: 'fas fa-eye',
      callback: (action, event) => this.logAction('View user details')
    },
    {
      id: 'edit-user',
      label: 'Edit User',
      icon: 'fas fa-edit',
      callback: (action, event) => this.logAction('Edit user')
    },
    {
      id: 'delete-user',
      label: 'Delete User',
      icon: 'fas fa-trash',
      callback: (action, event) => this.logAction('Delete user')
    }
  ];

  ngAfterViewInit(): void {
    // Setup text selection toolbar
    this.setupTextSelectionToolbar();
  }

  showToolbar(id: string, triggerElement: HTMLElement, config: Partial<FloatingToolbarConfig>): void {
    console.log('Demo: showToolbar called', { id, config, basicActions: this.basicActions });
    this.currentConfig = {
      ...this.currentConfig,
      ...config,
      visible: true
    };
    this.currentActions = [...this.basicActions];
    console.log('Demo: config and actions set', { 
      currentConfig: this.currentConfig, 
      currentActions: this.currentActions 
    });
    this.floatingToolbar.setAnchorElement(triggerElement);
  }

  showAutoHideToolbar(triggerElement: HTMLElement): void {
    this.currentConfig = {
      ...this.currentConfig,
      visible: true,
      autoHide: true,
      hideDelay: 3000,
      label: 'Auto-hide in 3 seconds'
    };
    this.currentActions = [...this.basicActions];
    this.floatingToolbar.setAnchorElement(triggerElement);
  }

  showCustomActionsToolbar(triggerElement: HTMLElement): void {
    this.currentConfig = {
      ...this.currentConfig,
      visible: true,
      autoHide: false,
      showShortcuts: true,
      label: 'Custom Actions'
    };
    this.currentActions = [...this.customActions];
    this.floatingToolbar.setAnchorElement(triggerElement);
  }

  showContextualToolbar(event: MouseEvent, actions: ToolbarAction[], context: string): void {
    event.preventDefault();
    
    // Create temporary anchor at mouse position
    const tempAnchor = {
      getBoundingClientRect: () => ({
        top: event.clientY,
        left: event.clientX,
        right: event.clientX,
        bottom: event.clientY,
        width: 0,
        height: 0
      } as DOMRect)
    } as HTMLElement;

    this.currentConfig = {
      ...this.currentConfig,
      visible: true,
      variant: 'contextual',
      position: 'bottom',
      autoHide: true,
      hideDelay: 5000,
      label: `${context} actions`
    };
    this.currentActions = [...actions];
    this.floatingToolbar.setAnchorElement(tempAnchor);
  }

  showConfigurableToolbar(triggerElement: HTMLElement): void {
    this.currentConfig = {
      ...this.currentConfig,
      ...this.demoConfig,
      visible: true,
      label: 'Configured Toolbar'
    };
    this.currentActions = [...this.basicActions];
    this.floatingToolbar.setAnchorElement(triggerElement);
  }

  updateDemoConfig(): void {
    // Update the demo configuration
    Object.assign(this.currentConfig, this.demoConfig);
  }

  handleTextSelection(element: HTMLElement): void {
    const selection = window.getSelection();
    if (selection && selection.toString().trim()) {
      const range = selection.getRangeAt(0);
      const rect = range.getBoundingClientRect();
      
      if (rect.width > 0 && rect.height > 0) {
        // Create anchor at selection
        const selectionAnchor = {
          getBoundingClientRect: () => rect
        } as HTMLElement;

        this.textSelectionToolbar.setAnchorElement(selectionAnchor);
        this.textSelectionToolbar.show();
      }
    } else {
      this.textSelectionToolbar.hide();
    }
  }

  selectUser(userId: number, rowElement: HTMLElement): void {
    this.selectedUserId = userId;
  }

  showUserActions(event: Event, rowElement: HTMLElement, user: any): void {
    event.stopPropagation();
    
    this.currentConfig = {
      ...this.currentConfig,
      visible: true,
      variant: 'elevated',
      position: 'left',
      label: `Actions for ${user.name}`
    };
    this.currentActions = [...this.userActions];
    this.floatingToolbar.setAnchorElement(rowElement);
  }

  onActionClicked(event: { action: ToolbarAction; event: Event }): void {
    this.logAction(`Action clicked: ${event.action.label}`);
  }

  onTextActionClicked(event: { action: ToolbarAction; event: Event }): void {
    this.logAction(`Text action: ${event.action.label}`);
  }

  onToolbarVisibilityChange(visible: boolean): void {
    this.currentConfig.visible = visible;
  }

  onToolbarHidden(): void {
    this.logAction('Toolbar hidden');
  }

  executeTextAction(command: string): void {
    try {
      document.execCommand(command, false);
      this.logAction(`Text formatting: ${command}`);
    } catch (error) {
      this.logAction(`Text formatting failed: ${command}`);
    }
  }

  toggleAction(action: ToolbarAction): void {
    const isToggled = action.icon === 'fas fa-toggle-on';
    action.icon = isToggled ? 'fas fa-toggle-off' : 'fas fa-toggle-on';
    this.logAction(`Toggle action: ${isToggled ? 'OFF' : 'ON'}`);
  }

  private setupTextSelectionToolbar(): void {
    document.addEventListener('selectionchange', () => {
      const selection = window.getSelection();
      if (!selection || !selection.toString().trim()) {
        this.textSelectionToolbar.hide();
      }
    });
  }

  getConfigValue<K extends keyof FloatingToolbarConfig>(key: K): NonNullable<FloatingToolbarConfig[K]> {
    const defaultValues: Required<FloatingToolbarConfig> = {
      size: 'md',
      variant: 'default',
      position: 'top',
      autoPosition: true,
      visible: false,
      actions: [],
      context: undefined as any,
      trigger: 'manual',
      autoHide: false,
      hideDelay: 3000,
      showAnimation: 'slide-fade',
      backdrop: false,
      backdropClosable: true,
      escapeClosable: true,
      offset: 12,
      label: '',
      showLabel: false,
      showShortcuts: false
    };

    const value = this.currentConfig[key];
    return (value !== undefined ? value : defaultValues[key]) as NonNullable<FloatingToolbarConfig[K]>;
  }

  private logAction(message: string): void {
    const timestamp = new Date().toLocaleTimeString();
    this.actionLog.unshift(`[${timestamp}] ${message}`);
    
    // Keep only the last 10 entries
    if (this.actionLog.length > 10) {
      this.actionLog = this.actionLog.slice(0, 10);
    }
  }
}