import 'package:comwell_key_app/.generated/assets/assets.gen.dart';
import 'package:comwell_key_app/connection_state/connection_state_cubit.dart';
import 'package:comwell_key_app/routing/app_routes.dart';
import 'package:comwell_key_app/themes/comwell_colors.dart';
import 'package:comwell_key_app/utils/l10n_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';

import '../permission_screen_template.dart';
import 'bluetooth_permission_cubit.dart';

class BluetoothPermissionScreen extends StatelessWidget {
  const BluetoothPermissionScreen({super.key});

  bool _bluetoothReady(AppConnectionState prev, AppConnectionState curr) {
    return curr.isBluetoothEnabled && curr.isBluetoothPermissionGranted;
  }

  @override
  Widget build(BuildContext context) {
    final cubit = context.read<BluetoothPermissionCubit>();
    return MultiBlocListener(
      listeners: [
        BlocListener<ConnectionStateCubit, AppConnectionState>(
          listenWhen: (prev, curr) => _bluetoothReady(prev, curr),
          listener: (context, state) {
            context.pop();
          },
        ),
      ],
      child: BlocBuilder<ConnectionStateCubit, AppConnectionState>(
        builder: (context, state) {
          if (state.isLoading) {
            return const Scaffold(
              backgroundColor: sandColor,
              body: Center(
                child: CircularProgressIndicator(
                  color: Colors.white,
                ),
              ),
            );
          }
          if (!state.isBluetoothEnabled) {
            return PermissionScreenTemplate(
              title: context.strings.bluetooth_disabled,
              subtitle: context.strings.please_enable_bluetooth,
              primaryButtonText: context.strings.generic_ok,
              primaryButtonOnClick: () {
                context.go(AppRoutes.overview);
              },
              image: Assets.icons.bluetoothCircled,
            );
          }
          return PermissionScreenTemplate(
            title: context.strings.bluetooth_permission_title,
            subtitle: context.strings.bluetooth_permission_description,
            primaryButtonText: context.strings.allow_bluetooth,
            primaryButtonOnClick: () async {
              await cubit.onRequestPermissionClicked();
              if (context.mounted) {
                if (cubit.isOnboarding) {
                  context.go(AppRoutes.overview);
                } else {
                  context.pop();
                }
              }
            },
            image: Assets.icons.bluetoothCircled,
          );
        },
      ),
    );
  }
}