import 'package:comwell_key_app/.generated/assets/assets.gen.dart';
import 'package:comwell_key_app/presentation/screens/webview/bloc/webview_cubit.dart';
import 'package:comwell_key_app/presentation/screens/webview/bloc/webview_state.dart';
import 'package:comwell_key_app/themes/comwell_colors.dart';
import 'package:comwell_key_app/utils/context_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';

import 'package:webview_flutter/webview_flutter.dart';

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

  @override
  Widget build(BuildContext context) {
    final cubit = context.read<WebviewCubit>();
    return BlocBuilder<WebviewCubit, WebviewState>(
      builder: (BuildContext context, WebviewState state) {
        final webviewCubit = context.read<WebviewCubit>();
        if (state.errorMessage.isNotEmpty) {
          return Scaffold(
            appBar: AppBar(
              leading: IconButton(
                onPressed: () {
                  context.pop();
                },
                icon: Assets.icons.arrowLeft.svg(
                  width: 24,
                  height: 24,
                  colorFilter: const ColorFilter.mode(
                    sandColor,
                    BlendMode.srcIn,
                  ),
                ),
              ),
              title: Text(cubit.title, style: context.textStyles.headingSmall),
              backgroundColor: Colors.white,
              elevation: 0,
              scrolledUnderElevation: 0,
              surfaceTintColor: Colors.transparent,
            ),
            backgroundColor: Colors.white,
            body: Center(
              child: Text(state.errorMessage),
            ),
          );
        }
        return Scaffold(
          appBar: AppBar(
            leading: IconButton(
              onPressed: () {
                context.pop();
              },
              icon: Assets.icons.arrowLeft.svg(
                width: 24,
                height: 24,
                colorFilter: ColorFilter.mode(
                  sandColor,
                  BlendMode.srcIn,
                ),
              ),
            ),
            title: Text(cubit.title, style: context.textStyles.bodySmall),
            backgroundColor: Colors.white,
            elevation: 0,
            scrolledUnderElevation: 0,
            surfaceTintColor: Colors.transparent,
          ),
          body: Stack(
            children: [
              WebViewWidget(controller: webviewCubit.controller),
              if (state.isLoading)
                Center(
                  child: CircularProgressIndicator(
                    color: sandColor,
                    strokeWidth: 2,
                    backgroundColor: sandColor,
                    strokeCap: StrokeCap.round,
                  ),
                ),
            ],
          ),
        );
      },
    );
  }
}