import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
import 'package:tour_travel_agr/api/all_api.dart';
import 'package:tour_travel_agr/helper/components_widget/custom_appbar.dart';
import 'package:tour_travel_agr/helper/components_widget/modal_select_date.dart';
import 'package:tour_travel_agr/helper/components_widget/transaction_list.dart';
import 'package:tour_travel_agr/helper/function/number.dart';
import 'package:tour_travel_agr/helper/function/replace_date.dart';
import 'package:tour_travel_agr/helper/function/session_check.dart';
import 'package:tour_travel_agr/helper/modal_dialog.dart';
import 'package:tour_travel_agr/helper/prefs.dart';
import 'package:tour_travel_agr/helper/widget_responsive.dart';
import 'package:tour_travel_agr/models/transaction_model.dart';
import 'package:tour_travel_agr/resource/assets.dart';
import 'package:tour_travel_agr/resource/colors.dart';
import 'package:tour_travel_agr/resource/constanta_string.dart';
import 'package:tour_travel_agr/resource/font.dart';
import 'package:tour_travel_agr/resource/routes.dart';
import 'package:tour_travel_agr/resource/size.dart';
import 'package:tour_travel_agr/resource/strings.dart';
import 'package:tour_travel_agr/resource/style.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorManager.backgroundColor,
      body: ScreenResponsive(
        widget: const BodyWidget(),
        widthScreen: MediaQuery.of(context).size.width,
      ),
    );
  }
}

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

  @override
  State<BodyWidget> createState() => _BodyWidgetState();
}

class _BodyWidgetState extends State<BodyWidget> {
  String dateSelected = dateLocal(DateTime.now().toLocal().toString());

  bool? todayActive;
  bool? customDateActive;
  String? startDate;
  String? endDate;
  TransactionModel? transactions;

  @override
  void initState() {
    checkSession().then((isLogin) {
      if (isLogin) {
        resetFilter().then((_) {
          getTransactionData(startDate, endDate);
        });
      } else {
        Navigator.pushNamedAndRemoveUntil(
          context,
          Routes.loginRoute,
          (route) => false,
        );
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    setHistoryDate("");
    super.dispose();
  }

  Future<void> resetFilter() async {
    String reimburseDate = getHistoryDate();
    if (reimburseDate != '') {
      List<String> split = reimburseDate.split(" - ");
      if (split.length > 1) {
        startDate = split[0];
        endDate = split[1];
        customDateActive = true;
        todayActive = false;
      } else {
        customDateActive = false;
        todayActive = true;
        startDate = split[0];
        endDate = split[0];
      }
    } else {
      startDate = dateLocal(DateTime.now().toLocal().toString());
      endDate = dateLocal(DateTime.now().toLocal().toString());
      customDateActive = false;
      todayActive = true;
    }
  }

  void getTransactionData(String? start, String? end) {
    Api.transaction(start, end).then((apiResponse) {
      if (apiResponse.error) {
        if (apiResponse.data["code"] == "WRONG_SESSION_ID") {
          modalDialogGlobal(
            context: context,
            title: "Session Expired",
            contentBody: Strings.sessionExpired,
            buttonText: "OK",
            tapButton: () {
              removeSessionId();
              Navigator.pushNamedAndRemoveUntil(
                context,
                Routes.loginRoute,
                (route) => false,
              );
            },
          );
        } else {
          modalDialogGlobal(
            context: context,
            title: "Error",
            contentBody: apiResponse.msg,
            buttonText: "OK",
            tapButton: () {
              Navigator.pop(context);
              Navigator.pop(context);
            },
          );
        }
      } else {
        setState(() {
          transactions = apiResponse.data as TransactionModel;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
        top: AppPadding.safeAreaTop(context),
        left: AppPadding.p20,
        right: AppPadding.p20,
        bottom: AppPadding.safeAreaBot(context),
      ),
      child: Column(
        children: [
          const CustomAppBar(text: "Transaksi"),
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(
                5,
              ),
              border: Border.all(
                color: ColorManager.grey.withOpacity(
                  0.25,
                ),
              ),
            ),
            margin: EdgeInsets.only(
              top: AppMargin.m16,
              bottom: AppMargin.m20,
            ),
            padding: EdgeInsets.symmetric(
              horizontal: AppPadding.p20,
              vertical: AppPadding.p9,
            ),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    dateSelected,
                    style: getSemiBoldStyle(
                      color: Colors.black,
                      fontFamily: FontConstants.openSans,
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      showModalBottomSheet(
                          backgroundColor: ColorManager.backgroundColor,
                          isScrollControlled: true,
                          context: context,
                          builder: (context) {
                            return ModalSelectDate(
                              onTapWidget: () {
                                setState(() {
                                  dateSelected = getHistoryDate();
                                  transactions = null;
                                });
                                Navigator.pop(context);
                                resetFilter().then((_) {
                                  getTransactionData(startDate, endDate);
                                });
                              },
                              todayActive: todayActive!,
                              customDateActive: customDateActive!,
                              startDate: startDate,
                              endDate: endDate,
                              fromWidget: ConstantString.fromWidgetHistory,
                            );
                          });
                    },
                    child: Image(
                      image: AssetImage(
                        Assets.calenderIcon,
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
          Row(
            children: [
              WidgetHead(
                text: "Transaksi",
                icon: Assets.moneyIcon,
                iconColor: ColorManager.pink,
                countText: (transactions == null)
                    ? null
                    : transactions?.transactionCount.toString(),
                countTextColor: ColorManager.primary,
              ),
              SizedBox(
                width: AppMargin.m8,
              ),
              WidgetHead(
                text: "Total",
                icon: Assets.totalIcon,
                iconColor: ColorManager.softGreen,
                countText: (transactions == null)
                    ? null
                    : "Rp ${parsingAmountBackend(transactions!.totalTransaction)}",
                countTextColor: ColorManager.green,
              ),
            ],
          ),
          SizedBox(
            height: AppMargin.m20,
          ),
          Expanded(
            child: (transactions == null)
                ? ListView.builder(
                    padding: EdgeInsets.zero,
                    itemCount: 10,
                    itemBuilder: (c, index) {
                      return const ListTransaction(
                        date: null,
                        title: null,
                        subtitle: null,
                      );
                    },
                  )
                : (transactions!.listTransaction.isEmpty)
                    ? Container(
                        width: double.infinity,
                        height: double.infinity,
                        padding: EdgeInsets.symmetric(
                          horizontal: AppPadding.p20,
                        ),
                        child: Center(
                          child: Text(
                            Strings.transactionNotFound,
                            style: getSemiBoldStyle(
                              color: Colors.grey,
                              fontSize: FontSize.s20,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      )
                    : ListView.builder(
                        padding: EdgeInsets.zero,
                        itemCount: transactions!.listTransaction.length,
                        itemBuilder: (c, index) {
                          return ListTransaction(
                            date: dateLocal(transactions!
                                .listTransaction[index].bussinesDate),
                            title:
                                transactions!.listTransaction[index].brandCode,
                            subtitle:
                                "Rp ${parsingAmountBackend(transactions!.listTransaction[index].total)}",
                          );
                        },
                      ),
          ),
        ],
      ),
    );
  }
}

class WidgetHead extends StatelessWidget {
  const WidgetHead({
    super.key,
    required this.text,
    required this.icon,
    this.countText,
    required this.iconColor,
    required this.countTextColor,
  });

  final String text;
  final String icon;
  final Color iconColor;
  final String? countText;
  final Color countTextColor;
  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        width: double.infinity,
        height: 129,
        padding: EdgeInsets.all(AppPadding.p15),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(
            12,
          ),
          color: ColorManager.backgroundColor,
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.3),
              blurRadius: 2,
              offset: const Offset(5, 5),
            ),
          ],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(100),
                    color: iconColor,
                  ),
                  margin: EdgeInsets.only(
                    right: AppMargin.m8,
                  ),
                  child: Center(
                    child: Image(
                      width: 20,
                      height: 20,
                      image: AssetImage(
                        icon,
                      ),
                    ),
                  ),
                ),
                Text(
                  text,
                  style: getSemiBoldStyle(
                    color: Colors.black,
                    fontFamily: FontConstants.openSans,
                  ),
                )
              ],
            ),
            Row(
              children: [
                (countText != null)
                    ? Expanded(
                        child: Text(
                          countText!,
                          style: getSemiBoldStyle(
                            color: countTextColor,
                            fontSize: 16,
                            fontFamily: FontConstants.openSans,
                          ),
                          textAlign: TextAlign.end,
                        ),
                      )
                    : Shimmer.fromColors(
                        baseColor: ColorManager.baseColorShimmer,
                        highlightColor: ColorManager.highlightColorShimmer,
                        child: Container(
                          width: 25,
                          height: 15,
                          color: ColorManager.primary,
                        ),
                      )
              ],
            )
          ],
        ),
      ),
    );
  }
}
