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

@Component({
  selector: 'app-slider-range',
  templateUrl: './slider-range.component.html',
  styleUrls: ['./slider-range.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => SliderRangeComponent),
      multi: true,
    },
  ],
})
export class SliderRangeComponent implements ControlValueAccessor {
  @Input() value: number = 10;
  @Input() max: number = 300;
  @Input() icon: string = '';
  @Output() valueChange = new EventEmitter<number>();

  onChange = (value: number) => {};
  onTouched = () => {};

  constructor() {}

  writeValue(value: number): void {
    this.value = value;
  }

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

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

  setDisabledState?(isDisabled: boolean): void {
    // Handle the disabled state if needed
  }

  onSliderChange(event: any) {
    this.value = event.target.value;
    this.onChange(this.value);
    this.onTouched();
    this.valueChange.emit(this.value);
  }

  onSliderChangeBackground() {
    let valPercent = (this.value / this.max) * 100;

    // Adjust valPercent based on your conditions
    switch (true) {
      case valPercent > 10 && valPercent <= 30:
        valPercent -= 0.5;
        break;
      case valPercent > 30 && valPercent <= 50:
        valPercent -= 1;
        break;
      case valPercent > 50 && valPercent <= 70:
        valPercent -= 1.5;
        break;
      case valPercent > 70 && valPercent <= 90:
        valPercent -= 2;
        break;
      case valPercent > 90 && valPercent <= 100:
        valPercent -= 2.3;
        break;
      default:
        break;
    }

    // Return CSS object with background style
    return {
      background: `linear-gradient(to right, #ff7723 ${valPercent}%, transparent ${valPercent}%)`,
    };
  }

  increaseVolume() {
    if (this.value < this.max) {
      this.value += 10;
      this.onChange(this.value);
      this.onTouched();
      this.valueChange.emit(this.value);
    }
  }

  decreaseVolume() {
    if (this.value > 0) {
      this.value -= 10;
      this.onChange(this.value);
      this.onTouched();
      this.valueChange.emit(this.value);
    }
  }
}
