import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { UpdatePasswordMutation } from 'src/app/graphql/mutations/auth/updatePassword.mutation';
import { Router } from '@angular/router';
import { BaseGraphQLPage } from 'src/app/shared/base/base-graphql.page';
import {
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonButton,
  IonInput,
  IonItem,
  IonLabel,
  IonText,
  IonButtons,
  IonBackButton,
} from '@ionic/angular/standalone';

@Component({
  selector: 'app-update-password',
  templateUrl: './update-password.page.html',
  styleUrls: ['./update-password.page.scss'],
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    RouterLink,
    IonHeader,
    IonToolbar,
    IonTitle,
    IonContent,
    IonButton,
    IonInput,
    IonItem,
    IonLabel,
    IonText,
    IonButtons,
    IonBackButton
  ]
})
export class UpdatePasswordPage extends BaseGraphQLPage implements OnInit {
  updatePasswordForm: FormGroup;
  isSubmitted = false;
  backendErrors: string[] = [];

  constructor(
    private formBuilder: FormBuilder,
    private router: Router
  ) {
    super();
    this.updatePasswordForm = this.formBuilder.group({
      currentPassword: ['', [Validators.required]],
      newPassword: ['', [Validators.required, Validators.minLength(8)]],
      confirmPassword: ['', [Validators.required]]
    }, { 
      validators: this.passwordMatchValidator 
    });
  }

  ngOnInit() {}

  // Custom validator to check if passwords match
  passwordMatchValidator(form: FormGroup) {
    const newPassword = form.get('newPassword')?.value;
    const confirmPassword = form.get('confirmPassword')?.value;
    
    if (newPassword !== confirmPassword) {
      form.get('confirmPassword')?.setErrors({ passwordMismatch: true });
      return { passwordMismatch: true };
    }
    
    return null;
  }

  // Getter for easy access to form fields in the template
  get f() {
    return this.updatePasswordForm.controls;
  }

  async onSubmit() {
    this.isSubmitted = true;
    this.backendErrors = [];

    if (this.updatePasswordForm.valid) {
      const passwordData = this.updatePasswordForm.value;
      
      this.executeMutation({
        mutation: UpdatePasswordMutation,
        variables: {
          currentPassword: passwordData.currentPassword,
          newPassword: passwordData.newPassword
        },
        responsePath: 'updatePassword',
        successMessage: 'Password updated successfully!',
        errorMessage: 'Password update failed. Please try again.',
        onSuccess: (response: any) => {
          this.router.navigate(['/profile']);
        },
        onError: (error) => this.backendErrors = this.errorService.errors
      });
    }
  }

  // Helper method to get error message
  getErrorMessage(control: string): string {
    if (!this.isSubmitted) return '';

    const formControl = this.f[control];
    if (!formControl || !formControl.errors) return '';

    if (formControl.errors['required']) return `${control} is required`;
    if (formControl.errors['minlength']) return 'Password must be at least 8 characters';
    if (formControl.errors['passwordMismatch']) return 'Passwords do not match';

    return '';
  }
} 