import { Component, OnDestroy, OnInit } from '@angular/core';
import { UserService } from '../../user.service';
import { Subscription } from 'rxjs';
import { User } from '../../../auth/model/user.model';
import { ProfilePhotoUploadService } from './profile-photo-upload.service';
import { AngularMaterialModule } from '../../../angular-material/angular-material.module';
import { CommonModule } from '@angular/common';
import { NotifierService } from '../../../shared/notifierService/notifier.service';

@Component({
  selector: 'app-profile-photo-upload',
  standalone: true,
  imports: [AngularMaterialModule, CommonModule],
  templateUrl: './profile-photo-upload.component.html',
  styleUrls: ['./profile-photo-upload.component.css'],
})
export class ProfilePhotoUploadComponent implements OnInit, OnDestroy {
  //TODO check why the userId remains empty/null in component, but in service the uid is returned proper?
  userProfileSubscription!: Subscription;
  currentUser: User | null = null;
  fileSelected: boolean = false;
  metadata = {
    contentType: 'image/jpeg',
    customMetadata: {
      imgId: undefined,
    },
  };
  selectedFile: File | null = null;

  constructor(
    private userService: UserService,
    private profilePhotoUploadService: ProfilePhotoUploadService,
    private notifierService: NotifierService
  ) {}

  ngOnInit(): void {
    this.userProfileSubscription =
      this.userService.currentUserProfile$.subscribe((user: User | null) => {
        this.currentUser = user;
      });
  }

  ngOnDestroy(): void {
    if (this.userProfileSubscription) {
      this.userProfileSubscription.unsubscribe();
    }
  }

  onFileSelected(event: any) {
    this.selectedFile = event.target.files[0];
    this.fileSelected = true;
    this.notifierService.showNotification(
      `Datei wurde ausgewählt. Bitte klicke auf die Schaltfläche "Hochladen", um Bild einzustellen.`,
      'OK'
    );
  }

  async uploadFile() {
    if (this.selectedFile && this.currentUser && this.currentUser.uid) {
      const file = this.selectedFile;
      const metadata = {
        contentType: 'image/jpeg',
        customMetadata: {
          imgId: this.currentUser?.uid,
        },
      };
      await this.profilePhotoUploadService.uploadFile(
        this.currentUser.uid,
        file,
        metadata
      );
      this.notifierService.showNotification(`Datei wurde hochgeladen`, 'OK');
    } else {
      this.notifierService.showInformation(
        'Keine Datei ausgewählt oder Benutzer-ID ist unbekannt.'
      );
    }
  }

  async deleteFile() {
    if (this.currentUser && this.currentUser.uid) {
      await this.profilePhotoUploadService.deleteFile(this.currentUser.uid);
      this.notifierService.showNotification(`Datei wurde gelöscht`, 'OK');
    } else {
      this.notifierService.showInformation('Benutzer-ID ist unbekannt. Bitte melde dich an, um die Datei zu löschen.');
    }
  }
}
