import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';

import 'package:dartz/dartz.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:injectable/injectable.dart';
import 'package:superport/core/errors/failures.dart';
import 'package:superport/data/datasources/remote/auth_remote_datasource.dart';
import 'package:superport/data/models/auth/auth_user.dart';
import 'package:superport/data/models/auth/login_request.dart';
import 'package:superport/data/models/auth/login_response.dart';
import 'package:superport/data/models/auth/logout_request.dart';
import 'package:superport/data/models/auth/refresh_token_request.dart';
import 'package:superport/data/models/auth/token_response.dart';
import 'package:superport/data/models/auth/change_password_request.dart';
import 'package:superport/data/models/auth/message_response.dart';

abstract class AuthService {
  Future<Either<Failure, LoginResponse>> login(LoginRequest request);
  Future<Either<Failure, void>> logout();
  Future<Either<Failure, TokenResponse>> refreshToken();
  Future<bool> isLoggedIn();
  Future<AuthUser?> getCurrentUser();
  Future<Either<Failure, AuthUser>> getCurrentAdminFromServer();
  Future<Either<Failure, MessageResponse>> changePassword({
    required String oldPassword,
    required String newPassword,
  });
  Future<String?> getAccessToken();
  Future<String?> getRefreshToken();
  Future<void> clearSession();
  Stream<bool> get authStateChanges;
}

@LazySingleton(as: AuthService)
class AuthServiceImpl implements AuthService {
  final AuthRemoteDataSource _authRemoteDataSource;
  final FlutterSecureStorage _secureStorage;
  
  static const String _accessTokenKey = 'access_token';
  static const String _refreshTokenKey = 'refresh_token';
  static const String _userKey = 'user';
  static const String _tokenExpiryKey = 'token_expiry';
  
  final _authStateController = StreamController<bool>.broadcast();
  
  AuthServiceImpl(
    this._authRemoteDataSource,
    this._secureStorage,
  );

  @override
  Future<Either<Failure, LoginResponse>> login(LoginRequest request) async {
    try {
      debugPrint('[AuthService] login 시작');
      
      // API 모드로 로그인 처리
      debugPrint('[AuthService] API 모드로 로그인 처리');
      final result = await _authRemoteDataSource.login(request);
      
      return await result.fold(
        (failure) async => Left(failure),
        (loginResponse) async {
          // 토큰 및 사용자 정보 저장
          await _saveTokens(
            loginResponse.accessToken,
            loginResponse.refreshToken,
            loginResponse.expiresIn,
          );
          await _saveUser(loginResponse.user);
          
          // 인증 상태 변경 알림
          _authStateController.add(true);
          
          return Right(loginResponse);
        },
      );
    } catch (e, stackTrace) {
      debugPrint('[AuthService] login 예외 발생: $e');
      debugPrint('[AuthService] Stack trace: $stackTrace');
      return Left(ServerFailure(message: '로그인 처리 중 오류가 발생했습니다.'));
    }
  }

  @override
  Future<Either<Failure, void>> logout() async {
    try {
      final refreshToken = await getRefreshToken();
      if (refreshToken != null) {
        final request = LogoutRequest(refreshToken: refreshToken);
        await _authRemoteDataSource.logout(request);
      }
      
      await clearSession();
      _authStateController.add(false);
      
      return const Right(null);
    } catch (e) {
      // 로그아웃 API 실패 시에도 로컬 세션은 정리
      await clearSession();
      _authStateController.add(false);
      return const Right(null);
    }
  }

  @override
  Future<Either<Failure, TokenResponse>> refreshToken() async {
    try {
      final refreshToken = await getRefreshToken();
      if (refreshToken == null) {
        return Left(AuthenticationFailure(
          message: '리프레시 토큰이 없습니다. 다시 로그인해주세요.',
        ));
      }
      
      final request = RefreshTokenRequest(refreshToken: refreshToken);
      final result = await _authRemoteDataSource.refreshToken(request);
      
      return await result.fold(
        (failure) async {
          // 토큰 갱신 실패 시 세션 정리
          await clearSession();
          _authStateController.add(false);
          return Left(failure);
        },
        (tokenResponse) async {
          // 새 토큰 저장
          await _saveTokens(
            tokenResponse.accessToken,
            tokenResponse.refreshToken,
            tokenResponse.expiresIn,
          );
          return Right(tokenResponse);
        },
      );
    } catch (e) {
      return Left(ServerFailure(message: '토큰 갱신 중 오류가 발생했습니다.'));
    }
  }

  @override
  Future<bool> isLoggedIn() async {
    try {
      final accessToken = await getAccessToken();
      if (accessToken == null) return false;
      
      // 토큰 만료 확인
      final expiryStr = await _secureStorage.read(key: _tokenExpiryKey);
      if (expiryStr != null) {
        final expiry = DateTime.parse(expiryStr);
        if (DateTime.now().isAfter(expiry)) {
          // 토큰이 만료되었으면 갱신 시도
          final refreshResult = await refreshToken();
          return refreshResult.isRight();
        }
      }
      
      return true;
    } catch (e) {
      return false;
    }
  }

  @override
  Future<AuthUser?> getCurrentUser() async {
    try {
      final userStr = await _secureStorage.read(key: _userKey);
      if (userStr == null) return null;
      
      final userJson = jsonDecode(userStr);
      return AuthUser.fromJson(userJson);
    } catch (e) {
      return null;
    }
  }

  @override
  Future<String?> getAccessToken() async {
    try {
      final token = await _secureStorage.read(key: _accessTokenKey);
      if (token != null && token.length > 20) {
        debugPrint('[AuthService] getAccessToken: Found (${token.substring(0, 20)}...)');
      } else if (token != null) {
        debugPrint('[AuthService] getAccessToken: Found ($token)');
      } else {
        debugPrint('[AuthService] getAccessToken: Not found');
      }
      return token;
    } catch (e) {
      debugPrint('[AuthService] getAccessToken error: $e');
      return null;
    }
  }

  @override
  Future<String?> getRefreshToken() async {
    try {
      return await _secureStorage.read(key: _refreshTokenKey);
    } catch (e) {
      return null;
    }
  }

  @override
  Future<void> clearSession() async {
    try {
      await _secureStorage.delete(key: _accessTokenKey);
      await _secureStorage.delete(key: _refreshTokenKey);
      await _secureStorage.delete(key: _userKey);
      await _secureStorage.delete(key: _tokenExpiryKey);
    } catch (e) {
      // 에러가 발생해도 계속 진행
    }
  }

  @override
  Stream<bool> get authStateChanges => _authStateController.stream;

  Future<void> _saveTokens(
    String accessToken,
    String refreshToken,
    int expiresIn,
  ) async {
    debugPrint('[AuthService] Saving tokens...');
    final accessTokenPreview = accessToken.length > 20 ? '${accessToken.substring(0, 20)}...' : accessToken;
    final refreshTokenPreview = refreshToken.length > 20 ? '${refreshToken.substring(0, 20)}...' : refreshToken;
    debugPrint('[AuthService] Access token: $accessTokenPreview');
    debugPrint('[AuthService] Refresh token: $refreshTokenPreview');
    debugPrint('[AuthService] Expires in: $expiresIn seconds');
    
    await _secureStorage.write(key: _accessTokenKey, value: accessToken);
    await _secureStorage.write(key: _refreshTokenKey, value: refreshToken);
    
    // 토큰 만료 시간 저장 (현재 시간 + expiresIn 초)
    final expiry = DateTime.now().add(Duration(seconds: expiresIn));
    await _secureStorage.write(
      key: _tokenExpiryKey,
      value: expiry.toIso8601String(),
    );
    
    debugPrint('[AuthService] Tokens saved successfully');
  }

  Future<void> _saveUser(AuthUser user) async {
    final userJson = jsonEncode(user.toJson());
    await _secureStorage.write(key: _userKey, value: userJson);
  }

  @override
  Future<Either<Failure, AuthUser>> getCurrentAdminFromServer() async {
    try {
      debugPrint('[AuthService] getCurrentAdminFromServer 시작');
      
      final result = await _authRemoteDataSource.getCurrentAdmin();
      
      return result.fold(
        (failure) {
          debugPrint('[AuthService] getCurrentAdminFromServer 실패: ${failure.message}');
          return Left(failure);
        },
        (authUser) {
          debugPrint('[AuthService] getCurrentAdminFromServer 성공: ${authUser.name} (${authUser.email})');
          return Right(authUser);
        },
      );
    } catch (e, stackTrace) {
      debugPrint('[AuthService] getCurrentAdminFromServer 예외 발생: $e');
      debugPrint('[AuthService] Stack trace: $stackTrace');
      return Left(ServerFailure(message: '관리자 정보 조회 중 오류가 발생했습니다.'));
    }
  }

  @override
  Future<Either<Failure, MessageResponse>> changePassword({
    required String oldPassword,
    required String newPassword,
  }) async {
    try {
      debugPrint('[AuthService] changePassword 시작');
      
      final request = ChangePasswordRequest(
        oldPassword: oldPassword,
        newPassword: newPassword,
      );
      
      final result = await _authRemoteDataSource.changePassword(request);
      
      return result.fold(
        (failure) {
          debugPrint('[AuthService] changePassword 실패: ${failure.message}');
          return Left(failure);
        },
        (messageResponse) {
          debugPrint('[AuthService] changePassword 성공: ${messageResponse.message}');
          return Right(messageResponse);
        },
      );
    } catch (e, stackTrace) {
      debugPrint('[AuthService] changePassword 예외 발생: $e');
      debugPrint('[AuthService] Stack trace: $stackTrace');
      return Left(ServerFailure(message: '비밀번호 변경 중 오류가 발생했습니다.'));
    }
  }

  void dispose() {
    _authStateController.close();
  }
}