import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { UserService } from 'src/app/services/user.service';
import { environment } from '../../../environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-first-password',
  templateUrl: './first-password.page.html',
  styleUrls: ['./first-password.page.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FirstPasswordPageComponent implements OnInit {
  form: FormGroup;
  isLoading = false;
  errorMessage = '';
  submitted = false;
  hideNew = true;
  hideConfirm = true;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private http: HttpClient,
    private cdr: ChangeDetectorRef,
  ) {
    this.form = this.fb.group({
      new_password: ['', [
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(6),
        Validators.pattern(/^[0-9]{6}$/)
      ]],
      confirm_password: ['', [Validators.required]],
    });
  }

  ngOnInit(): void {
    // Verifier que l'utilisateur doit changer son mot de passe
    const mustChange = sessionStorage.getItem('__must_change_password');
    if (mustChange !== 'true') {
      this.router.navigate(['/login']);
    }
  }

  get f() {
    return this.form.controls;
  }

  get passwordsMatch(): boolean {
    return this.form.get('new_password')?.value === this.form.get('confirm_password')?.value;
  }

  async submitNewPassword(): Promise<void> {
    this.submitted = true;
    this.errorMessage = '';

    if (this.form.invalid || !this.passwordsMatch || this.isLoading) {
      if (!this.passwordsMatch) {
        this.errorMessage = 'Les mots de passe ne correspondent pas.';
        this.cdr.markForCheck();
      }
      return;
    }

    this.isLoading = true;
    this.cdr.markForCheck();

    try {
      const oldPassword = sessionStorage.getItem('__temp_password') || '';
      const phoneNumber = sessionStorage.getItem('__temp_phone') || '';
      const newPassword = this.form.get('new_password')?.value;

      const headers = new HttpHeaders({
        'Content-Type': 'application/json',
        'X-API-KEY': environment.AUTH_APY_KEY,
        'Authorization': `Bearer ${this.getAccessToken()}`,
      });

      const response: any = await this.http.put(
        `${environment.AUTH_URL}user/change-password`,
        {
          phone_number: phoneNumber,
          old_password: oldPassword,
          new_password: newPassword,
          confirm_password: newPassword,
        },
        { headers }
      ).toPromise();

      if (response && response.success) {
        // Nettoyer les donnees temporaires
        sessionStorage.removeItem('__must_change_password');
        sessionStorage.removeItem('__temp_password');
        sessionStorage.removeItem('__temp_phone');

        // Rediriger vers le dashboard
        this.router.navigate(['/admin/dashboard/reporting']);
      } else {
        this.errorMessage = response?.message || 'Erreur lors du changement de mot de passe.';
      }
    } catch (error: any) {
      console.error('Erreur changement mot de passe:', error);
      this.errorMessage = error?.error?.message || 'Une erreur est survenue. Veuillez reessayer.';
    } finally {
      this.isLoading = false;
      this.cdr.markForCheck();
    }
  }

  private getAccessToken(): string {
    try {
      const tokenData = localStorage.getItem('__token');
      if (tokenData) {
        const parsed = JSON.parse(tokenData);
        return parsed.accessToken || parsed.token || '';
      }
    } catch {}
    return '';
  }

  toggleNewVisibility(): void {
    this.hideNew = !this.hideNew;
    this.cdr.markForCheck();
  }

  toggleConfirmVisibility(): void {
    this.hideConfirm = !this.hideConfirm;
    this.cdr.markForCheck();
  }
}
