import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:go_router/go_router.dart';
import 'package:syncrow_web/pages/auth/model/user_model.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/home/bloc/home_event.dart';
import 'package:syncrow_web/pages/home/bloc/home_state.dart';
import 'package:syncrow_web/pages/home/home_model/home_item_model.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart';
import 'package:syncrow_web/services/home_api.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/constants/routes_const.dart';

class HomeBloc extends Bloc<HomeEvent, HomeState> {
  UserModel? user;
  String terms = '';
  String policy = '';

  HomeBloc() : super(HomeInitial()) {
    on<FetchUserInfo>(_fetchUserInfo);
    on<FetchTermEvent>(_fetchTerms);
    on<FetchPolicyEvent>(_fetchPolicy);
    on<ConfirmUserAgreementEvent>(_confirmUserAgreement);
  }

  Future<void> _fetchUserInfo(
    FetchUserInfo event,
    Emitter<HomeState> emit,
  ) async {
    try {
      final uuid =
          await const FlutterSecureStorage().read(key: UserModel.userUuidKey);
      if (uuid != null) {
        user = await HomeApi().fetchUserInfo(uuid);
      }

      if (user != null && user?.project != null) {
        await ProjectManager.setProjectUUID(user!.project!.uuid);
      }
      add(FetchTermEvent());
      add(FetchPolicyEvent());

      emit(HomeInitial());
    } catch (e) {
      return;
    }
  }

  Future<void> _fetchTerms(FetchTermEvent event, Emitter<HomeState> emit) async {
    try {
      emit(LoadingHome());
      terms = await HomeApi().fetchTerms();
      emit(HomeInitial());
    } catch (e) {
      return;
    }
  }

  Future<void> _fetchPolicy(FetchPolicyEvent event, Emitter<HomeState> emit) async {
    try {
      emit(LoadingHome());
      policy = await HomeApi().fetchPolicy();
      emit(HomeInitial());
    } catch (e) {
      debugPrint('Error fetching policy: $e');
      return;
    }
  }

  Future<void> _confirmUserAgreement(
      ConfirmUserAgreementEvent event, Emitter<HomeState> emit) async {
    try {
      emit(LoadingHome());
      final uuid =
          await const FlutterSecureStorage().read(key: UserModel.userUuidKey);
      policy = await HomeApi().confirmUserAgreements(uuid);
      emit(PolicyAgreement());
    } catch (e) {
      return;
    }
  }

  final List<HomeItemModel> homeItems = [
    HomeItemModel(
      title: 'Access Management',
      icon: Assets.accessIcon,
      active: true,
      onPress: (context) {
        context.read<SpaceTreeBloc>().add(ClearCachedData());
        context.go(RoutesConst.accessManagementPage);
      },
      color: const Color(0xFF0036E6),
    ),
    HomeItemModel(
      title: 'Space Management',
      icon: Assets.spaseManagementIcon,
      active: true,
      onPress: (context) {
        context.read<SpaceTreeBloc>().add(ClearCachedData());
        context.go(RoutesConst.spacesManagementPage);
      },
      color: const Color(0xFF0026A2),
    ),
    HomeItemModel(
      title: 'Devices Management',
      icon: Assets.devicesIcon,
      active: true,
      onPress: (context) {
        context.read<SpaceTreeBloc>().add(ClearCachedData());
        BlocProvider.of<RoutineBloc>(context)
            .add(const TriggerSwitchTabsEvent(isRoutineTab: false));
        context.go(RoutesConst.deviceManagementPage);
      },
      color: const Color(0xFF00165E),
    ),
    HomeItemModel(
      title: 'Syncrow Analytics',
      icon: Assets.analyticsIcon,
      active: true,
      onPress: (context) {
        context.read<SpaceTreeBloc>().add(ClearCachedData());
        BlocProvider.of<RoutineBloc>(context)
            .add(const TriggerSwitchTabsEvent(isRoutineTab: false));
        context.go(RoutesConst.analytics);
      },
      color: const Color(0xFF023DFE),
    ),
  ];
}
