import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { Router } from '@angular/router';

import { TranslateModule } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { UpdatePasswordAction } from '../../../shared/action/auth.action';
import { Alert } from '../../../shared/components/widgets/alert/alert';
import { Breadcrumb } from '../../../shared/components/widgets/breadcrumb/breadcrumb';
import { Button } from '../../../shared/components/widgets/button/button';
import { IBreadcrumb } from '../../../shared/interface/breadcrumb';
import { IValues } from '../../../shared/interface/setting.interface';
import { SettingState } from '../../../shared/state/setting.state';

@Component({
  selector: 'app-update-password',
  imports: [CommonModule, TranslateModule, ReactiveFormsModule, Breadcrumb, Alert, Button],
  templateUrl: './update-password.html',
  styleUrl: './update-password.scss',
})
export class UpdatePassword {
  public router = inject(Router);
  private store = inject(Store);
  private formBuilder = inject(FormBuilder);

  setting$: Observable<IValues> = inject(Store).select(SettingState.setting) as Observable<IValues>;

  public form: FormGroup;
  public email: string;
  public token: any;
  public breadcrumb: IBreadcrumb = {
    title: 'Reset Password',
    items: [{ label: 'Reset Password', active: true }],
  };

  constructor() {
    this.email = this.store.selectSnapshot(state => state.auth.email);
    this.token = this.store.selectSnapshot(state => state.auth.token);
    if (!this.email && !this.token) void this.router.navigateByUrl('/auth/login');
    this.form = this.formBuilder.group({
      newPassword: new FormControl('', [Validators.required]),
      confirmPassword: new FormControl('', [Validators.required]),
    });
  }

  submit() {
    this.form.markAllAsTouched();
    if (this.form.valid) {
      this.store
        .dispatch(
          new UpdatePasswordAction({
            email: this.email,
            token: this.token,
            password: this.form.value.newPassword,
            password_confirmation: this.form.value.confirmPassword,
          }),
        )
        .subscribe({
          complete: () => {
            void this.router.navigateByUrl('/auth/login');
          },
        });
    }
  }
}
