import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:qpay/models/responsive_policy.dart';
import 'package:qpay/screens/gateway/gateway_controller.dart';
import 'package:url_launcher/url_launcher.dart';

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

  @override
  State<GatewayRedirectScreen> createState() => _GatewayRedirectScreenState();
}

class _GatewayRedirectScreenState extends State<GatewayRedirectScreen> {
  late GatewayController controller;
  late String url;
  String? sessionID;
  bool redirected = false;

  bool integrationStarted = false;

  @override
  void initState() {
    super.initState();
    controller = GatewayController(context);

    url = controller.transactionController.model.receiptData?['targetUrl'];
  }

  void updateRedirect(){
    setState(() {
      redirected = true;
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Complete your payment'),
        leading: context.canPop()
            ? IconButton(
                onPressed: () {
                  context.pop();
                },
                icon: const Icon(Icons.arrow_back),
              )
            : SizedBox.shrink(),
      ),
      body: ListenableBuilder(
        listenable: controller,
        builder: (context, child) {
          return Container(
            padding: EdgeInsets.all(50),
            child: Center(
              child: LayoutBuilder(
                  builder: (context, constraints) {
                    return SizedBox(
                      width: double.parse(constraints.maxWidth > ResponsivePolicy.md ?
                      ResponsivePolicy.md.toString() :
                      constraints.maxWidth.toString()),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(height: 75),

                          Column(
                            children: [
                              Text(
                                'You are about to be redirected to an external gateway to complete your payment. '
                                    'Once complete you can close the gateway tab and return to this one to check your '
                                    'transaction status.',
                                style: TextStyle(fontSize: 20),
                                textAlign: TextAlign.center,
                              ),
                              SizedBox(height: 50,),
                              Image.asset('assets/velocity-animation.gif', width: 150),
                              SizedBox(height: 50),

                              if(!redirected)
                              OutlinedButton(
                                child: Text('Redirect'),
                                onPressed: () async {
                                  updateRedirect();
                                  final Uri uri = Uri.parse(url);
                                  if (!await launchUrl(
                                    uri,
                                    mode: LaunchMode.platformDefault, // Default behavior, usually opens in new tab on web
                                    webOnlyWindowName: '_blank', // Specifically for web to open in a new tab
                                  )) {
                                    throw Exception('Could not launch $url');
                                  }
                                },
                              ),

                              if(redirected)
                              OutlinedButton(
                                child: Text('Check Status'),
                                onPressed: () {
                                  context.go("/poll");
                                },
                              )
                            ],
                          ),
                        ],
                      ),
                    );
                  }
              ),
            ),
          );
        },
      ),
    );
  }
}
