import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:go_router/go_router.dart';
import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/routes_const.dart';
import 'package:url_launcher/url_launcher.dart';

class AgreementAndPrivacyDialog extends StatefulWidget {
  final String terms;
  final String policy;

  const AgreementAndPrivacyDialog({
    super.key,
    required this.terms,
    required this.policy,
  });

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

class _AgreementAndPrivacyDialogState extends State<AgreementAndPrivacyDialog> {
  final ScrollController _scrollController = ScrollController();
  bool _isAtEnd = false;
  int _currentPage = 1;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    WidgetsBinding.instance
        .addPostFrameCallback((_) => _checkScrollRequirement());
  }

  void _checkScrollRequirement() {
    final scrollPosition = _scrollController.position;
    if (scrollPosition.maxScrollExtent <= 0) {
      setState(() {
        _isAtEnd = true;
      });
    }
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.atEdge) {
      final isAtBottom = _scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent;
      if (isAtBottom && !_isAtEnd) {
        setState(() {
          _isAtEnd = true;
        });
      }
    }
  }

  String get _dialogTitle =>
      _currentPage == 1 ? 'User Agreement' : 'Privacy Policy';

  String get _dialogContent => _currentPage == 1 ? widget.terms : widget.policy;
  final String staticText =
      '<h5 style="color: #FF5722;">If you cancel you will be logged out.</h5>';

  Widget _buildScrollableContent() {
    return Container(
      padding: const EdgeInsets.all(40),
      width: MediaQuery.of(context).size.width * 0.8,
      height: MediaQuery.of(context).size.height * 0.75,
      decoration: BoxDecoration(
        color: Colors.grey[200],
        borderRadius: const BorderRadius.all(Radius.circular(20)),
      ),
      child: Scrollbar(
        thumbVisibility: true,
        trackVisibility: true,
        interactive: true,
        controller: _scrollController,
        child: SingleChildScrollView(
          controller: _scrollController,
          padding: const EdgeInsets.all(25),
          child: Html(
            data: "$_dialogContent $staticText",
            onLinkTap: (url, attributes, element) async {
              if (url != null) {
                final uri = Uri.parse(url);
                await launchUrl(uri, mode: LaunchMode.externalApplication);
              }
            },
            style: {
              "body": Style(
                fontSize: FontSize(14),
                color: Colors.black87,
                lineHeight: LineHeight(1.5),
              ),
            },
          ),
        ),
      ),
    );
  }

  Widget _buildActionButton() {
    final String buttonText = _currentPage == 2 ? "I Agree" : "Next";

    return InkWell(
      onTap: _isAtEnd
          ? () {
              if (_currentPage == 1) {
                setState(() {
                  _currentPage = 2;
                  _isAtEnd = false;
                  _scrollController.jumpTo(0);
                  WidgetsBinding.instance
                      .addPostFrameCallback((_) => _checkScrollRequirement());
                });
              } else {
                Navigator.of(context).pop(true);
              }
            }
          : null,
      child: Text(
        buttonText,
        style: TextStyle(
          color: _isAtEnd ? ColorsManager.secondaryColor : Colors.grey,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Text(
              _dialogTitle,
              textAlign: TextAlign.center,
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.w700,
                color: ColorsManager.secondaryColor,
              ),
            ),
          ),
          const Divider(),
          _buildScrollableContent(),
          const Divider(),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                InkWell(
                  onTap: () {
                    AuthBloc.logout(context);
                    context.go(RoutesConst.auth);
                  },
                  child: const Text("Cancel"),
                ),
                _buildActionButton(),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
