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 { UpdateUserMutation } from 'src/app/graphql/mutations/auth/updateUser.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-user',
  templateUrl: './update-user.page.html',
  styleUrls: ['./update-user.page.scss'],
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    RouterLink,
    IonHeader,
    IonToolbar,
    IonTitle,
    IonContent,
    IonButton,
    IonInput,
    IonItem,
    IonLabel,
    IonText,
    IonButtons,
    IonBackButton
  ]
})
export class UpdateUserPage extends BaseGraphQLPage implements OnInit {
  updateUserForm: FormGroup;
  isSubmitted = false;
  backendErrors: string[] = [];

  constructor(
    private formBuilder: FormBuilder,
    private router: Router
  ) {
    super();
    this.updateUserForm = this.formBuilder.group({
      firstName: ['', [Validators.required]],
      lastName: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.email]],
      phoneNumber: ['', [Validators.required]]
    });
  }

  ngOnInit() {
    // Load current user data
    // This would typically come from a user service or state management
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}');
    if (currentUser) {
      this.updateUserForm.patchValue({
        firstName: currentUser.firstName || '',
        lastName: currentUser.lastName || '',
        email: currentUser.email || '',
        phoneNumber: currentUser.phoneNumber || ''
      });
    }
  }

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

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

    if (this.updateUserForm.valid) {
      const userData = this.updateUserForm.value;
      
      this.executeMutation({
        mutation: UpdateUserMutation,
        variables: {
          firstName: userData.firstName,
          lastName: userData.lastName,
          email: userData.email,
          phoneNumber: userData.phoneNumber
        },
        responsePath: 'updateUser',
        successMessage: 'Profile updated successfully!',
        errorMessage: 'Profile update failed. Please try again.',
        onSuccess: (response: any) => {
          // Update user in localStorage if needed
          const currentUser = JSON.parse(localStorage.getItem('user') || '{}');
          const updatedUser = { ...currentUser, ...userData };
          localStorage.setItem('user', JSON.stringify(updatedUser));
          
          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['email']) return 'Please enter a valid email';

    return '';
  }
} 