import { Component, ViewChild, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ListDetailLayoutComponent } from '../../../../../ui-essentials/src/lib/components/layout/list-detail-layout/list-detail-layout.component';

interface DemoItem {
  id: number;
  title: string;
  subtitle: string;
  description: string;
  status: 'active' | 'pending' | 'completed';
  category: string;
  date: string;
}

@Component({
  selector: 'ui-list-detail-layout-demo',
  standalone: true,
  imports: [CommonModule, ListDetailLayoutComponent],
  template: `
    <div class="demo-container">
      <h2>List Detail Layout Demo</h2>
      <p>Master-detail pattern with resizable panes and mobile-adaptive behavior</p>
      
      <!-- Size Variants -->
      <section class="demo-section">
        <h3>Size Variants</h3>
        <div class="demo-variant-container">
          @for (size of sizes; track size) {
            <div class="demo-variant">
              <h4>{{ size | titlecase }} Size</h4>
              <div class="demo-layout-container" [class]="'demo-layout--' + size">
                <ui-list-detail-layout 
                  [size]="size"
                  [selectedItem]="selectedItems[size]"
                  (selectionChanged)="handleSelectionChange(size, $event)">
                  
                  <div slot="list" class="demo-list">
                    <div class="demo-list__header">
                      <h4>Items ({{ size }})</h4>
                    </div>
                    <div class="demo-list__content">
                      @for (item of demoItems(); track item.id) {
                        <div 
                          class="demo-list-item"
                          [class.demo-list-item--selected]="selectedItems[size]?.id === item.id"
                          (click)="selectItem(size, item)"
                          [attr.aria-selected]="selectedItems[size]?.id === item.id"
                          role="option">
                          <div class="demo-list-item__content">
                            <h5>{{ item.title }}</h5>
                            <p>{{ item.subtitle }}</p>
                            <span class="demo-list-item__status demo-list-item__status--{{ item.status }}">
                              {{ item.status }}
                            </span>
                          </div>
                        </div>
                      }
                    </div>
                  </div>
                  
                  <div slot="detail" class="demo-detail">
                    @if (selectedItems[size]) {
                      <div class="demo-detail__header">
                        <h3>{{ selectedItems[size].title }}</h3>
                        <span class="demo-detail__category">{{ selectedItems[size].category }}</span>
                      </div>
                      <div class="demo-detail__content">
                        <div class="demo-detail__meta">
                          <p><strong>Subtitle:</strong> {{ selectedItems[size].subtitle }}</p>
                          <p><strong>Status:</strong> {{ selectedItems[size].status }}</p>
                          <p><strong>Date:</strong> {{ selectedItems[size].date }}</p>
                        </div>
                        <div class="demo-detail__description">
                          <h4>Description</h4>
                          <p>{{ selectedItems[size].description }}</p>
                        </div>
                        <div class="demo-detail__actions">
                          <button 
                            type="button"
                            class="demo-button demo-button--primary"
                            (click)="handleAction('edit', selectedItems[size])">
                            Edit Item
                          </button>
                          <button 
                            type="button"
                            class="demo-button demo-button--secondary"
                            (click)="handleAction('delete', selectedItems[size])">
                            Delete Item
                          </button>
                        </div>
                      </div>
                    }
                  </div>
                  
                  <div slot="empty" class="demo-empty-state">
                    <div class="demo-empty-state__icon">📋</div>
                    <h4>No Item Selected</h4>
                    <p>Choose an item from the list to view its details</p>
                  </div>
                </ui-list-detail-layout>
              </div>
            </div>
          }
        </div>
      </section>
      
      <!-- Variant Styles -->
      <section class="demo-section">
        <h3>Style Variants</h3>
        <div class="demo-variant-container">
          @for (variant of variants; track variant) {
            <div class="demo-variant">
              <h4>{{ variant | titlecase }} Style</h4>
              <div class="demo-layout-container demo-layout--variant">
                <ui-list-detail-layout 
                  [variant]="variant"
                  [selectedItem]="selectedItems[variant]"
                  (selectionChanged)="handleSelectionChange(variant, $event)">
                  
                  <div slot="list" class="demo-list">
                    <div class="demo-list__header">
                      <h4>{{ variant | titlecase }} List</h4>
                    </div>
                    <div class="demo-list__content">
                      @for (item of demoItems().slice(0, 3); track item.id) {
                        <div 
                          class="demo-list-item"
                          [class.demo-list-item--selected]="selectedItems[variant]?.id === item.id"
                          (click)="selectItem(variant, item)"
                          role="option">
                          <div class="demo-list-item__content">
                            <h5>{{ item.title }}</h5>
                            <p>{{ item.subtitle }}</p>
                          </div>
                        </div>
                      }
                    </div>
                  </div>
                  
                  <div slot="detail" class="demo-detail">
                    @if (selectedItems[variant]) {
                      <div class="demo-detail__header">
                        <h3>{{ selectedItems[variant].title }}</h3>
                      </div>
                      <div class="demo-detail__content">
                        <p>{{ selectedItems[variant].description }}</p>
                      </div>
                    }
                  </div>
                </ui-list-detail-layout>
              </div>
            </div>
          }
        </div>
      </section>
      
      <!-- Interactive Features -->
      <section class="demo-section">
        <h3>Interactive Features</h3>
        <div class="demo-interactive">
          <div class="demo-controls">
            <label>
              <input 
                type="checkbox" 
                [checked]="interactiveFeatures.resizable"
                (change)="toggleFeature('resizable', $event)">
              Resizable Panels
            </label>
            <label>
              <input 
                type="checkbox" 
                [checked]="interactiveFeatures.showEmptyState"
                (change)="toggleFeature('showEmptyState', $event)">
              Show Empty State
            </label>
            <label>
              <input 
                type="checkbox" 
                [checked]="interactiveFeatures.showMobileNavigation"
                (change)="toggleFeature('showMobileNavigation', $event)">
              Mobile Navigation
            </label>
            <label>
              <input 
                type="checkbox" 
                [checked]="interactiveFeatures.loading"
                (change)="toggleFeature('loading', $event)">
              Loading State
            </label>
          </div>
          
          <div class="demo-layout-container demo-layout--interactive">
            <ui-list-detail-layout 
              #interactiveLayout
              [resizable]="interactiveFeatures.resizable"
              [showEmptyState]="interactiveFeatures.showEmptyState"
              [showMobileNavigation]="interactiveFeatures.showMobileNavigation"
              [loading]="interactiveFeatures.loading"
              [selectedItem]="selectedItems['interactive']"
              (selectionChanged)="handleSelectionChange('interactive', $event)"
              (mobileNavigated)="handleMobileNavigation($event)"
              (panelResized)="handlePanelResize($event)">
              
              <div slot="list" class="demo-list">
                <div class="demo-list__header">
                  <h4>Interactive List</h4>
                  <button 
                    type="button"
                    class="demo-button demo-button--small"
                    (click)="clearSelection('interactive')">
                    Clear Selection
                  </button>
                </div>
                <div class="demo-list__content">
                  @for (item of demoItems(); track item.id) {
                    <div 
                      class="demo-list-item"
                      [class.demo-list-item--selected]="selectedItems['interactive']?.id === item.id"
                      (click)="selectItem('interactive', item)"
                      role="option">
                      <div class="demo-list-item__content">
                        <h5>{{ item.title }}</h5>
                        <p>{{ item.subtitle }}</p>
                        <span class="demo-list-item__status demo-list-item__status--{{ item.status }}">
                          {{ item.status }}
                        </span>
                      </div>
                    </div>
                  }
                </div>
              </div>
              
              <div slot="detail" class="demo-detail">
                @if (selectedItems['interactive']) {
                  <div class="demo-detail__header">
                    <h3>{{ selectedItems['interactive'].title }}</h3>
                    <span class="demo-detail__category">{{ selectedItems['interactive'].category }}</span>
                  </div>
                  <div class="demo-detail__content">
                    <p>{{ selectedItems['interactive'].description }}</p>
                    <div class="demo-detail__stats">
                      <div class="demo-stat">
                        <label>Status:</label>
                        <span>{{ selectedItems['interactive'].status }}</span>
                      </div>
                      <div class="demo-stat">
                        <label>Category:</label>
                        <span>{{ selectedItems['interactive'].category }}</span>
                      </div>
                      <div class="demo-stat">
                        <label>Date:</label>
                        <span>{{ selectedItems['interactive'].date }}</span>
                      </div>
                    </div>
                  </div>
                }
              </div>
              
              <div slot="empty" class="demo-empty-state">
                <div class="demo-empty-state__icon">🎯</div>
                <h4>Ready to Explore</h4>
                <p>Select any item to see the interactive features in action</p>
              </div>
            </ui-list-detail-layout>
          </div>
        </div>
      </section>
      
      <!-- Event Log -->
      <section class="demo-section">
        <h3>Event Log</h3>
        <div class="demo-event-log">
          @for (event of eventLog(); track $index) {
            <div class="demo-event-log__item">
              <span class="demo-event-log__timestamp">{{ event.timestamp }}</span>
              <span class="demo-event-log__type">{{ event.type }}</span>
              <span class="demo-event-log__data">{{ event.data }}</span>
            </div>
          }
        </div>
      </section>
    </div>
  `,
  styleUrl: './list-detail-layout-demo.component.scss'
})
export class ListDetailLayoutDemoComponent {
  @ViewChild('interactiveLayout') interactiveLayout?: ListDetailLayoutComponent;
  
  sizes = ['sm', 'md', 'lg'] as const;
  variants = ['default', 'bordered', 'elevated'] as const;
  
  selectedItems: Record<string, DemoItem | null> = {
    sm: null,
    md: null,
    lg: null,
    default: null,
    bordered: null,
    elevated: null,
    interactive: null
  };
  
  interactiveFeatures = {
    resizable: true,
    showEmptyState: true,
    showMobileNavigation: true,
    loading: false
  };
  
  demoItems = signal<DemoItem[]>([
    {
      id: 1,
      title: 'Project Alpha',
      subtitle: 'High-priority initiative',
      description: 'A comprehensive project focused on improving user experience and system performance. This initiative involves multiple teams and requires careful coordination across different departments.',
      status: 'active',
      category: 'Development',
      date: '2024-01-15'
    },
    {
      id: 2,
      title: 'Database Migration',
      subtitle: 'Critical infrastructure update',
      description: 'Migration of legacy database systems to modern cloud infrastructure. This project includes data validation, performance optimization, and minimal downtime deployment strategies.',
      status: 'pending',
      category: 'Infrastructure',
      date: '2024-02-01'
    },
    {
      id: 3,
      title: 'UI Component Library',
      subtitle: 'Design system implementation',
      description: 'Development of a comprehensive UI component library to ensure consistency across all applications. Includes documentation, testing, and integration guidelines.',
      status: 'completed',
      category: 'Design',
      date: '2024-01-28'
    },
    {
      id: 4,
      title: 'Security Audit',
      subtitle: 'Annual security review',
      description: 'Comprehensive security audit covering all systems, applications, and infrastructure. Includes penetration testing, vulnerability assessment, and compliance verification.',
      status: 'active',
      category: 'Security',
      date: '2024-02-10'
    },
    {
      id: 5,
      title: 'Mobile App Redesign',
      subtitle: 'User interface overhaul',
      description: 'Complete redesign of the mobile application focusing on improved usability, modern design patterns, and enhanced accessibility features.',
      status: 'pending',
      category: 'Mobile',
      date: '2024-03-01'
    }
  ]);
  
  eventLog = signal<Array<{ timestamp: string; type: string; data: string }>>([]);
  
  selectItem(context: string, item: DemoItem): void {
    this.selectedItems[context] = item;
    this.logEvent('selection', `Selected: ${item.title} (${context})`);
  }
  
  clearSelection(context: string): void {
    this.selectedItems[context] = null;
    this.logEvent('selection', `Cleared selection (${context})`);
  }
  
  handleSelectionChange(context: string, item: DemoItem | null): void {
    this.selectedItems[context] = item;
    this.logEvent('selectionChanged', 
      item ? `Item selected: ${item.title}` : 'Selection cleared');
  }
  
  handleMobileNavigation(event: any): void {
    this.logEvent('mobileNavigation', 
      `Navigated to: ${event.view} (has selection: ${event.hasSelection})`);
  }
  
  handlePanelResize(event: any): void {
    this.logEvent('panelResize', `List width: ${event.listWidth}px`);
  }
  
  handleAction(action: string, item: DemoItem): void {
    this.logEvent('action', `${action} action on: ${item.title}`);
  }
  
  toggleFeature(feature: keyof typeof this.interactiveFeatures, event: Event): void {
    const target = event.target as HTMLInputElement;
    this.interactiveFeatures[feature] = target.checked;
    this.logEvent('feature', `${feature}: ${target.checked ? 'enabled' : 'disabled'}`);
  }
  
  private logEvent(type: string, data: string): void {
    const timestamp = new Date().toLocaleTimeString();
    const events = this.eventLog();
    events.unshift({ timestamp, type, data });
    // Keep only last 10 events
    if (events.length > 10) {
      events.splice(10);
    }
    this.eventLog.set([...events]);
  }
}