import {
  Component,
  DestroyRef,
  computed,
  effect,
  inject,
  signal
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { Store } from '@ngrx/store';
import { NgIcon, provideIcons } from '@ng-icons/core';
import {
  lucideCheck,
  lucideChevronDown,
  lucideGamepad2
} from '@ng-icons/lucide';
import { UserAvatarComponent } from '../user-avatar/user-avatar.component';
import { ProfileSignalServerTagComponent } from './profile-signal-server-tag.component';
import { UserStatusService } from '../../../core/services/user-status.service';
import {
  GameActivity,
  User,
  UserStatus
} from '../../../shared-kernel';
import {
  EditableProfileAvatarSource,
  ProfileAvatarFacade,
  ProfileAvatarEditorService,
  PROFILE_AVATAR_ACCEPT_ATTRIBUTE,
  ProcessedProfileAvatar
} from '../../../domains/profile-avatar';
import { UsersActions } from '../../../store/users/users.actions';
import { selectUsersEntities } from '../../../store/users/users.selectors';
import { ThemeNodeDirective } from '../../../domains/theme';
import { formatGameActivityElapsed } from '../../../domains/game-activity';
import { ExternalLinkService } from '../../../core/platform/external-link.service';
import { AppI18nService, APP_TRANSLATE_IMPORTS } from '../../../core/i18n';
import {
  AutoFocusDirective,
  SelectOnFocusDirective,
  SubmitOnEnterDirective
} from '../../directives';
import { visibilityAwareInterval$ } from '../../rxjs';
import { ServerDirectoryFacade } from '../../../domains/server-directory';
import { resolveUserHomeSignalServerTag } from '../../../domains/server-directory/domain/logic/signal-server-tag.rules';

@Component({
  selector: 'app-profile-card',
  standalone: true,
  imports: [
    CommonModule,
    NgIcon,
    UserAvatarComponent,
    ProfileSignalServerTagComponent,
    ThemeNodeDirective,
    AutoFocusDirective,
    SelectOnFocusDirective,
    SubmitOnEnterDirective,
    ...APP_TRANSLATE_IMPORTS
  ],
  viewProviders: [provideIcons({ lucideCheck, lucideChevronDown, lucideGamepad2 })],
  templateUrl: './profile-card.component.html'
})
export class ProfileCardComponent {
  readonly user = signal<User>({ id: '', oderId: '', username: '', displayName: '', status: 'offline', role: 'member', joinedAt: 0 });
  readonly displayedUser = computed(() => {
    const snapshot = this.user();
    const entities = this.users();
    const liveUser = entities[snapshot.id] ?? entities[snapshot.oderId];

    return liveUser ? { ...snapshot, ...liveUser } : snapshot;
  });
  readonly signalServerTag = computed(() =>
    resolveUserHomeSignalServerTag(
      this.displayedUser().homeSignalServerUrl,
      this.serverDirectory.servers()
    )
  );
  readonly editable = signal(false);
  readonly showStatusMenu = signal(false);
  readonly avatarAccept = PROFILE_AVATAR_ACCEPT_ATTRIBUTE;
  readonly avatarError = signal<string | null>(null);
  readonly avatarSaving = signal(false);
  readonly editingField = signal<'displayName' | 'description' | null>(null);
  readonly displayNameDraft = signal('');
  readonly descriptionDraft = signal('');
  readonly activityNow = signal(Date.now());

  readonly statusOptions = computed(() => [
    { value: null as UserStatus | null, label: this.appI18n.instant('profile.card.status.online'), color: 'bg-green-500' },
    { value: 'away' as const, label: this.appI18n.instant('profile.card.status.away'), color: 'bg-yellow-500' },
    { value: 'busy' as const, label: this.appI18n.instant('profile.card.status.busy'), color: 'bg-red-500' },
    { value: 'offline' as const, label: this.appI18n.instant('profile.card.status.offline'), color: 'bg-gray-500' }
  ]);

  private readonly store = inject(Store);
  private readonly serverDirectory = inject(ServerDirectoryFacade);
  private readonly users = this.store.selectSignal(selectUsersEntities);
  private readonly userStatus = inject(UserStatusService);
  private readonly profileAvatar = inject(ProfileAvatarFacade);
  private readonly profileAvatarEditor = inject(ProfileAvatarEditorService);
  private readonly externalLinks = inject(ExternalLinkService);
  private readonly appI18n = inject(AppI18nService);
  private readonly destroyRef = inject(DestroyRef);
  private readonly activityTimerSub = visibilityAwareInterval$(1_000)
    .pipe(takeUntilDestroyed(this.destroyRef))
    .subscribe(() => this.activityNow.set(Date.now()));
  private readonly syncProfileDrafts = effect(
    () => {
      const user = this.displayedUser();
      const editingField = this.editingField();

      if (editingField !== 'displayName') {
        this.displayNameDraft.set(user.displayName || '');
      }

      if (editingField !== 'description') {
        this.descriptionDraft.set(user.description || '');
      }
    },
    { allowSignalWrites: true }
  );

  currentStatusColor(): string {
    switch (this.displayedUser().status) {
      case 'online':
        return 'bg-green-500';
      case 'away':
        return 'bg-yellow-500';
      case 'busy':
        return 'bg-red-500';
      case 'offline':
        return 'bg-gray-500';
      case 'disconnected':
        return 'bg-gray-500';
      default:
        return 'bg-green-500';
    }
  }

  currentStatusLabel(): string {
    switch (this.displayedUser().status) {
      case 'online':
        return this.appI18n.instant('profile.card.status.online');
      case 'away':
        return this.appI18n.instant('profile.card.status.away');
      case 'busy':
        return this.appI18n.instant('profile.card.status.busy');
      case 'offline':
        return this.appI18n.instant('profile.card.status.offline');
      case 'disconnected':
        return this.appI18n.instant('profile.card.status.disconnected');
      default:
        return this.appI18n.instant('profile.card.status.online');
    }
  }

  gameActivityElapsed(): string {
    const activity = this.displayedUser().gameActivity;

    return activity ? formatGameActivityElapsed(activity.startedAt, this.activityNow()) : '';
  }

  openGameStore(activity: GameActivity, event: Event): void {
    event.stopPropagation();

    if (activity.store?.url) {
      this.externalLinks.open(activity.store.url);
    }
  }

  toggleStatusMenu(): void {
    this.showStatusMenu.update((isOpen) => !isOpen);
  }

  setStatus(status: UserStatus | null): void {
    this.userStatus.setManualStatus(status);
    this.showStatusMenu.set(false);
  }

  isStatusOptionSelected(status: UserStatus | null): boolean {
    const currentStatus = this.displayedUser().status;

    return status === null ? currentStatus === 'online' : currentStatus === status;
  }

  onDisplayNameInput(event: Event): void {
    this.displayNameDraft.set((event.target as HTMLInputElement).value);
  }

  onDescriptionInput(event: Event): void {
    this.descriptionDraft.set((event.target as HTMLTextAreaElement).value);
  }

  startEdit(field: 'displayName' | 'description'): void {
    if (!this.editable() || this.editingField() === field) {
      return;
    }

    this.editingField.set(field);
  }

  finishEdit(field: 'displayName' | 'description'): void {
    if (this.editingField() !== field) {
      return;
    }

    this.commitProfileDrafts();
    this.editingField.set(null);
  }

  pickAvatar(fileInput: HTMLInputElement): void {
    if (!this.editable() || this.avatarSaving()) {
      return;
    }

    this.avatarError.set(null);
    fileInput.click();
  }

  async onAvatarSelected(event: Event): Promise<void> {
    const input = event.target as HTMLInputElement;
    const file = input.files?.[0];

    let source: EditableProfileAvatarSource | null = null;

    input.value = '';

    if (!file) {
      return;
    }

    const validationError = this.profileAvatar.validateFile(file);

    if (validationError) {
      this.avatarError.set(validationError);
      return;
    }

    try {
      source = await this.profileAvatar.prepareEditableSource(file);
      const avatar = await this.profileAvatarEditor.open(source);

      if (!avatar) {
        return;
      }

      await this.applyAvatar(avatar);
    } catch {
      this.avatarError.set(this.appI18n.instant('profile.card.openImageFailed'));
    } finally {
      this.profileAvatar.releaseEditableSource(source);
    }
  }

  async applyAvatar(avatar: ProcessedProfileAvatar): Promise<void> {
    const currentUser = this.displayedUser();

    this.avatarSaving.set(true);
    this.avatarError.set(null);

    try {
      await this.profileAvatar.persistProcessedAvatar(currentUser, avatar);

      const updates = this.profileAvatar.buildAvatarUpdates(avatar);

      this.store.dispatch(UsersActions.updateCurrentUserAvatar({ avatar: updates }));
      this.user.update((user) => ({
        ...user,
        ...updates
      }));
    } catch {
      this.avatarError.set(this.appI18n.instant('profile.card.saveImageFailed'));
    } finally {
      this.avatarSaving.set(false);
    }
  }

  private commitProfileDrafts(): void {
    if (!this.editable()) {
      return;
    }

    const displayName = this.normalizeDisplayName(this.displayNameDraft());

    if (!displayName) {
      this.displayNameDraft.set(this.user().displayName || '');
      return;
    }

    const user = this.displayedUser();
    const description = this.normalizeDescription(this.descriptionDraft());

    if (displayName === this.normalizeDisplayName(user.displayName) && description === this.normalizeDescription(user.description)) {
      return;
    }

    const profile = {
      displayName,
      description,
      profileUpdatedAt: Date.now()
    };

    this.store.dispatch(UsersActions.updateCurrentUserProfile({ profile }));
    this.user.update((user) => ({
      ...user,
      ...profile
    }));
  }

  private normalizeDisplayName(value: string | undefined): string {
    return value?.trim().replace(/\s+/g, ' ') || '';
  }

  private normalizeDescription(value: string | undefined): string | undefined {
    const normalized = value?.trim();

    return normalized || undefined;
  }
}
