import { Component, ChangeDetectionStrategy, TemplateRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TableComponent } from '../../../../../ui-essentials/src/lib/components/data-display/table/table.component';
import { TableAction, TableActionsComponent } from '../../../../../ui-essentials/src/lib/components/data-display/table/table-actions.component';
import type { TableColumn } from '../../../../../ui-essentials/src/lib/components/data-display/table/table.component';
import type { TableSortEvent } from '../../../../../ui-essentials/src/lib/components/data-display/table/table.component';
import { StatusBadgeComponent } from '../../../../../ui-essentials/src/lib/components/feedback/status-badge.component';
interface User {
  id: number;
  name: string;
  email: string;
  status: 'active' | 'inactive' | 'pending';
  role: string;
  lastLogin: string;
  joinDate: string;
}

@Component({
  selector: 'ui-table-demo',
  standalone: true,
  imports: [
    CommonModule,
    TableComponent,
    StatusBadgeComponent,
    TableActionsComponent
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div style="padding: 2rem;">
      <h2>Table Component Showcase</h2>

      <!-- Basic Table -->
      <section style="margin-bottom: 3rem;">
        <h3>Basic Table</h3>
        <ui-table 
          [data]="userData"
          [columns]="basicColumns"
          variant="default"
          size="default"
          [hoverable]="true"
          (sort)="handleSort($event)"
          (rowClick)="handleRowClick($event)">
        </ui-table>
      </section>

      <!-- Table Variants -->
      <section style="margin-bottom: 3rem;">
        <h3>Table Variants</h3>
        
        <div style="margin-bottom: 2rem;">
          <h4>Striped Table</h4>
          <ui-table 
            [data]="userData.slice(0, 5)"
            [columns]="basicColumns"
            variant="striped"
            size="default"
            [hoverable]="true">
          </ui-table>
        </div>

        <div style="margin-bottom: 2rem;">
          <h4>Bordered Table</h4>
          <ui-table 
            [data]="userData.slice(0, 5)"
            [columns]="basicColumns"
            variant="bordered"
            size="default"
            [hoverable]="true">
          </ui-table>
        </div>

        <div style="margin-bottom: 2rem;">
          <h4>Minimal Table</h4>
          <ui-table 
            [data]="userData.slice(0, 5)"
            [columns]="basicColumns"
            variant="minimal"
            size="default"
            [hoverable]="true">
          </ui-table>
        </div>
      </section>

      <!-- Size Variants -->
      <section style="margin-bottom: 3rem;">
        <h3>Size Variants</h3>
        
        <div style="margin-bottom: 2rem;">
          <h4>Compact Size</h4>
          <ui-table 
            [data]="userData.slice(0, 4)"
            [columns]="basicColumns"
            variant="default"
            size="compact"
            [hoverable]="true">
          </ui-table>
        </div>

        <div style="margin-bottom: 2rem;">
          <h4>Comfortable Size</h4>
          <ui-table 
            [data]="userData.slice(0, 4)"
            [columns]="basicColumns"
            variant="default"
            size="comfortable"
            [hoverable]="true">
          </ui-table>
        </div>
      </section>

      <!-- Advanced Table with Status and Actions -->
      <section style="margin-bottom: 3rem;">
        <h3>Advanced Table with Status Badges and Actions</h3>
        <ui-table 
          [data]="userData"
          [columns]="advancedColumns"
          variant="default"
          size="default"
          [hoverable]="true"
          [cellTemplates]="cellTemplates"
          [sortColumn]="currentSortColumn"
          [sortDirection]="currentSortDirection"
          (sort)="handleAdvancedSort($event)"
          (rowClick)="handleAdvancedRowClick($event)">
        </ui-table>

        <!-- Cell 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 #actionsTemplate let-row="row" let-index="index">
          <ui-table-actions 
            [actions]="getActionsForUser(row)"
            [data]="row"
            [index]="index"
            size="medium"
            [showLabels]="false"
            (actionClick)="handleAction($event)">
          </ui-table-actions>
        </ng-template>
      </section>

      <!-- Sticky Header Table -->
      <section style="margin-bottom: 3rem;">
        <h3>Sticky Header Table</h3>
        <div style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px;">
          <ui-table 
            [data]="largeDataset"
            [columns]="basicColumns"
            variant="default"
            size="compact"
            [stickyHeader]="true"
            [hoverable]="true">
          </ui-table>
        </div>
      </section>

      <!-- Loading State -->
      <section style="margin-bottom: 3rem;">
        <h3>Loading State</h3>
        <ui-table 
          [data]="[]"
          [columns]="basicColumns"
          variant="default"
          size="default"
          [loading]="isLoading"
          loadingMessage="Loading user data...">
        </ui-table>
        <button 
          (click)="toggleLoading()"
          style="margin-top: 1rem; padding: 0.5rem 1rem; border: 1px solid #007bff; background: #007bff; color: white; border-radius: 4px; cursor: pointer;">
          {{ isLoading ? 'Stop Loading' : 'Start Loading' }}
        </button>
      </section>

      <!-- Empty State -->
      <section style="margin-bottom: 3rem;">
        <h3>Empty State</h3>
        <ui-table 
          [data]="[]"
          [columns]="basicColumns"
          variant="default"
          size="default"
          [showEmptyState]="true"
          emptyMessage="No users found. Try adding some users first.">
        </ui-table>
      </section>

      <!-- Selectable Table -->
      <section style="margin-bottom: 3rem;">
        <h3>Selectable Rows</h3>
        <ui-table 
          [data]="userData.slice(0, 6)"
          [columns]="basicColumns"
          variant="default"
          size="default"
          [selectable]="true"
          [hoverable]="true"
          (selectionChange)="handleSelectionChange($event)">
        </ui-table>
        @if (selectedUsers.length > 0) {
          <div style="margin-top: 1rem; padding: 1rem; background: #e3f2fd; border-radius: 4px;">
            <strong>Selected users:</strong> {{ selectedUsers.length }}
            <div style="margin-top: 0.5rem;">
              @for (user of selectedUsers; track user.id) {
                <span style="display: inline-block; margin: 0.25rem; padding: 0.25rem 0.5rem; background: #fff; border-radius: 4px;">
                  {{ user.name }}
                </span>
              }
            </div>
          </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 Table:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>&lt;ui-table 
  [data]="tableData"
  [columns]="columns"
  variant="striped"
  size="default"
  [hoverable]="true"
  (sort)="handleSort($event)"
  (rowClick)="handleRowClick($event)"&gt;
&lt;/ui-table&gt;</code></pre>
          
          <h4>With Custom Cell Templates:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>&lt;ui-table 
  [data]="userData"
  [columns]="columns"
  [cellTemplates]="cellTemplates"&gt;
&lt;/ui-table&gt;

&lt;ng-template #statusTemplate let-value&gt;
  &lt;ui-status-badge [variant]="getVariant(value)"&gt;
    {{ "{{ value }}" }}
  &lt;/ui-status-badge&gt;
&lt;/ng-template&gt;</code></pre>

          <h4>Column Configuration:</h4>
          <pre style="background: #fff; padding: 1rem; border-radius: 4px; overflow-x: auto;"><code>columns: TableColumn[] = [
  {{ '{' }} key: 'name', label: 'Name', sortable: true {{ '}' }},
  {{ '{' }} key: 'email', label: 'Email', sortable: true {{ '}' }},
  {{ '{' }} key: 'status', label: 'Status', align: 'center' {{ '}' }},
  {{ '{' }} key: 'actions', label: 'Actions', align: 'right' {{ '}' }}
];</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)="addRandomUser()" style="padding: 0.5rem 1rem; border: 1px solid #28a745; background: #28a745; color: white; border-radius: 4px; cursor: pointer;">
            Add Random User
          </button>
          <button (click)="clearAllUsers()" style="padding: 0.5rem 1rem; border: 1px solid #dc3545; background: #dc3545; color: white; border-radius: 4px; cursor: pointer;">
            Clear All Users
          </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;
    }
  `]
})
export class TableDemoComponent {
  @ViewChild('statusTemplate') statusTemplate!: TemplateRef<any>;
  @ViewChild('actionsTemplate') actionsTemplate!: TemplateRef<any>;

  isLoading = false;
  selectedUsers: User[] = [];
  lastAction = '';
  currentSortColumn = '';
  currentSortDirection: 'asc' | 'desc' | null = null;

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

  userData: User[] = [
    {
      id: 1,
      name: 'Alice Johnson',
      email: 'alice@example.com',
      status: 'active',
      role: 'Admin',
      lastLogin: '2024-01-15',
      joinDate: '2023-01-15'
    },
    {
      id: 2,
      name: 'Bob Smith',
      email: 'bob@example.com',
      status: 'inactive',
      role: 'User',
      lastLogin: '2024-01-10',
      joinDate: '2023-02-20'
    },
    {
      id: 3,
      name: 'Carol Williams',
      email: 'carol@example.com',
      status: 'pending',
      role: 'Editor',
      lastLogin: '2024-01-14',
      joinDate: '2023-03-10'
    },
    {
      id: 4,
      name: 'David Brown',
      email: 'david@example.com',
      status: 'active',
      role: 'User',
      lastLogin: '2024-01-16',
      joinDate: '2023-04-05'
    },
    {
      id: 5,
      name: 'Eve Davis',
      email: 'eve@example.com',
      status: 'active',
      role: 'Admin',
      lastLogin: '2024-01-16',
      joinDate: '2023-05-12'
    },
    {
      id: 6,
      name: 'Frank Miller',
      email: 'frank@example.com',
      status: 'inactive',
      role: 'User',
      lastLogin: '2024-01-08',
      joinDate: '2023-06-18'
    }
  ];

  basicColumns: TableColumn[] = [
    { key: 'name', label: 'Name', sortable: true },
    { key: 'email', label: 'Email', sortable: true },
    { key: 'role', label: 'Role', sortable: true },
    { key: 'lastLogin', label: 'Last Login', sortable: true, align: 'right' }
  ];

  advancedColumns: TableColumn[] = [
    { key: 'name', label: 'Name', sortable: true },
    { key: 'email', label: 'Email', sortable: true },
    { key: 'status', label: 'Status', align: 'center' },
    { key: 'role', label: 'Role', sortable: true },
    { key: 'actions', label: 'Actions', align: 'right', width: '120px' }
  ];

  largeDataset: User[] = [];

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

    // Generate large dataset for sticky header demo
    this.largeDataset = this.generateLargeDataset(50);
  }

  handleSort(event: TableSortEvent): void {
    this.lastAction = `Sorted by ${event.column} (${event.direction || 'none'})`;
    console.log('Sort event:', event);
  }

  handleAdvancedSort(event: TableSortEvent): void {
    this.currentSortColumn = event.column;
    this.currentSortDirection = event.direction;
    this.handleSort(event);
    
    // Actually sort the data
    if (event.direction) {
      this.userData.sort((a, b) => {
        const aVal = this.getCellValue(a, event.column);
        const bVal = this.getCellValue(b, event.column);
        
        if (event.direction === 'asc') {
          return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
        } else {
          return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
        }
      });
    }
  }

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

  handleAdvancedRowClick(event: {row: User, index: number}): void {
    this.lastAction = `Advanced row click: ${event.row.name}`;
    console.log('Advanced row click:', event);
  }

  handleSelectionChange(selectedUsers: User[]): void {
    this.selectedUsers = selectedUsers;
    this.lastAction = `Selection changed: ${selectedUsers.length} users selected`;
  }

  handleAction(event: any): void {
    const { action, data, index } = event;
    this.lastAction = `Action "${action.id}" on user ${data.name} (index: ${index})`;
    
    switch (action.id) {
      case 'edit':
        console.log('Edit user:', data);
        break;
      case 'delete':
        this.deleteUser(data.id);
        break;
      case 'view':
        console.log('View user:', data);
        break;
    }
  }

  getStatusVariant(status: string): any {
    const variants: any = {
      'active': 'success',
      'inactive': 'danger', 
      'pending': 'warning'
    };
    return variants[status] || 'neutral';
  }

  getActionsForUser(user: User): TableAction[] {
    const baseActions: TableAction[] = [
      { id: 'view', label: 'View', variant: 'view', icon: '👁️' },
      { id: 'edit', label: 'Edit', variant: 'edit', icon: '✏️' }
    ];

    if (user.status !== 'active') {
      baseActions.push({ 
        id: 'delete', 
        label: 'Delete', 
        variant: 'delete', 
        icon: '🗑️',
        confirmMessage: `Are you sure you want to delete ${user.name}?`
      });
    }

    return baseActions;
  }

  toggleLoading(): void {
    this.isLoading = !this.isLoading;
    this.lastAction = `Loading ${this.isLoading ? 'started' : 'stopped'}`;
  }

  addRandomUser(): void {
    const names = ['John Doe', 'Jane Smith', 'Mike Johnson', 'Sarah Wilson', 'Tom Anderson'];
    const roles = ['Admin', 'User', 'Editor', 'Moderator'];
    const statuses: ('active' | 'inactive' | 'pending')[] = ['active', 'inactive', 'pending'];
    
    const newUser: User = {
      id: Math.max(...this.userData.map(u => u.id)) + 1,
      name: names[Math.floor(Math.random() * names.length)],
      email: `user${Date.now()}@example.com`,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      role: roles[Math.floor(Math.random() * roles.length)],
      lastLogin: new Date().toISOString().split('T')[0],
      joinDate: new Date().toISOString().split('T')[0]
    };
    
    this.userData = [...this.userData, newUser];
    this.lastAction = `Added new user: ${newUser.name}`;
  }

  clearAllUsers(): void {
    this.userData = [];
    this.selectedUsers = [];
    this.lastAction = 'Cleared all users';
  }

  resetDemo(): void {
    this.ngOnInit();
    this.selectedUsers = [];
    this.isLoading = false;
    this.lastAction = 'Demo reset to initial state';
  }

  private deleteUser(id: number): void {
    this.userData = this.userData.filter(user => user.id !== id);
    this.selectedUsers = this.selectedUsers.filter(user => user.id !== id);
    this.lastAction = `Deleted user with ID: ${id}`;
  }

  private getCellValue(row: any, key: string): any {
    return key.split('.').reduce((obj, prop) => obj?.[prop], row) ?? '';
  }

  private generateLargeDataset(count: number): User[] {
    const dataset: User[] = [];
    const names = ['Alex', 'Morgan', 'Casey', 'Jordan', 'Taylor', 'Riley', 'Avery', 'Quinn'];
    const domains = ['example.com', 'test.com', 'demo.com', 'sample.com'];
    const roles = ['Admin', 'User', 'Editor', 'Moderator', 'Viewer'];
    const statuses: ('active' | 'inactive' | 'pending')[] = ['active', 'inactive', 'pending'];

    for (let i = 0; i < count; i++) {
      dataset.push({
        id: i + 100,
        name: `${names[i % names.length]} ${i + 1}`,
        email: `user${i + 100}@${domains[i % domains.length]}`,
        status: statuses[i % statuses.length],
        role: roles[i % roles.length],
        lastLogin: new Date(2024, 0, (i % 30) + 1).toISOString().split('T')[0],
        joinDate: new Date(2023, (i % 12), (i % 28) + 1).toISOString().split('T')[0]
      });
    }

    return dataset;
  }

  ngOnInit(): void {
    // Reset to initial data
    this.userData = [
      {
        id: 1,
        name: 'Alice Johnson',
        email: 'alice@example.com',
        status: 'active',
        role: 'Admin',
        lastLogin: '2024-01-15',
        joinDate: '2023-01-15'
      },
      {
        id: 2,
        name: 'Bob Smith',
        email: 'bob@example.com',
        status: 'inactive',
        role: 'User',
        lastLogin: '2024-01-10',
        joinDate: '2023-02-20'
      },
      {
        id: 3,
        name: 'Carol Williams',
        email: 'carol@example.com',
        status: 'pending',
        role: 'Editor',
        lastLogin: '2024-01-14',
        joinDate: '2023-03-10'
      },
      {
        id: 4,
        name: 'David Brown',
        email: 'david@example.com',
        status: 'active',
        role: 'User',
        lastLogin: '2024-01-16',
        joinDate: '2023-04-05'
      },
      {
        id: 5,
        name: 'Eve Davis',
        email: 'eve@example.com',
        status: 'active',
        role: 'Admin',
        lastLogin: '2024-01-16',
        joinDate: '2023-05-12'
      },
      {
        id: 6,
        name: 'Frank Miller',
        email: 'frank@example.com',
        status: 'inactive',
        role: 'User',
        lastLogin: '2024-01-08',
        joinDate: '2023-06-18'
      }
    ];
  }
}