import { Component, inject, TemplateRef, viewChild } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';

import { ModalDismissReasons, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Select2Module } from 'ng-select2-component';
import { Observable } from 'rxjs';

import { UpdateUserProfileAction } from '../../../../action/account.action';
import * as data from '../../../../data/country-code';
import { IAccountUser } from '../../../../interface/account.interface';
import { AccountState } from '../../../../state/account.state';
import { Button } from '../../button/button';

@Component({
  selector: 'app-edit-profile-modal',
  imports: [TranslateModule, ReactiveFormsModule, Select2Module, Button],
  templateUrl: './edit-profile-modal.html',
  styleUrl: './edit-profile-modal.scss',
})
export class EditProfileModal {
  private modalService = inject(NgbModal);
  private store = inject(Store);
  private formBuilder = inject(FormBuilder);

  user$: Observable<IAccountUser> = inject(Store).select(
    AccountState.user,
  ) as Observable<IAccountUser>;

  public form: FormGroup;
  public closeResult: string;

  public modalOpen: boolean = false;
  public flicker: boolean = false;
  public codes = data.countryCodes;

  readonly ProfileModal = viewChild<TemplateRef<string>>('profileModal');

  constructor() {
    this.user$.subscribe(user => {
      this.flicker = true;
      this.form = this.formBuilder.group({
        name: new FormControl(user?.name, [Validators.required]),
        email: new FormControl(user?.email, [Validators.required, Validators.email]),
        phone: new FormControl(user?.phone, [Validators.required, Validators.pattern(/^[0-9]*$/)]),
        country_code: new FormControl(user?.country_code),
        profile_image_id: new FormControl(user?.profile_image_id),
        _method: new FormControl('PUT'),
      });
      setTimeout(() => (this.flicker = false), 200);
    });
  }

  async openModal() {
    this.modalOpen = true;
    this.modalService
      .open(this.ProfileModal(), {
        ariaLabelledBy: 'profile-Modal',
        centered: true,
        windowClass: 'theme-modal profile-modal',
      })
      .result.then(
        result => {
          `Result ${result}`;
        },
        reason => {
          this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        },
      );
  }

  private getDismissReason(reason: ModalDismissReasons): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }

  submit() {
    this.form.markAllAsTouched();
    if (this.form.valid) {
      this.store.dispatch(new UpdateUserProfileAction(this.form.value));
    }
  }

  ngOnDestroy() {
    if (this.modalOpen) {
      this.modalService.dismissAll();
    }
  }
}
