import { animate, state, style, transition, trigger } from '@angular/animations';
import { Component, ElementRef, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
import { CommonNzModule } from './../../common.nz.module';

@Component({
  selector: 'datav-select',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './datav-select.component.html',
  styleUrl: './datav-select.component.less',
  animations: [
    trigger('dropdown', [
      state('in', style({ transform: 'translate(0, 0%)', opacity: 1 })),
      transition('void => *', [style({ transform: 'translate(0, -100%)', opacity: 0 }), animate(150)]),
      transition('* => void', [animate(150, style({ transform: 'translate(0, -100%)', opacity: 0 }))]),
    ]),
  ],
})
export class DatavSelectComponent<T = any> {
  @ViewChild('dropdown') dropdown!: ElementRef<HTMLDivElement>;
  listen$?: Subscription;
  @Input() placeholder = '请选择';
  @Input() value: T | null = null;
  @Input() options: Option<T>[] = [];
  @Output() onChange = new EventEmitter<T>();

  dropdownVisible = false;

  constructor(private el: ElementRef) {}
  onClick() {
    this.dropdownVisible = !this.dropdownVisible;
    if (this.dropdownVisible) {
      setTimeout(() => {
        this.addListener();
      });
    } else {
      this.removeListener();
    }
  }
  handleChange(value: T) {
    this.onChange.emit(value);
    this.onClick();
  }

  addListener() {
    this.listen$ = fromEvent(document, 'click').subscribe((e: Event) => {
      if (e.target && !this.el.nativeElement.parentElement!.contains(e.target as Node)) {
        this.dropdownVisible = false;
        this.removeListener();
      }
    });
  }
  removeListener() {
    if (this.listen$) {
      this.listen$?.unsubscribe();
      this.listen$ = undefined;
    }
  }
  ngOnDestroy() {
    this.removeListener();
  }
  get label() {
    if (!this.value) return '';
    return this.options.find(option => option.value === this.value)?.label || '';
  }

  get dropdownHeight() {
    return this.dropdownVisible ? 'auto' : 0;
  }
  get minWidth() {
    return this.el.nativeElement.clientWidth;
  }
}
