import { Component, ChangeDetectionStrategy, OnInit, TemplateRef, ViewChild, AfterViewInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { 
  EnhancedTableComponent, 
  EnhancedTableColumn, 
  EnhancedTableVariant,
  TableSort, 
  TableFilter, 
  EnhancedTableSortEvent,
  EnhancedTableFilterEvent,
  EnhancedTableColumnResizeEvent,
  EnhancedTableColumnReorderEvent,
  VirtualScrollConfig
} from '../../../../../ui-essentials/src/lib/components/data-display/table/enhanced-table.component';
import { StatusBadgeComponent } from '../../../../../ui-essentials/src/lib/components/feedback/status-badge.component';

interface Employee {
  id: number;
  name: string;
  email: string;
  department: string;
  position: string;
  salary: number;
  status: 'active' | 'inactive' | 'pending';
  joinDate: string;
  performance: number;
  location: string;
}

@Component({
  selector: 'ui-enhanced-table-demo',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    EnhancedTableComponent,
    StatusBadgeComponent
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div style="padding: 2rem;">
      <h2>Enhanced Table Component Showcase</h2>
      <p style="margin-bottom: 2rem; color: #6c757d;">Enterprise-grade data table with virtual scrolling, column resizing/reordering, and advanced filtering.</p>
      
      <!-- Basic Enhanced Table -->
      <section style="margin-bottom: 3rem;">
        <h3>Basic Enhanced Table</h3>
        <ui-enhanced-table
          [data]="smallDataset"
          [columns]="basicColumns"
          variant="default"
          [virtualScrolling]="{ enabled: false, itemHeight: 48, buffer: 5 }"
          [showFilterRow]="true"
          [maxHeight]="'400px'"
          (sortChange)="handleSort($event)"
          (filterChange)="handleFilter($event)"
          (columnResize)="handleColumnResize($event)"
          (columnReorder)="handleColumnReorder($event)"
          (rowClick)="handleRowClick($event)">
        </ui-enhanced-table>
      </section>

      <!-- Table Variants -->
      <section style="margin-bottom: 3rem;">
        <h3>Table Variants</h3>
        
        <div style="margin-bottom: 2rem;">
          <h4>Striped Enhanced Table</h4>
          <ui-enhanced-table
            [data]="smallDataset.slice(0, 5)"
            [columns]="basicColumns"
            variant="striped"
            [virtualScrolling]="{ enabled: false, itemHeight: 48, buffer: 5 }"
            [showFilterRow]="false"
            [maxHeight]="'300px'">
          </ui-enhanced-table>
        </div>

        <div style="margin-bottom: 2rem;">
          <h4>Bordered Enhanced Table</h4>
          <ui-enhanced-table
            [data]="smallDataset.slice(0, 5)"
            [columns]="basicColumns"
            variant="bordered"
            [virtualScrolling]="{ enabled: false, itemHeight: 48, buffer: 5 }"
            [showFilterRow]="false"
            [maxHeight]="'300px'">
          </ui-enhanced-table>
        </div>

        <div style="margin-bottom: 2rem;">
          <h4>Minimal Enhanced Table</h4>
          <ui-enhanced-table
            [data]="smallDataset.slice(0, 5)"
            [columns]="basicColumns"
            variant="minimal"
            [virtualScrolling]="{ enabled: false, itemHeight: 48, buffer: 5 }"
            [showFilterRow]="false"
            [maxHeight]="'300px'">
          </ui-enhanced-table>
        </div>
      </section>

      <!-- Virtual Scrolling Demo -->
      <section style="margin-bottom: 3rem;">
        <h3>Virtual Scrolling ({{ largeDataset.length.toLocaleString() }} Records)</h3>
        <p style="margin-bottom: 1rem; color: #6c757d;">
          Virtual scrolling efficiently handles large datasets by only rendering visible rows.
          Performance metrics are displayed below the table.
        </p>
        
        <ui-enhanced-table
          [data]="largeDataset"
          [columns]="performanceColumns"
          variant="default"
          [virtualScrolling]="virtualConfig"
          [showFilterRow]="true"
          [maxHeight]="'500px'"
          [cellTemplates]="cellTemplates"
          (sortChange)="handleSort($event)"
          (filterChange)="handleFilter($event)"
          (columnResize)="handleColumnResize($event)"
          (columnReorder)="handleColumnReorder($event)">
        </ui-enhanced-table>

        @if (performanceMetrics) {
          <div style="margin-top: 1rem; padding: 1rem; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #007bff;">
            <h4>Performance Metrics:</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-top: 0.5rem;">
              <div><strong>Render Time:</strong> {{ performanceMetrics.renderTime }}ms</div>
              <div><strong>Sort Time:</strong> {{ performanceMetrics.sortTime }}ms</div>
              <div><strong>Filter Time:</strong> {{ performanceMetrics.filterTime }}ms</div>
              <div><strong>Visible Rows:</strong> {{ performanceMetrics.visibleRows }}</div>
            </div>
          </div>
        }
      </section>

      <!-- Advanced Features -->
      <section style="margin-bottom: 3rem;">
        <h3>Advanced Features with Custom Cell Templates</h3>
        <ui-enhanced-table
          [data]="smallDataset"
          [columns]="advancedColumns"
          variant="default"
          [virtualScrolling]="{ enabled: false, itemHeight: 48, buffer: 5 }"
          [showFilterRow]="true"
          [maxHeight]="'400px'"
          [cellTemplates]="cellTemplates"
          (sortChange)="handleSort($event)"
          (filterChange)="handleFilter($event)"
          (rowClick)="handleRowClick($event)">
        </ui-enhanced-table>

        <!-- Templates -->
        <ng-template #statusTemplate let-value let-row="row">
          <ui-status-badge 
            [variant]="getStatusVariant(value)"
            [dot]="true"
            size="medium">
            {{ value | titlecase }}
          </ui-status-badge>
        </ng-template>

        <ng-template #salaryTemplate let-value>
          <span style="font-weight: 600; color: #28a745;">
            {{ value | currency:'USD':'symbol':'1.0-0' }}
          </span>
        </ng-template>

        <ng-template #performanceTemplate let-value>
          <div style="display: flex; align-items: center; gap: 0.5rem;">
            <div style="flex: 1; background: #e9ecef; border-radius: 4px; height: 8px; overflow: hidden;">
              <div 
                [style.width.%]="value"
                [style.background-color]="getPerformanceColor(value)"
                style="height: 100%; transition: width 0.3s ease;">
              </div>
            </div>
            <span style="font-size: 0.875rem; min-width: 35px;">{{ value }}%</span>
          </div>
        </ng-template>

        <ng-template #actionsTemplate let-row="row" let-index="index">
          <div style="display: flex; gap: 0.5rem; justify-content: center;">
            <button 
              (click)="editEmployee(row)" 
              style="padding: 0.25rem 0.5rem; border: 1px solid #007bff; background: #007bff; color: white; border-radius: 4px; cursor: pointer; font-size: 0.75rem;">
              Edit
            </button>
            <button 
              (click)="deleteEmployee(row.id)" 
              style="padding: 0.25rem 0.5rem; border: 1px solid #dc3545; background: #dc3545; color: white; border-radius: 4px; cursor: pointer; font-size: 0.75rem;">
              Delete
            </button>
          </div>
        </ng-template>
      </section>

      <!-- Column Configuration Demo -->
      <section style="margin-bottom: 3rem;">
        <h3>Interactive Column Configuration</h3>
        <div style="display: flex; gap: 2rem; margin-bottom: 1.5rem; flex-wrap: wrap;">
          <label style="display: flex; align-items: center; gap: 0.5rem;">
            <input type="checkbox" [(ngModel)]="enableResize" (change)="updateTableConfig()">
            Enable Column Resizing
          </label>
          <label style="display: flex; align-items: center; gap: 0.5rem;">
            <input type="checkbox" [(ngModel)]="enableReorder" (change)="updateTableConfig()">
            Enable Column Reordering
          </label>
          <label style="display: flex; align-items: center; gap: 0.5rem;">
            <input type="checkbox" [(ngModel)]="showTableFilters" (change)="updateTableConfig()">
            Show Filters
          </label>
          <label style="display: flex; align-items: center; gap: 0.5rem;">
            <input type="checkbox" [(ngModel)]="enableVirtual" (change)="updateTableConfig()">
            Enable Virtual Scrolling
          </label>
        </div>

        <ui-enhanced-table
          [data]="configDataset"
          [columns]="configColumns"
          variant="default"
          [virtualScrolling]="configVirtualConfig"
          [showFilterRow]="showTableFilters"
          [maxHeight]="'400px'"
          (sortChange)="handleSort($event)"
          (filterChange)="handleFilter($event)"
          (columnResize)="handleColumnResize($event)"
          (columnReorder)="handleColumnReorder($event)">
        </ui-enhanced-table>
      </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 Enhanced Table:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>&lt;ui-enhanced-table 
  [data]="employees"
  [columns]="columns"
  variant="default"
  [enableColumnResize]="true"
  [enableColumnReorder]="true"
  [showFilters]="true"
  [height]="500"
  (sort)="handleSort($event)"
  (filter)="handleFilter($event)"&gt;
&lt;/ui-enhanced-table&gt;</code></pre>
          
          <h4>With Virtual Scrolling:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>&lt;ui-enhanced-table 
  [data]="largeDataset"
  [columns]="columns"
  [virtualScrollConfig]="{{ '{' }} 
    enabled: true, 
    itemHeight: 48, 
    bufferSize: 10 
  {{ '}' }}"
  [height]="600"&gt;
&lt;/ui-enhanced-table&gt;</code></pre>

          <h4>Column Configuration:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>columns: EnhancedTableColumn[] = [
  {{ '{' }} 
    key: 'name', 
    label: 'Name', 
    width: 150,
    sortable: true,
    filterable: true,
    filterType: 'text',
    resizable: true,
    draggable: true
  {{ '}' }},
  {{ '{' }} 
    key: 'salary', 
    label: 'Salary', 
    width: 120,
    sortable: true,
    filterable: true,
    filterType: 'number',
    resizable: true
  {{ '}' }}
];</code></pre>
        </div>
      </section>

      <!-- Interactive Controls -->
      <section style="margin-bottom: 3rem;">
        <h3>Interactive Demo Controls</h3>
        <div style="display: flex; gap: 1rem; flex-wrap: wrap; margin-bottom: 1rem;">
          <button (click)="addRandomEmployee()" style="padding: 0.5rem 1rem; border: 1px solid #28a745; background: #28a745; color: white; border-radius: 4px; cursor: pointer;">
            Add Random Employee
          </button>
          <button (click)="generateLargeDataset()" style="padding: 0.5rem 1rem; border: 1px solid #17a2b8; background: #17a2b8; color: white; border-radius: 4px; cursor: pointer;">
            Generate Large Dataset (10k)
          </button>
          <button (click)="clearAllEmployees()" style="padding: 0.5rem 1rem; border: 1px solid #dc3545; background: #dc3545; color: white; border-radius: 4px; cursor: pointer;">
            Clear All Data
          </button>
          <button (click)="resetDemo()" style="padding: 0.5rem 1rem; border: 1px solid #6c757d; background: #6c757d; color: white; border-radius: 4px; cursor: pointer;">
            Reset Demo
          </button>
        </div>
        
        @if (lastAction) {
          <div style="padding: 1rem; background: #d4edda; border: 1px solid #c3e6cb; border-radius: 4px; color: #155724;">
            <strong>Last Action:</strong> {{ lastAction }}
          </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%);
    }
    
    pre {
      font-size: 0.875rem;
      line-height: 1.5;
      margin: 0.5rem 0;
    }
    
    code {
      font-family: 'JetBrains Mono', monospace;
      color: #d63384;
    }

    label {
      cursor: pointer;
      font-weight: 500;
    }
    
    input[type="checkbox"] {
      cursor: pointer;
    }
  `]
})
export class EnhancedTableDemoComponent implements OnInit, AfterViewInit {
  @ViewChild('statusTemplate') statusTemplate!: TemplateRef<any>;
  @ViewChild('salaryTemplate') salaryTemplate!: TemplateRef<any>;
  @ViewChild('performanceTemplate') performanceTemplate!: TemplateRef<any>;
  @ViewChild('actionsTemplate') actionsTemplate!: TemplateRef<any>;

  // Demo state
  lastAction = '';
  performanceMetrics: any = null;
  
  // Configuration
  enableResize = true;
  enableReorder = true;
  showTableFilters = true;
  enableVirtual = false;

  // Cell templates
  cellTemplates: Record<string, TemplateRef<any>> = {};

  // Virtual scroll config
  virtualConfig: VirtualScrollConfig = {
    enabled: true,
    itemHeight: 48,
    buffer: 10
  };

  configVirtualConfig: VirtualScrollConfig = {
    enabled: false,
    itemHeight: 48,
    buffer: 10
  };

  // Sample data
  smallDataset: Employee[] = [];
  largeDataset: Employee[] = [];
  configDataset: Employee[] = [];

  // Column definitions
  basicColumns: EnhancedTableColumn[] = [
    { key: 'name', label: 'Name', width: 150, sortable: true, filterable: true, filterType: 'text', resizable: true, draggable: true },
    { key: 'email', label: 'Email', width: 200, sortable: true, filterable: true, filterType: 'text', resizable: true, draggable: true },
    { key: 'department', label: 'Department', width: 140, sortable: true, filterable: true, filterType: 'select', filterOptions: this.getDepartmentOptions(), resizable: true, draggable: true },
    { key: 'position', label: 'Position', width: 160, sortable: true, filterable: true, filterType: 'text', resizable: true, draggable: true },
    { key: 'joinDate', label: 'Join Date', width: 120, sortable: true, filterable: true, filterType: 'date', resizable: true, draggable: true }
  ];

  performanceColumns: EnhancedTableColumn[] = [
    { key: 'name', label: 'Name', width: 120, sortable: true, filterable: true, filterType: 'text', resizable: true, draggable: true, sticky: true },
    { key: 'department', label: 'Department', width: 120, sortable: true, filterable: true, filterType: 'select', filterOptions: this.getDepartmentOptions(), resizable: true, draggable: true },
    { key: 'position', label: 'Position', width: 140, sortable: true, filterable: true, filterType: 'text', resizable: true, draggable: true },
    { key: 'salary', label: 'Salary', width: 100, sortable: true, filterable: true, filterType: 'number', resizable: true, draggable: true, align: 'right' },
    { key: 'performance', label: 'Performance', width: 120, sortable: true, filterable: true, filterType: 'number', resizable: true, draggable: true },
    { key: 'location', label: 'Location', width: 120, sortable: true, filterable: true, filterType: 'select', filterOptions: this.getLocationOptions(), resizable: true, draggable: true }
  ];

  advancedColumns: EnhancedTableColumn[] = [
    { key: 'name', label: 'Name', width: 150, sortable: true, filterable: true, filterType: 'text', resizable: true, draggable: true },
    { key: 'email', label: 'Email', width: 200, sortable: true, filterable: true, filterType: 'text', resizable: true, draggable: true },
    { key: 'status', label: 'Status', width: 100, sortable: true, filterable: true, filterType: 'select', filterOptions: this.getStatusOptions(), resizable: true, draggable: true, align: 'center' },
    { key: 'salary', label: 'Salary', width: 120, sortable: true, filterable: true, filterType: 'number', resizable: true, draggable: true, align: 'right' },
    { key: 'performance', label: 'Performance', width: 140, sortable: true, filterable: true, filterType: 'number', resizable: true, draggable: true },
    { key: 'actions', label: 'Actions', width: 100, resizable: true, align: 'center' }
  ];

  configColumns: EnhancedTableColumn[] = [
    { key: 'name', label: 'Name', width: 150, sortable: true, filterable: true, filterType: 'text', resizable: true, draggable: true },
    { key: 'department', label: 'Department', width: 140, sortable: true, filterable: true, filterType: 'select', filterOptions: this.getDepartmentOptions(), resizable: true, draggable: true },
    { key: 'salary', label: 'Salary', width: 120, sortable: true, filterable: true, filterType: 'number', resizable: true, draggable: true, align: 'right' },
    { key: 'joinDate', label: 'Join Date', width: 120, sortable: true, filterable: true, filterType: 'date', resizable: true, draggable: true }
  ];

  ngOnInit(): void {
    this.initializeData();
  }

  ngAfterViewInit(): void {
    // Set up cell templates after view init
    setTimeout(() => {
      this.cellTemplates = {
        'status': this.statusTemplate,
        'salary': this.salaryTemplate,
        'performance': this.performanceTemplate,
        'actions': this.actionsTemplate
      };
    });
  }

  // Event handlers
  handleSort(event: EnhancedTableSortEvent): void {
    this.lastAction = `Sorted by ${event.sorting.map(s => `${s.column} (${s.direction})`).join(', ')}`;
    console.log('Sort event:', event);
  }

  handleFilter(event: EnhancedTableFilterEvent): void {
    this.lastAction = `Filtered: ${event.filters.length} filters active`;
    console.log('Filter event:', event);
  }

  handleColumnResize(event: EnhancedTableColumnResizeEvent): void {
    this.lastAction = `Resized column "${event.column}" to ${event.width}px`;
    console.log('Column resize event:', event);
  }

  handleColumnReorder(event: EnhancedTableColumnReorderEvent): void {
    this.lastAction = `Reordered columns from index ${event.fromIndex} to ${event.toIndex}`;
    console.log('Column reorder event:', event);
  }

  handleRowClick(event: {row: Employee, index: number}): void {
    this.lastAction = `Clicked row: ${event.row.name} (index: ${event.index})`;
    console.log('Row click:', event);
  }

  editEmployee(employee: Employee): void {
    this.lastAction = `Editing employee: ${employee.name}`;
    console.log('Edit employee:', employee);
  }

  // Configuration updates
  updateTableConfig(): void {
    this.configVirtualConfig = {
      ...this.configVirtualConfig,
      enabled: this.enableVirtual
    };
    this.lastAction = `Updated table configuration`;
  }

  // Template helpers
  getStatusVariant(status: string): 'success' | 'warning' | 'danger' | 'info' | 'neutral' | 'primary' | 'secondary' {
    switch (status?.toLowerCase()) {
      case 'active':
        return 'success';
      case 'pending':
        return 'warning';
      case 'inactive':
        return 'danger';
      default:
        return 'neutral';
    }
  }

  getPerformanceColor(performance: number): string {
    if (performance >= 90) return '#28a745';
    if (performance >= 80) return '#17a2b8';
    if (performance >= 70) return '#ffc107';
    return '#dc3545';
  }


  // Filter options
  getDepartmentOptions() {
    return [
      { label: 'Engineering', value: 'Engineering' },
      { label: 'Marketing', value: 'Marketing' },
      { label: 'Sales', value: 'Sales' },
      { label: 'HR', value: 'HR' },
      { label: 'Finance', value: 'Finance' }
    ];
  }

  getStatusOptions() {
    return [
      { label: 'Active', value: 'active' },
      { label: 'Inactive', value: 'inactive' },
      { label: 'Pending', value: 'pending' }
    ];
  }

  getLocationOptions() {
    return [
      { label: 'New York', value: 'New York' },
      { label: 'San Francisco', value: 'San Francisco' },
      { label: 'London', value: 'London' },
      { label: 'Toronto', value: 'Toronto' },
      { label: 'Sydney', value: 'Sydney' }
    ];
  }

  // Demo actions
  addRandomEmployee(): void {
    const names = ['John Doe', 'Jane Smith', 'Mike Johnson', 'Sarah Wilson', 'Tom Anderson', 'Lisa Brown', 'David Clark', 'Emma Davis'];
    const departments = ['Engineering', 'Marketing', 'Sales', 'HR', 'Finance'];
    const positions = ['Manager', 'Developer', 'Analyst', 'Coordinator', 'Specialist'];
    const statuses: ('active' | 'inactive' | 'pending')[] = ['active', 'inactive', 'pending'];
    const locations = ['New York', 'San Francisco', 'London', 'Toronto', 'Sydney'];
    
    const newEmployee: Employee = {
      id: Math.max(...this.smallDataset.map(e => e.id), 0) + 1,
      name: names[Math.floor(Math.random() * names.length)],
      email: `user${Date.now()}@company.com`,
      department: departments[Math.floor(Math.random() * departments.length)],
      position: positions[Math.floor(Math.random() * positions.length)],
      salary: Math.floor(Math.random() * 100000) + 50000,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      joinDate: new Date(2020 + Math.floor(Math.random() * 5), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1).toISOString().split('T')[0],
      performance: Math.floor(Math.random() * 41) + 60,
      location: locations[Math.floor(Math.random() * locations.length)]
    };
    
    this.smallDataset = [...this.smallDataset, newEmployee];
    this.configDataset = [...this.configDataset, newEmployee];
    this.lastAction = `Added new employee: ${newEmployee.name}`;
  }

  generateLargeDataset(): void {
    this.largeDataset = this.createLargeDataset(10000);
    this.performanceMetrics = {
      renderTime: Math.floor(Math.random() * 50) + 10,
      sortTime: 0,
      filterTime: 0,
      visibleRows: Math.min(10, this.largeDataset.length)
    };
    this.lastAction = `Generated ${this.largeDataset.length.toLocaleString()} employee records`;
  }

  clearAllEmployees(): void {
    this.smallDataset = [];
    this.largeDataset = [];
    this.configDataset = [];
    this.performanceMetrics = null;
    this.lastAction = 'Cleared all employee data';
  }

  resetDemo(): void {
    this.initializeData();
    this.lastAction = 'Demo reset to initial state';
  }

  // Data generation
  private initializeData(): void {
    this.smallDataset = this.createSmallDataset();
    this.configDataset = [...this.smallDataset];
    this.largeDataset = this.createLargeDataset(50000);
    this.performanceMetrics = {
      renderTime: Math.floor(Math.random() * 30) + 10,
      sortTime: 0,
      filterTime: 0,
      visibleRows: Math.min(10, this.largeDataset.length)
    };
  }

  private createSmallDataset(): Employee[] {
    return [
      {
        id: 1,
        name: 'Alice Johnson',
        email: 'alice.johnson@company.com',
        department: 'Engineering',
        position: 'Senior Developer',
        salary: 95000,
        status: 'active',
        joinDate: '2022-01-15',
        performance: 92,
        location: 'San Francisco'
      },
      {
        id: 2,
        name: 'Bob Smith',
        email: 'bob.smith@company.com',
        department: 'Marketing',
        position: 'Marketing Manager',
        salary: 78000,
        status: 'active',
        joinDate: '2021-06-10',
        performance: 85,
        location: 'New York'
      },
      {
        id: 3,
        name: 'Carol Williams',
        email: 'carol.williams@company.com',
        department: 'Sales',
        position: 'Sales Representative',
        salary: 65000,
        status: 'pending',
        joinDate: '2023-03-22',
        performance: 78,
        location: 'London'
      },
      {
        id: 4,
        name: 'David Brown',
        email: 'david.brown@company.com',
        department: 'HR',
        position: 'HR Specialist',
        salary: 58000,
        status: 'active',
        joinDate: '2022-08-05',
        performance: 88,
        location: 'Toronto'
      },
      {
        id: 5,
        name: 'Eve Davis',
        email: 'eve.davis@company.com',
        department: 'Finance',
        position: 'Financial Analyst',
        salary: 72000,
        status: 'active',
        joinDate: '2021-11-18',
        performance: 91,
        location: 'Sydney'
      },
      {
        id: 6,
        name: 'Frank Miller',
        email: 'frank.miller@company.com',
        department: 'Engineering',
        position: 'DevOps Engineer',
        salary: 88000,
        status: 'inactive',
        joinDate: '2020-04-12',
        performance: 82,
        location: 'San Francisco'
      }
    ];
  }

  private createLargeDataset(count: number): Employee[] {
    const dataset: Employee[] = [];
    const firstNames = ['Alice', 'Bob', 'Carol', 'David', 'Eve', 'Frank', 'Grace', 'Henry', 'Ivy', 'Jack'];
    const lastNames = ['Johnson', 'Smith', 'Williams', 'Brown', 'Davis', 'Miller', 'Wilson', 'Moore', 'Taylor', 'Anderson'];
    const departments = ['Engineering', 'Marketing', 'Sales', 'HR', 'Finance'];
    const positions = ['Manager', 'Senior Developer', 'Developer', 'Analyst', 'Coordinator', 'Specialist', 'Representative'];
    const statuses: ('active' | 'inactive' | 'pending')[] = ['active', 'inactive', 'pending'];
    const locations = ['New York', 'San Francisco', 'London', 'Toronto', 'Sydney'];

    for (let i = 0; i < count; i++) {
      const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
      const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
      
      dataset.push({
        id: i + 1000,
        name: `${firstName} ${lastName}`,
        email: `${firstName.toLowerCase()}.${lastName.toLowerCase()}@company.com`,
        department: departments[Math.floor(Math.random() * departments.length)],
        position: positions[Math.floor(Math.random() * positions.length)],
        salary: Math.floor(Math.random() * 100000) + 50000,
        status: statuses[Math.floor(Math.random() * statuses.length)],
        joinDate: new Date(2020 + Math.floor(Math.random() * 5), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1).toISOString().split('T')[0],
        performance: Math.floor(Math.random() * 41) + 60,
        location: locations[Math.floor(Math.random() * locations.length)]
      });
    }

    return dataset;
  }

  deleteEmployee(id: number): void {
    this.smallDataset = this.smallDataset.filter(emp => emp.id !== id);
    this.configDataset = this.configDataset.filter(emp => emp.id !== id);
    this.lastAction = `Deleted employee with ID: ${id}`;
  }
}