import {Component, inject, OnInit, signal} from '@angular/core';
import {TuiAppearance, TuiButton, TuiError, TuiErrorDirective, TuiIcon, TuiInput, TuiTextfield} from '@taiga-ui/core';
import {TranslatePipe} from '@ngx-translate/core';
import {TuiButtonGroup, TuiPassword} from '@taiga-ui/kit';
import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {AuthService} from '@chatenium/chatenium-sdk/services/authService';
import {AuthMethods} from '@chatenium/chatenium-sdk/domain/authService.schema';
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
import {ServiceManager} from '../service-manager';
import {IndexedDB} from '../storage/indexed-db';
import {PublicUserData} from '@chatenium/chatenium-sdk/domain/common.schema';
import {Router} from '@angular/router';

@Component({
  selector: 'app-signin',
  imports: [
    TuiAppearance,
    TranslatePipe,
    TuiTextfield,
    TuiInput,
    TuiButton,
    TuiButtonGroup,
    TuiPassword,
    TuiIcon,
    ReactiveFormsModule,
    TuiErrorDirective,
    TuiError
  ],
  templateUrl: './signin.html',
  styleUrl: './signin.scss',
})
export class SignIn implements OnInit {
  indexedDb = inject(IndexedDB)
  router = inject(Router)

  service = new AuthService()
  serviceManager = new ServiceManager()
  methods = signal<AuthMethods>({sms: false, email: false, password: false})

  private clickEvent = signal(0)

  signInForm = new FormGroup({
    unameMailPhone: new FormControl('', {
      validators: [Validators.required]
    }),
    password: new FormControl('', {
      validators: [Validators.required]
    })
  })

  timeoutId: any;

  async checkAuthMethods(unameMailPhone: string | null) {
    console.log("Called")
    clearTimeout(this.timeoutId);

    this.timeoutId = setTimeout(async () => {
      this.methods.set({sms: false, password: false, email: false})
      this.methods.set(await this.service.getAuthMethods(unameMailPhone ?? ""))
    }, 500)
  }

  async passwordSignIn(unameMailPhone: string | null, password: string | null) {
    try {
      const resp = await this.service.loginPasswordAuth(unameMailPhone ?? "", password ?? "")
      this.serviceManager.sessionManager.addSession(<PublicUserData>{
        pfp: resp.pfp,
        userid: resp.userid,
        username: resp.username,
        displayName: resp.displayName,
      }, resp.token)
      console.log("Logged in")
      this.router.navigate(["/chat"])
    } catch (e) {
      console.error(e)
      this.signInForm.controls['password'].setErrors({incorrect: true})
    }
  }

  ngOnInit() {
    this.indexedDb.openDatabase()
  }
}
