/* eslint-disable @typescript-eslint/member-ordering */
import {
  Component,
  inject,
  OnInit,
  signal
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { Store } from '@ngrx/store';
import { NgIcon, provideIcons } from '@ng-icons/core';
import {
  lucideArrowLeft,
  lucideChevronDown,
  lucideChevronUp
} from '@ng-icons/lucide';

import { APP_TRANSLATE_IMPORTS } from '../../../../core/i18n';
import { AutoFocusDirective, SelectOnFocusDirective } from '../../../../shared/directives';
import { RoomsActions } from '../../../../store/rooms/rooms.actions';
import { selectCurrentUser } from '../../../../store/users/users.selectors';
import { setStoredCurrentUserId } from '../../../../core/storage/current-user-storage';
import { buildLoginReturnQueryParams } from '../../../authentication/domain/logic/auth-navigation.rules';
import { ServerDirectoryFacade } from '../../application/facades/server-directory.facade';

/** Preset categories that pre-fill the server topic to speed up creation. */
export interface ServerCategoryPreset {
  id: string;
  topic: string;
}

export const CATEGORY_PRESETS: ServerCategoryPreset[] = [
  { id: 'gaming', topic: 'gaming' },
  { id: 'music', topic: 'music' },
  { id: 'coding', topic: 'coding' },
  { id: 'community', topic: 'community' },
  { id: 'study', topic: 'study' }
];

/**
 * Dedicated server-creation page. Replaces the old in-search create dialog with a
 * focused form: category presets up front and signaling/privacy options behind a
 * progressive-disclosure "Advanced settings" section.
 */
@Component({
  selector: 'app-create-server',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    RouterLink,
    NgIcon,
    AutoFocusDirective,
    SelectOnFocusDirective,
    ...APP_TRANSLATE_IMPORTS
  ],
  viewProviders: [provideIcons({ lucideArrowLeft, lucideChevronDown, lucideChevronUp })],
  templateUrl: './create-server.component.html'
})
export class CreateServerComponent implements OnInit {
  private store = inject(Store);
  private router = inject(Router);
  private serverDirectory = inject(ServerDirectoryFacade);
  private currentUser = this.store.selectSignal(selectCurrentUser);

  readonly categories = CATEGORY_PRESETS;
  activeEndpoints = this.serverDirectory.activeServers;

  name = signal('');
  description = signal('');
  topic = signal('');
  selectedCategoryId = signal<string | null>(null);
  isPrivate = signal(false);
  password = signal('');
  sourceId = '';
  showAdvanced = signal(false);

  ngOnInit(): void {
    this.sourceId = this.activeEndpoints()[0]?.id ?? '';
  }

  /** True when the form has enough to create a server. */
  get canCreate(): boolean {
    return this.name().trim().length > 0 && this.sourceId.length > 0;
  }

  selectCategory(category: ServerCategoryPreset): void {
    if (this.selectedCategoryId() === category.id) {
      this.selectedCategoryId.set(null);
      this.topic.set('');
      return;
    }

    this.selectedCategoryId.set(category.id);
    this.topic.set(category.topic);
  }

  toggleAdvanced(): void {
    this.showAdvanced.update((shown) => !shown);
  }

  cancel(): void {
    this.router.navigate(['/dashboard']);
  }

  createServer(): void {
    if (!this.canCreate) {
      return;
    }

    const currentUser = this.currentUser();
    const currentUserId = localStorage.getItem('metoyou_currentUserId') || currentUser?.id;

    if (!currentUserId) {
      this.router.navigate(['/login'], {
        queryParams: buildLoginReturnQueryParams(this.router.url)
      });

      return;
    }

    setStoredCurrentUserId(currentUserId);

    this.store.dispatch(
      RoomsActions.createRoom({
        name: this.name().trim(),
        description: this.description().trim() || undefined,
        topic: this.topic().trim() || undefined,
        isPrivate: this.isPrivate(),
        password: this.password().trim() || undefined,
        sourceId: this.sourceId || undefined
      })
    );
  }
}
