import { Component, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-star-rating',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './star-rating.component.html',
  styleUrls: ['./star-rating.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => StarRatingComponent),
      multi: true
    }
  ]
})
export class StarRatingComponent implements ControlValueAccessor {
  @Input() rating: number = 0;
  @Input() maxStars: number = 5;
  @Input() size: 'small' | 'medium' | 'large' = 'medium';
  @Input() readonly: boolean = false;
  @Input() showText: boolean = true;
  
  @Output() ratingChange = new EventEmitter<number>();

  stars: { index: number; filled: boolean; hovered: boolean; }[] = [];
  hoverRating: number = 0;
  
  private onChange: (value: number) => void = () => {};
  private onTouched: () => void = () => {};

  ngOnInit() {
    this.updateStars();
  }

  ngOnChanges() {
    this.updateStars();
  }

  updateStars() {
    this.stars = Array.from({ length: this.maxStars }, (_, index) => ({
      index: index + 1,
      filled: index < this.rating,
      hovered: index < this.hoverRating
    }));
  }

  setRating(rating: number) {
    if (this.readonly) return;
    
    this.rating = rating;
    this.hoverRating = 0;
    this.updateStars();
    this.ratingChange.emit(rating);
    this.onChange(rating);
    this.onTouched();
  }

  setHoverRating(rating: number) {
    if (this.readonly) return;
    
    this.hoverRating = rating;
    this.updateStars();
  }

  clearHover() {
    if (this.readonly) return;
    
    this.hoverRating = 0;
    this.updateStars();
  }

  getRatingText(): string {
    const texts = [
      '非常差',
      '差',
      '一般',
      '好',
      '非常好'
    ];
    
    return texts[Math.floor(this.rating) - 1] || '';
  }

  // ControlValueAccessor implementation
  writeValue(value: number): void {
    this.rating = value || 0;
    this.updateStars();
  }

  registerOnChange(fn: (value: number) => void): void {
    this.onChange = fn;
  }

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

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