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

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

import { LoginWithNumberAction } 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 * as data from '../../../shared/data/country-code';
import { IBreadcrumb } from '../../../shared/interface/breadcrumb';
import { IValues } from '../../../shared/interface/setting.interface';
import { AuthService } from '../../../shared/services/auth.service';
import { SettingState } from '../../../shared/state/setting.state';

@Component({
  selector: 'app-login-with-number',
  imports: [
    CommonModule,
    TranslateModule,
    ReactiveFormsModule,
    Select2Module,
    RouterModule,
    Breadcrumb,
    Button,
    Alert,
  ],
  templateUrl: './login-with-number.html',
  styleUrl: './login-with-number.scss',
})
export class LoginWithNumber {
  private router = inject(Router);
  private store = inject(Store);
  private authService = inject(AuthService);
  private formBuilder = inject(FormBuilder);

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

  public form: FormGroup;
  public codes = data.countryCodes;

  public breadcrumb: IBreadcrumb = {
    title: 'Login With Number',
    items: [{ label: 'Login With Number', active: true }],
  };

  constructor() {
    this.form = this.formBuilder.group({
      phone: new FormControl('', [Validators.required, Validators.pattern(/^[0-9]*$/)]),
      country_code: new FormControl('91', [Validators.required]),
    });
  }

  submit() {
    this.form.markAllAsTouched();
    if (this.form.valid) {
      this.store.dispatch(new LoginWithNumberAction(this.form.value)).subscribe({
        complete: () => {
          this.authService.otpType = 'number';
          void this.router.navigateByUrl('/auth/otp');
        },
      });
    }
  }
}
