import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/asset_delivery_module/helper_function.dart';
import 'package:test_sa/modules/asset_delivery_module/models/asset_delivery_data_model.dart';
import 'package:test_sa/modules/asset_delivery_module/models/cost_center_model.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/attachment_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/end_user_acceptance/cost_center_card_view.dart';
import 'package:test_sa/modules/asset_delivery_module/pages/end_user_acceptance/update_end_user_cost_center_details_view.dart';
import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import '../../../../new_views/common_widgets/app_filled_button.dart';
import '../../../../new_views/common_widgets/default_app_bar.dart';

class EndUserCostCenterLIstView extends StatefulWidget {
  final AssetDeliveryTableModel deliveryTableModel;
  final AssetDeliveryDataModel? requestModel;

  EndUserCostCenterLIstView({
    Key? key,
    required this.deliveryTableModel,
    this.requestModel,
  }) : super(key: key);

  @override
  State<EndUserCostCenterLIstView> createState() => _EndUserCostCenterLIstViewState();
}

class _EndUserCostCenterLIstViewState extends State<EndUserCostCenterLIstView> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool viewOnly = false;
  List<CostCenterModel> costCenterList = [];
  AssetDeliveryProvider? assetDeliveryProvider;
  bool isLoading = false;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
    super.initState();
  }

  void getInitialData() async {
    assetDeliveryProvider = Provider.of<AssetDeliveryProvider>(context, listen: false);
    isLoading = true;
    if (widget.deliveryTableModel.status?.value != null && widget.deliveryTableModel.status!.value! > 4) {
      viewOnly = true;
    }
    setState(() {});
    costCenterList = (await assetDeliveryProvider?.getEndUserCostCenterList(
          tableItemId: widget.deliveryTableModel.id,
        )) ??
        [];
    isLoading = false;
    setState(() {});
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      // appBar: DefaultAppBar(
      //   title: 'End-User Acceptance'.addTranslation,
      //   titleStyle: AppTextStyles.heading3.copyWith(fontWeight: FontWeight.w500, color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
      // ),
      body: Form(
        key: _formKey,
        child: isLoading
            ?  CircularProgressIndicator(color: AppColor.loadingColor(context)).center
            : Column(
                children: [
                  //Refactor this
                  SingleChildScrollView(padding: const EdgeInsets.all(16), child: linesList(context)).expanded,

                  !viewOnly
                      ? FooterActionButton.footerContainer(
                          context: context,
                          child: Column(
                            children: [
                              AppFilledButton(buttonColor: AppColor.primary10, label: 'Attachments'.addTranslation, maxWidth: true, onPressed: _attachmentTap),
                              16.height,
                              Row(
                                children: [
                                  AppFilledButton(
                                    label: 'Cancel'.addTranslation,
                                    maxWidth: true,
                                    buttonColor: AppColor.background(context),
                                    textColor: AppColor.red30,
                                    showBorder: true,
                                    onPressed: _cancelTap,
                                  ).expanded,
                                  12.width,
                                  AppFilledButton(buttonColor: AppColor.green70, label: 'Change Status'.addTranslation, maxWidth: true, onPressed: _changeStatusTap).expanded,
                                ],
                              ),
                            ],
                          ))
                      : FooterActionButton.footerContainer(
                          context: context,
                          child: AppFilledButton(
                              buttonColor: AppColor.white60,
                              label: 'Attachments'.addTranslation,
                              maxWidth: true,
                              textColor: AppColor.black10,
                              onPressed: () {
                                HelperFunction.attachmentTap(context: context, viewOnly: true, assetDeliveryProvider: assetDeliveryProvider!, deliveryTableItemId: widget.deliveryTableModel.id);
                              }),
                        ),
                ],
              ),
      ),
    );
  }

  //Need to refector don't use listview and singlechildview both @waseem.
  Widget linesList(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "Cost Center",
          style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.black10),
        ),
        8.height,
        ListView.separated(
          itemCount: costCenterList.length,
          separatorBuilder: (_, __) => 8.height,
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (listContext, itemIndex) {
            return EndUserCostCenterCardView(
              costModel: costCenterList[itemIndex],
              isViewOnly: viewOnly,
              editPress: () async {
                bool isRefresh = await Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => UpdateEndUserCostCenterDetailsView(
                              costCenterModel: costCenterList[itemIndex],
                              tableItemId: widget.deliveryTableModel.id,
                              isHmg: widget.requestModel?.isHMG,
                            )));
                if (isRefresh) {
                  getInitialData();
                }
              },
            );
          },
        ),
      ],
    );
  }

  void _attachmentTap() async {
    HelperFunction.attachmentTap(context: context, assetDeliveryProvider: assetDeliveryProvider!, deliveryTableItemId: widget.deliveryTableModel.id);
  }

  void _cancelTap() async {
    HelperFunction.cancelRequest(context: context, itemId: widget.deliveryTableModel.id!, requestId: widget.requestModel?.id);
    // showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    // await assetDeliveryProvider?.changeDeliveryStatusToCancel(itemId: widget.deliveryTableModel.id).then((status) async {
    //   Navigator.pop(context);
    //   if (status) {
    //     Navigator.pop(context);
    //     await assetDeliveryProvider?.getAssetDeliveryTableListById(requestId: widget.requestModel?.id);
    //   }
    // });
  }

  void _changeStatusTap() async {
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    await assetDeliveryProvider?.changeDeliveryStatus(itemId: widget.deliveryTableModel.id).then((status) async {
      Navigator.pop(context);
      if (status) {
        Navigator.pop(context);
        await assetDeliveryProvider?.getAssetDeliveryTableListById(requestId: widget.requestModel?.id);
      }
    });
  }

  void _nextTap() async {
    // Navigator.push(context, MaterialPageRoute(builder: (context) => EndUserCostCenterLIstView()));
  }
}
