import {
  ChangeDetectorRef,
  Component,
  EventEmitter,
  Input,
  OnChanges,
  Output,
  SimpleChanges,
} from '@angular/core';
import { v4 as uuid } from 'uuid';

@Component({
  selector: 'app-upload-avatar',
  templateUrl: './upload-avatar.component.html',
  styleUrls: ['./upload-avatar.component.scss'],
})
export class UploadAvatarComponent implements OnChanges {
  @Input() src: string | File = '';
  @Input() name = '';

  @Output() srcChange = new EventEmitter<File>();

  avatarPreview = '';

  constructor(private cdr: ChangeDetectorRef) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['src']?.currentValue) {
      const src = changes['src'].currentValue as string | File;

      if (src instanceof File) {
        this.avatarPreview = URL.createObjectURL(src);
        return;
      }

      this.avatarPreview = src;
    }

    if (changes['name']?.currentValue) {
      if (!this.src) this.createAvatarWithInitials();
    }
  }

  getInitials(name: string) {
    const nameSplitted = name.split(' ');
    const initials = nameSplitted[0][0] + nameSplitted[1][0];

    return initials.toUpperCase();
  }

  createAvatarWithInitials() {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    const size = 120;
    const initials = this.getInitials(this.name);

    canvas.width = size;
    canvas.height = size;

    if (!context) return;

    context.fillStyle = '#f5f5f5';
    context.fillRect(0, 0, size, size);
    context.font = 'bold 32px Montserrat';

    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.fillStyle = '#363636';
    context.fillText(initials, size / 2, size / 2);

    canvas.toBlob((blob) => {
      if (!blob) return;

      const fileName = `${uuid()}.png`;

      this.src = new File([blob], fileName, { type: 'image/png' });
      this.avatarPreview = URL.createObjectURL(blob);

      this.srcChange.emit(this.src);
      this.cdr.detectChanges();
    });
  }

  handleUploadFile() {
    const input = document.createElement('input');

    input.type = 'file';
    input.accept = 'image/png, image/jpeg, image/jpg';
    input.click();

    input.onchange = (event: Event) => {
      const eventTarget = event.target as HTMLInputElement;
      const file = eventTarget.files?.[0];

      if (!file) return;

      this.src = file as File;
      this.avatarPreview = URL.createObjectURL(file);

      this.srcChange.emit(this.src);
      this.cdr.detectChanges();
    };
  }
}
