import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SubmitReviewInput } from '../../../../../../core/products/models/product-engagement.model';
import { TranslatePipe } from '../../../../../../i18n/translate.pipe';
import { StarSelectorComponent } from '../star-selector/star-selector.component';

@Component({
  selector: 'app-review-form',
  standalone: true,
  imports: [FormsModule, StarSelectorComponent, TranslatePipe],
  templateUrl: './review-form.component.html',
  styleUrls: ['./review-form.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ReviewFormComponent {
  @Input() submitting = false;
  @Output() submitReview = new EventEmitter<SubmitReviewInput>();

  rating = 0;
  title = '';
  text = '';
  anonymous = false;
  attemptedSubmit = false;
  submittedSuccessfully = false;

  onSubmit(): void {
    this.attemptedSubmit = true;
    const payload: SubmitReviewInput = {
      rating: this.rating,
      title: this.title,
      text: this.text,
      anonymous: this.anonymous
    };

    if (!payload.rating || !payload.text.trim()) {
      return;
    }

    this.submitReview.emit(payload);
    this.submittedSuccessfully = true;
    this.reset();
  }

  updateRating(value: number): void {
    this.rating = value;
    this.submittedSuccessfully = false;
  }

  hideSuccess(): void {
    this.submittedSuccessfully = false;
  }

  get showRatingError(): boolean {
    return this.attemptedSubmit && !this.rating;
  }

  get showTextError(): boolean {
    return this.attemptedSubmit && !this.text.trim();
  }

  private reset(): void {
    this.rating = 0;
    this.title = '';
    this.text = '';
    this.anonymous = false;
    this.attemptedSubmit = false;
  }
}
