import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:syncrow_app/features/menu/bloc/menu_cubit.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:url_launcher/url_launcher.dart';

class UserAgreement extends StatefulWidget {
  const UserAgreement({super.key});

  @override
  _UserAgreementState createState() => _UserAgreementState();
}

class _UserAgreementState extends State<UserAgreement> {
  @override
  void initState() {
    super.initState();
    MenuCubit.of(context).fetchAgreement();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultScaffold(
      title: 'User Agreement',
      child: BlocBuilder<MenuCubit, MenuState>(
        builder: (context, state) {
          if (state is MenuLoading) {
            return const Center(child: CircularProgressIndicator());
          } else if (state is MenuLoaded) {
            return ListView(
              children: [
                Html(
                  data: state.userAgreementHtml.isNotEmpty
                      ? state.userAgreementHtml
                      : '',
                  onLinkTap: (url, attributes, element) async {
                    final uri = Uri.parse(url!);
                    await launchUrl(uri, mode: LaunchMode.externalApplication);
                  },
                ),
              ],
            );
          } else if (state is MenuError) {
            return Center(
              child: Text(
                'Error: ${state.message}',
                style: const TextStyle(color: Colors.red),
              ),
            );
          }
          return const Center(child: Text('Loading User Agreement...'));
        },
      ),
    );
  }
}
