import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { CharacterService } from '../services/character.service';
import { LoadingController } from '@ionic/angular';

@Component({
  selector: 'app-character-creator',
  templateUrl: './character-creator.page.html',
  styleUrls: ['./character-creator.page.scss'],
  standalone: true,
  imports: [CommonModule, IonicModule, FormsModule, ReactiveFormsModule]
})
export class CharacterCreatorPage {
  characterForm!: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private router: Router,
    private characterService: CharacterService,
    private loadingController: LoadingController
  ) {
    this.initForm();
  }

  private initForm() {
    this.characterForm = this.formBuilder.group({
      name: ['', Validators.required],
      gender: ['male', Validators.required],
      appearance: ['', [Validators.required, Validators.minLength(20)]],
      personality: ['', [Validators.required, Validators.minLength(20)]]
    });
  }

  async generateCharacter() {
    if (this.characterForm.valid) {
      const loading = await this.loadingController.create({
        message: '正在生成角色...'
      });
      await loading.present();

      try {
        const characterData = this.characterForm.value;
        const avatar = await this.characterService
          .generateCharacterAvatar(characterData.appearance)
          .toPromise();

        const character = await this.characterService.createCharacterAgent({
          ...characterData,
          avatar,
          id: Date.now().toString()
        }).toPromise();

        await loading.dismiss();
        this.router.navigate(['/character']);
      } catch (error) {
        console.error('Error generating character:', error);
        await loading.dismiss();
      }
    }
  }
} 
