import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import {
  IonAvatar, IonBackButton, IonButton, IonButtons, IonContent, IonHeader, IonIcon,
  IonItem, IonLabel, IonList, IonTitle, IonToolbar, ToastController, AlertController, IonCard, IonCardHeader, IonCardTitle
} from '@ionic/angular/standalone';
import { UserService } from '../services/user.service';
import { ActionSheetController } from '@ionic/angular';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';

interface User {
  username: string;
  avatar: string;
}

@Component({
  selector: 'app-person',
  templateUrl: './person.page.html',
  styleUrls: ['./person.page.scss'],
  standalone: true,
  imports: [IonContent, IonHeader, IonToolbar, CommonModule, FormsModule,
    IonAvatar, IonList, IonItem, IonLabel, IonButtons, IonCard, IonIcon, IonTitle, IonButton, IonCardHeader, IonCardTitle]
})
export class PersonPage implements OnInit {
  isLoggedIn: boolean = false;
  user: User = {
    username: 'User_123456',
    avatar: 'assets/default-avatar.png'
  };

  @ViewChild('fileInput') fileInput!: ElementRef;

  constructor(
    private router: Router,
    private alertController: AlertController,
    private actionSheetController: ActionSheetController,
    private userService: UserService
  ) { }

  ngOnInit() {
    this.checkLoginStatus();
    this.subscribeToUserChanges();
  }

  subscribeToUserChanges() {
    this.userService.currentUser$.subscribe(user => {
      if (user) {
        this.user = user;
      }
    });
  }

  checkLoginStatus() {
    this.userService.isLoggedIn$.subscribe(
      isLoggedIn => {
        this.isLoggedIn = isLoggedIn;
        if (isLoggedIn) {
          // 获取用户信息
          this.userService.getCurrentUser().subscribe(user => {
            if (user) {
              this.user = user;
            }
          });
        }
      }
    );
  }

  async changeAvatar() {
    try {
      const actionSheet = await this.actionSheetController.create({
        header: '选择头像',
        buttons: [
          {
            text: '拍照',
            icon: 'camera',
            handler: () => {
              this.takePicture('camera');
            }
          },
          {
            text: '从相册选择',
            icon: 'image',
            handler: () => {
              this.takePicture('photos');
            }
          },
          {
            text: '从电脑选择',
            icon: 'desktop',
            handler: () => {
              this.fileInput.nativeElement.click();
            }
          },
          {
            text: '取消',
            icon: 'close',
            role: 'cancel'
          }
        ]
      });
      await actionSheet.present();
    } catch (error) {
      console.error('Error showing action sheet:', error);
      this.showAlert('错误', '无法打开选择菜单');
    }
  }

  private async takePicture(sourceType: 'camera' | 'photos') {
    try {
      const image = await Camera.getPhoto({
        quality: 90,
        allowEditing: true,
        resultType: CameraResultType.DataUrl,
        source: sourceType === 'camera' ? CameraSource.Camera : CameraSource.Photos
      });

      if (image && image.dataUrl) {
        // 先更新本地显示
        this.user.avatar = image.dataUrl;

        // 然后保存到服务
        this.userService.updateAvatar(image.dataUrl).subscribe(
          response => {
            if (response.success) {
              this.showAlert('成功', '头像更新成功');
            } else {
              // 如果更新失败，恢复原来的头像
              this.userService.getCurrentUser().subscribe(user => {
                if (user) {
                  this.user.avatar = user.avatar;
                }
              });
              this.showAlert('错误', '头像更新失败');
            }
          },
          error => {
            console.error('Error updating avatar:', error);
            this.showAlert('错误', '头像更新失败');
          }
        );
      }
    } catch (error) {
      console.error('Error taking photo:', error);
      this.showAlert('错误', '获取图片失败');
    }
  }

  async changePassword() {
    const alert = await this.alertController.create({
      header: '修改密码',
      inputs: [
        {
          name: 'oldPassword',
          type: 'password',
          placeholder: '请输入原密码'
        },
        {
          name: 'newPassword',
          type: 'password',
          placeholder: '请输入新密码'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确定',
          handler: (data) => {
            this.userService.changePassword(data.oldPassword, data.newPassword).subscribe(
              response => {
                if (response.success) {
                  this.showAlert('成功', '密码修改成功');
                } else {
                  this.showAlert('错误', response.message || '密码修改失败');
                }
              }
            );
          }
        }
      ]
    });
    await alert.present();
  }

  async switchAccount() {
    const alert = await this.alertController.create({
      header: '切换账号',
      inputs: [
        {
          name: 'phone',
          type: 'tel',
          placeholder: '请输入手机号'
        },
        {
          name: 'password',
          type: 'password',
          placeholder: '请输入密码'
        }
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确定',
          handler: (data) => {
            this.userService.switchAccount(data).subscribe(
              response => {
                if (response.success) {
                  this.showAlert('成功', '账号切换成功');
                  this.checkLoginStatus();
                } else {
                  this.showAlert('错误', '账号或密码错误');
                }
              }
            );
          }
        }
      ]
    });
    await alert.present();
  }

  async showLogoutConfirm() {
    const alert = await this.alertController.create({
      header: '确认注销账号',
      message: '您确定要注销账号吗？此操作不可逆',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确定',
          handler: () => {
            this.userService.deleteAccount().subscribe(
              response => {
                if (response.success) {
                  this.userService.logout();
                  this.router.navigate(['/login']);
                }
              }
            );
          }
        }
      ]
    });
    await alert.present();
  }

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

  goToCreativeCenter() {
    this.router.navigate(['/tabs/home']);
  }

  goToLogin() {
    this.router.navigate(['/login']);
  }

  goToRegister() {
    this.router.navigate(['/register']);
  }

  async uploadAvatarFromFile(event: any) {
    const file = event.target.files[0];
    if (file) {
      try {
        const reader = new FileReader();
        reader.onload = (e: any) => {
          const imageData = e.target.result;
          // 先更新本地显示
          this.user.avatar = imageData;

          // 然后保存到服务
          this.userService.updateAvatar(imageData).subscribe(
            response => {
              if (response.success) {
                this.showAlert('成功', '头像更新成功');
              } else {
                // 如果更新失败，恢复原来的头像
                this.userService.getCurrentUser().subscribe(user => {
                  if (user) {
                    this.user.avatar = user.avatar;
                  }
                });
                this.showAlert('错误', '头像更新失败');
              }
            },
            error => {
              console.error('Error updating avatar:', error);
              this.showAlert('错误', '头像更新失败');
            }
          );
        };
        reader.readAsDataURL(file);
      } catch (error) {
        console.error('Error reading file:', error);
        this.showAlert('错误', '文件读取失败');
      }
    }
  }
} 