import 'package:fhub/backend/DataManager.dart';
import 'package:fhub/backend/helpers.dart';
import 'package:fhub/src/CustomWidgets.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart';

class WithdrawalHistoryPage extends StatefulWidget {
  const WithdrawalHistoryPage({Key? key}) : super(key: key);

  @override
  State<WithdrawalHistoryPage> createState() => _WithdrawalHistoryPageState();
}

class _WithdrawalHistoryPageState extends State<WithdrawalHistoryPage> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    kickstartAnimations();
    GetHistory();
  }
  List<dynamic> wd_requests = [];
  void GetHistory() async{
    wd_requests = await DataManager.GetWithdrawalHistory();

    loaded =true;
    setState(() {

    });
  }

  void kickstartAnimations() async {
    await Future.delayed(const Duration(milliseconds: 500));

    setState(() {
      op1 = 0.5;
      op2 = 0.5;
      op3 = 0.5;
    });
  }
  bool loaded = false;
  ScrollController scrollController = ScrollController();
  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    final screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: Colors.black,
      body: CustomBody(
          child: SafeArea(
              child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Column(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                InkWell(
                                  child: Container(
                                      margin: EdgeInsets.all(10),
                                      child: Icon(Icons.keyboard_arrow_left,
                                          size: 50)),
                                  onTap: () {
                                    Navigator.of(context).pop();
                                  },
                                ),
                                GradientText(
                                  text: "Withdrawal History",
                                  gradient: LinearGradient(colors: [
                                    Colors.white.withOpacity(0.6),
                                    Colors.white.withOpacity(0.5),
                                    Colors.white.withOpacity(0.2)
                                  ]),
                                  style: TextStyle(
                                      fontSize: 29,
                                      fontWeight: FontWeight.bold),
                                ),
                                Container(
                                  width: 40,
                                )
                              ],
                            ),
                            SizedBox(
                              height: 50,
                            ),
                            (loaded) ?
                            (wd_requests.length > 0) ? Padding(
                              padding: const EdgeInsets.all(20.0),
                              child: GlassCard(child: Container(
                                constraints: BoxConstraints(maxHeight: screenHeight * 0.6),
                                padding: EdgeInsets.all(12),
                                child: SingleChildScrollView(
                                  child: Column(
                                    children: [
                                      Container(
                                        padding: EdgeInsets.all(10),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text("Date Requested"),
                                            Text("Amount"),
                                            Text("Status")
                                        ],),
                                      ),
                                      SizedBox(height: 10,),
                                      ListView.builder(
                                        shrinkWrap: true,
                                        controller: scrollController,
                                        itemCount: wd_requests.length,
                                        itemBuilder: (BuildContext context, int index) {
                                          return WdRequestItem(
                                              wd_requests[index]);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              )),
                            ) : Container(height: screenHeight * 0.6,child: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.account_balance_outlined,size: 100,color: Colors.white60,),
                                SizedBox(height: 20,),
                                Text("No Withdrawal Requests"),
                              ],
                            )))
                            :Container(height: screenHeight * 0.6,child: Center(child: Text("Loading...")))

                          ],
                        )
                      ]))),
          context: context,
          onAnimEnd: () {
            kickstartAnimations();
          }),
    );
  }

  Widget WdRequestItem(dynamic request) {
    DateTime createdTime = DateTime.parse(request['created_time']);
    return InkWell(
      onTap: (){
        if((request['receipt'].toString() ?? "").contains("http")){
          launchUrl(Uri.parse(request['receipt']));
        }
      },
      child: Padding(
        padding: const EdgeInsets.all(3.0),
        child: GlassCard(
            color: Colors.white,
            child: Container(
              padding: const EdgeInsets.all(10.0),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [SizedBox(width: 100, child: Text(DateFormat('yyyy-MM-dd').format(createdTime)))],
                    ),
                    Row(
                      children: [
                        Text(
                            "${Helpers.SatsToCoin(int.parse(request['amount'])).toStringAsFixed(8)}"),
                        SizedBox(
                          width: 5,
                        ),
                        Icon(Helpers.GetIconForCrypto(request['coin']))
                      ],
                    ),
                    Text(request['status'])
                  ],
                ),
              ),
            )),
      ),
    );
  }
}
