import { Component, Input, Output, EventEmitter, forwardRef, OnInit, OnDestroy, ElementRef, ViewChild } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { trigger, state, style, transition, animate } from '@angular/animations';

export interface DropdownOption {
  value: any;
  label: string;
  icon?: string;
  disabled?: boolean;
  group?: string;
  description?: string;
  isGroup?: boolean;
}

@Component({
  selector: 'app-dropdown',
  standalone: true,
  imports: [CommonModule, MatIconModule, MatButtonModule, FormsModule],
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => DropdownComponent),
      multi: true
    }
  ],
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({
          opacity: 0,
          transform: 'translateY(-10px) scale(0.95)'
        }),
        animate('200ms cubic-bezier(0.25, 0.8, 0.25, 1)', style({
          opacity: 1,
          transform: 'translateY(0) scale(1)'
        }))
      ]),
      transition(':leave', [
        animate('150ms cubic-bezier(0.25, 0.8, 0.25, 1)', style({
          opacity: 0,
          transform: 'translateY(-10px) scale(0.95)'
        }))
      ])
    ])
  ]
})
export class DropdownComponent implements ControlValueAccessor, OnInit, OnDestroy {
  @ViewChild('dropdownWrapper') dropdownWrapper!: ElementRef;
  @ViewChild('optionsContainer') optionsContainer!: ElementRef;
  @ViewChild('searchInput') searchInput!: ElementRef;

  // 基础配置
  @Input() options: DropdownOption[] = [];
  @Input() placeholder: string = '请选择...';
  @Input() label: string = '';
  @Input() disabled: boolean = false;
  @Input() required: boolean = false;
  @Input() multiple: boolean = false;
  @Input() clearable: boolean = true;
  @Input() searchable: boolean = false;
  @Input() maxHeight: number = 300;
  
  // 样式配置
  @Input() size: 'small' | 'medium' | 'large' = 'medium';
  @Input() variant: 'outlined' | 'filled' | 'standard' = 'outlined';
  @Input() color: 'primary' | 'secondary' | 'success' | 'warning' | 'error' = 'primary';
  
  // 验证
  @Input() errorMessage: string = '';
  @Input() helpText: string = '';
  
  // 事件
  @Output() selectionChange = new EventEmitter<any>();
  @Output() opened = new EventEmitter<void>();
  @Output() closed = new EventEmitter<void>();
  @Output() searchChange = new EventEmitter<string>();

  // 组件状态
  isOpen: boolean = false;
  isFocused: boolean = false;
  searchTerm: string = '';
  selectedValue: any = null;
  selectedValues: any[] = [];
  filteredOptions: DropdownOption[] = [];
  highlightedIndex: number = -1;
  groupedOptions: Map<string, DropdownOption[]> = new Map();

  // ControlValueAccessor
  private onChange = (value: any) => {};
  private onTouched = () => {};

  constructor(private elementRef: ElementRef) {}

  ngOnInit() {
    this.filteredOptions = [...this.options];
    this.updateGroupedOptions();
  }

  ngOnDestroy() {
    this.removeClickOutside();
  }

  // ControlValueAccessor 实现
  writeValue(value: any): void {
    if (this.multiple) {
      this.selectedValues = Array.isArray(value) ? value : [];
    } else {
      this.selectedValue = value;
    }
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  // 计算属性
  get hasValue(): boolean {
    return this.multiple ? this.selectedValues.length > 0 : this.selectedValue !== null && this.selectedValue !== undefined;
  }

  get hasError(): boolean {
    return !!this.errorMessage;
  }

  get selectedOption(): DropdownOption | null {
    if (this.multiple) return null;
    return this.options.find(option => option.value === this.selectedValue) || null;
  }

  get displayText(): string {
    if (this.multiple) {
      if (this.selectedValues.length === 0) {
        return this.placeholder;
      } else {
        return `已选择 ${this.selectedValues.length} 项`;
      }
    } else {
      return this.selectedOption?.label || this.placeholder;
    }
  }

  get selectedOptions(): DropdownOption[] {
    if (!this.multiple) return [];
    return this.options.filter(option => this.selectedValues.includes(option.value));
  }

  // 交互方法（保留旧方法以兼容）
  toggle(): void {
    this.toggleDropdown();
  }

  open(): void {
    this.openDropdown();
  }

  close(): void {
    this.closeDropdown();
  }

  selectOption(option: DropdownOption, event?: Event): void {
    if (event) {
      event.stopPropagation();
    }

    if (option.disabled) return;

    if (this.multiple) {
      const index = this.selectedValues.indexOf(option.value);
      if (index > -1) {
        this.selectedValues.splice(index, 1);
      } else {
        this.selectedValues.push(option.value);
      }
      this.onChange([...this.selectedValues]);
      this.selectionChange.emit([...this.selectedValues]);
    } else {
      this.selectedValue = option.value;
      this.onChange(this.selectedValue);
      this.selectionChange.emit(this.selectedValue);
      this.closeDropdown();
    }
  }

  clear(event: Event): void {
    this.clearSelection(event);
  }

  isSelected(option: DropdownOption): boolean {
    if (this.multiple) {
      return this.selectedValues.includes(option.value);
    } else {
      return this.selectedValue === option.value;
    }
  }

  isGroupHeader(option: DropdownOption): boolean {
    if (!option.group) return false;
    const index = this.filteredOptions.indexOf(option);
    if (index === 0) return true;
    const prevOption = this.filteredOptions[index - 1];
    return prevOption.group !== option.group;
  }

  onSearch(): void {
    this.filteredOptions = this.options.filter(option => 
      option.label.toLowerCase().includes(this.searchTerm.toLowerCase())
    );
    this.updateGroupedOptions();
    this.highlightedIndex = -1;
    this.searchChange.emit(this.searchTerm);
  }

  clearSearch(): void {
    this.searchTerm = '';
    this.onSearch();
  }

  toggleDropdown(): void {
    if (this.disabled) return;
    
    if (this.isOpen) {
      this.closeDropdown();
    } else {
      this.openDropdown();
    }
  }

  openDropdown(): void {
    if (this.disabled) return;
    
    this.isOpen = true;
    this.isFocused = true;
    this.filteredOptions = [...this.options];
    this.updateGroupedOptions();
    this.highlightedIndex = -1;
    this.setupClickOutside();
    this.opened.emit();

    // 聚焦搜索框
    if (this.searchable) {
      setTimeout(() => {
        const searchInput = document.querySelector('.search-input') as HTMLInputElement;
        if (searchInput) {
          searchInput.focus();
        }
      }, 100);
    }
  }

  closeDropdown(): void {
    this.isOpen = false;
    this.isFocused = false;
    this.searchTerm = '';
    this.highlightedIndex = -1;
    this.removeClickOutside();
    this.closed.emit();
    this.onTouched();
  }

  removeOption(event: Event, option: DropdownOption): void {
    event.stopPropagation();
    
    if (this.multiple) {
      const index = this.selectedValues.indexOf(option.value);
      if (index > -1) {
        this.selectedValues.splice(index, 1);
        this.onChange([...this.selectedValues]);
        this.selectionChange.emit([...this.selectedValues]);
      }
    }
  }

  clearSelection(event: Event): void {
    event.stopPropagation();
    
    if (this.multiple) {
      this.selectedValues = [];
      this.onChange([]);
      this.selectionChange.emit([]);
    } else {
      this.selectedValue = null;
      this.onChange(null);
      this.selectionChange.emit(null);
    }
  }

  onKeyDown(event: KeyboardEvent): void {
    switch (event.key) {
      case 'Enter':
      case ' ':
        event.preventDefault();
        if (!this.isOpen) {
          this.openDropdown();
        } else if (this.highlightedIndex >= 0) {
          const option = this.filteredOptions[this.highlightedIndex];
          if (option && !option.disabled && !option.isGroup) {
            this.selectOption(option);
          }
        }
        break;
        
      case 'Escape':
        event.preventDefault();
        this.closeDropdown();
        break;
        
      case 'ArrowDown':
        event.preventDefault();
        if (!this.isOpen) {
          this.openDropdown();
        } else {
          this.highlightNext();
        }
        break;
        
      case 'ArrowUp':
        event.preventDefault();
        if (this.isOpen) {
          this.highlightPrevious();
        }
        break;

      case 'Home':
        if (this.isOpen) {
          event.preventDefault();
          this.highlightFirst();
        }
        break;

      case 'End':
        if (this.isOpen) {
          event.preventDefault();
          this.highlightLast();
        }
        break;
        
      case 'Tab':
        if (this.isOpen) {
          this.closeDropdown();
        }
        break;

      // 字母键快速导航
      default:
        if (this.isOpen && event.key.length === 1 && /[a-zA-Z0-9]/.test(event.key)) {
          this.quickNavigate(event.key.toLowerCase());
        }
        break;
    }
  }

  private highlightNext(): void {
    const maxIndex = this.filteredOptions.length - 1;
    let nextIndex = this.highlightedIndex < maxIndex ? this.highlightedIndex + 1 : 0;
    
    // 跳过禁用和分组标题选项
    while (nextIndex !== this.highlightedIndex) {
      const option = this.filteredOptions[nextIndex];
      if (option && !option.disabled && !option.isGroup) {
        this.highlightedIndex = nextIndex;
        this.scrollToHighlighted();
        return;
      }
      nextIndex = nextIndex < maxIndex ? nextIndex + 1 : 0;
    }
  }

  private highlightPrevious(): void {
    const maxIndex = this.filteredOptions.length - 1;
    let prevIndex = this.highlightedIndex > 0 ? this.highlightedIndex - 1 : maxIndex;
    
    // 跳过禁用和分组标题选项
    while (prevIndex !== this.highlightedIndex) {
      const option = this.filteredOptions[prevIndex];
      if (option && !option.disabled && !option.isGroup) {
        this.highlightedIndex = prevIndex;
        this.scrollToHighlighted();
        return;
      }
      prevIndex = prevIndex > 0 ? prevIndex - 1 : maxIndex;
    }
  }

  private highlightFirst(): void {
    for (let i = 0; i < this.filteredOptions.length; i++) {
      const option = this.filteredOptions[i];
      if (option && !option.disabled && !option.isGroup) {
        this.highlightedIndex = i;
        this.scrollToHighlighted();
        return;
      }
    }
  }

  private highlightLast(): void {
    for (let i = this.filteredOptions.length - 1; i >= 0; i--) {
      const option = this.filteredOptions[i];
      if (option && !option.disabled && !option.isGroup) {
        this.highlightedIndex = i;
        this.scrollToHighlighted();
        return;
      }
    }
  }

  private quickNavigate(key: string): void {
    const startIndex = this.highlightedIndex + 1;
    
    // 从当前位置之后开始搜索
    for (let i = startIndex; i < this.filteredOptions.length; i++) {
      const option = this.filteredOptions[i];
      if (option && !option.disabled && !option.isGroup && 
          option.label.toLowerCase().startsWith(key)) {
        this.highlightedIndex = i;
        this.scrollToHighlighted();
        return;
      }
    }
    
    // 如果没找到，从头开始搜索
    for (let i = 0; i < startIndex; i++) {
      const option = this.filteredOptions[i];
      if (option && !option.disabled && !option.isGroup && 
          option.label.toLowerCase().startsWith(key)) {
        this.highlightedIndex = i;
        this.scrollToHighlighted();
        return;
      }
    }
  }

  private scrollToHighlighted(): void {
    if (this.highlightedIndex >= 0 && this.optionsContainer) {
      const optionElements = this.optionsContainer.nativeElement.querySelectorAll('.dropdown-option:not(.group-header)');
      const highlightedElement = optionElements[this.highlightedIndex];
      
      if (highlightedElement) {
        highlightedElement.scrollIntoView({
          block: 'nearest',
          behavior: 'smooth'
        });
      }
    }
  }

  getOptionIndex(option: DropdownOption): number {
    return this.filteredOptions.indexOf(option);
  }

  private updateGroupedOptions(): void {
    this.groupedOptions.clear();
    
    this.filteredOptions.forEach(option => {
      if (option.group) {
        if (!this.groupedOptions.has(option.group)) {
          this.groupedOptions.set(option.group, []);
        }
        this.groupedOptions.get(option.group)!.push(option);
      }
    });
  }

  // 点击外部关闭
  private clickOutsideHandler = (event: Event) => {
    if (!this.elementRef.nativeElement.contains(event.target)) {
      this.close();
    }
  };

  private setupClickOutside(): void {
    document.addEventListener('click', this.clickOutsideHandler);
  }

  private removeClickOutside(): void {
    document.removeEventListener('click', this.clickOutsideHandler);
  }
}