/* eslint-disable @typescript-eslint/member-ordering */
import {
  Component,
  inject,
  signal
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgIcon, provideIcons } from '@ng-icons/core';
import {
  lucideShield,
  lucidePlus,
  lucideTrash2,
  lucideArrowUp,
  lucideArrowDown,
  lucideRotateCcw
} from '@ng-icons/lucide';

import { IceServerSettingsService, IceServerEntry } from '../../../../infrastructure/realtime/ice-server-settings.service';

@Component({
  selector: 'app-ice-server-settings',
  standalone: true,
  host: {
    style: 'display: block;'
  },
  imports: [
    CommonModule,
    FormsModule,
    NgIcon
  ],
  viewProviders: [
    provideIcons({
      lucideShield,
      lucidePlus,
      lucideTrash2,
      lucideArrowUp,
      lucideArrowDown,
      lucideRotateCcw
    })
  ],
  templateUrl: './ice-server-settings.component.html'
})
export class IceServerSettingsComponent {
  private iceSettings = inject(IceServerSettingsService);

  entries = this.iceSettings.entries;

  addError = signal<string | null>(null);
  newType: 'stun' | 'turn' = 'stun';
  newUrl = '';
  newUsername = '';
  newCredential = '';

  addEntry(): void {
    this.addError.set(null);

    const url = this.newUrl.trim();

    if (!url) {
      this.addError.set('URL is required');
      return;
    }

    const prefix = this.newType === 'stun' ? 'stun:' : 'turn';

    if (!url.startsWith(prefix) && !url.startsWith('turns:')) {
      this.addError.set(`URL must start with ${this.newType === 'stun' ? 'stun:' : 'turn: or turns:'}`);
      return;
    }

    if (this.newType === 'turn' && !this.newUsername.trim()) {
      this.addError.set('Username is required for TURN servers');
      return;
    }

    if (this.newType === 'turn' && !this.newCredential.trim()) {
      this.addError.set('Credential is required for TURN servers');
      return;
    }

    if (this.entries().some((entry) => entry.urls === url)) {
      this.addError.set('This URL already exists');
      return;
    }

    this.iceSettings.addEntry({
      type: this.newType,
      urls: url,
      ...(this.newType === 'turn'
        ? { username: this.newUsername.trim(), credential: this.newCredential.trim() }
        : {})
    });

    this.newUrl = '';
    this.newUsername = '';
    this.newCredential = '';
  }

  removeEntry(id: string): void {
    this.iceSettings.removeEntry(id);
  }

  moveUp(index: number): void {
    if (index > 0)
      this.iceSettings.moveEntry(index, index - 1);
  }

  moveDown(index: number): void {
    if (index < this.entries().length - 1)
      this.iceSettings.moveEntry(index, index + 1);
  }

  restoreDefaults(): void {
    this.iceSettings.restoreDefaults();
  }

  trackEntry(_index: number, entry: IceServerEntry): string {
    return entry.id;
  }
}
