import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AbstractControl, FormsModule } from '@angular/forms';
import {Router} from '@angular/router';
import { AlertController, IonBackButton, IonButton, IonButtons, IonContent, IonHeader, IonIcon, IonInput, IonItem, IonLabel, IonList, IonTitle, IonToolbar,ToastController } from '@ionic/angular/standalone';
import { FormBuilder, FormGroup, Validators,ReactiveFormsModule } from '@angular/forms';
import { Camera, CameraResultType } from '@capacitor/camera';
import { UserService } from '../services/user.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
  standalone: true,
  imports: [IonContent, IonHeader, IonTitle, IonToolbar, CommonModule, FormsModule
    ,IonLabel,IonItem,IonInput,IonButton,IonButtons,IonBackButton,IonIcon,ReactiveFormsModule]
})
export class RegisterPage implements OnInit {
  registerForm: FormGroup = this.formBuilder.group({
    username: ['', [Validators.required]],
    phone: ['', [Validators.required, Validators.pattern('^1[3-9]\\d{9}$')]],
    password: ['', [
      Validators.required,
      Validators.pattern('^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$')
    ]]
  });
  
  avatarPreview: string | undefined;

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private userService: UserService,
    private alertController: AlertController
  ) {}

  ngOnInit() {}

  get f(): { [key: string]: AbstractControl } {
    if (!this.registerForm) {
      return {};
    }
    return this.registerForm.controls;
  }

  async uploadAvatar() {
    try {
      const image = await Camera.getPhoto({
        quality: 90,
        allowEditing: true,
        resultType: CameraResultType.DataUrl
      });
      
      if (image && image.dataUrl) {
        this.avatarPreview = image.dataUrl;
      }
    } catch (error) {
      console.error('Error uploading avatar:', error);
    }
  }

  async onSubmit() {
    if (this.registerForm && this.registerForm.valid) {
      try {
        const userData = {
          ...this.registerForm.value,
          avatar: this.avatarPreview || 'assets/default-avatar.png'
        };
        
        this.userService.register(userData).subscribe(
          response => {
            if (response.success) {
              this.router.navigate(['/login']);
            } else {
              this.showAlert('错误', response.message || '注册失败');
            }
          }
        );
      } catch (error) {
        console.error('Registration error:', error);
        this.showAlert('错误', '注册失败');
      }
    }
  }

  private async showAlert(header: string, message: string) {
    const alert = await this.alertController.create({
      header,
      message,
      buttons: ['确定']
    });
    await alert.present();
  }
} 