import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class AuthState {
  final bool isAuthenticated;
  final String? userId;
  final String? email;
  final String? displayName;
  final bool isLoading;

  const AuthState({
    required this.isAuthenticated,
    this.userId,
    this.email,
    this.displayName,
    this.isLoading = false,
  });

  AuthState copyWith({
    bool? isAuthenticated,
    String? userId,
    String? email,
    String? displayName,
    bool? isLoading,
  }) {
    return AuthState(
      isAuthenticated: isAuthenticated ?? this.isAuthenticated,
      userId: userId ?? this.userId,
      email: email ?? this.email,
      displayName: displayName ?? this.displayName,
      isLoading: isLoading ?? this.isLoading,
    );
  }
}

class AuthNotifier extends StateNotifier<AuthState> {
  AuthNotifier() : super(const AuthState(isAuthenticated: false));

  Future<void> login(String email, String password) async {
    state = state.copyWith(isLoading: true);
    
    try {
      // TODO: 實現實際的登入邏輯
      await Future.delayed(const Duration(seconds: 1));
      
      state = state.copyWith(
        isAuthenticated: true,
        userId: 'user_123',
        email: email,
        displayName: email.split('@').first,
        isLoading: false,
      );
    } catch (e) {
      state = state.copyWith(isLoading: false);
      rethrow;
    }
  }

  Future<void> register(String email, String password, String displayName) async {
    state = state.copyWith(isLoading: true);
    
    try {
      // TODO: 實現實際的註冊邏輯
      await Future.delayed(const Duration(seconds: 1));
      
      state = state.copyWith(
        isAuthenticated: true,
        userId: 'user_${DateTime.now().millisecondsSinceEpoch}',
        email: email,
        displayName: displayName,
        isLoading: false,
      );
    } catch (e) {
      state = state.copyWith(isLoading: false);
      rethrow;
    }
  }

  Future<void> logout() async {
    state = const AuthState(isAuthenticated: false);
  }

  void checkAuthStatus() {
    // TODO: 檢查本地儲存的登入狀態
    // 暫時保持未登入狀態供展示
  }
}

final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
  return AuthNotifier();
});