import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_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/models/enums/user_types.dart';
import 'package:test_sa/models/enums/sort_order.dart';
import 'package:test_sa/models/search_all_requests_model.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_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/pages/land_page/widgets/static_filter_buttons.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';

import '../../../../controllers/providers/api/all_requests_provider.dart';
import '../../../common_widgets/app_lazy_loading.dart';

class AllRequestsFilterPage extends StatefulWidget {
  static const String id = "all_requests_filter_page";
  final SearchAllRequestsModel? data;

  const AllRequestsFilterPage({Key? key, this.data}) : super(key: key);

  @override
  State<AllRequestsFilterPage> createState() => _AllRequestsFilterPageState();
}

class _AllRequestsFilterPageState extends State<AllRequestsFilterPage> {
  SearchAllRequestsModel? search;
  SortOrder selectedSortOption = SortOrder.descending;

  @override
  void initState() {
    search = widget.data;

    // Initialize from widget.data if available, otherwise default to Descending
    if (search?.selectedSortOption != null) {
      // Match the saved sort option name to our enum
      try {
        selectedSortOption = SortOrder.values.firstWhere(
          (e) => e.name == search!.selectedSortOption,
          orElse: () => SortOrder.descending,
        );
      } catch (e) {
        selectedSortOption = SortOrder.descending;
      }
    }

    if (search != null) {
      search?.requestNumber?.controller?.text = search?.requestNumber?.value ?? "";
      search!.assetName?.controller?.text = search?.assetName?.value ?? "";
      search!.assetNo?.controller?.text = search?.assetNo!.value ?? "";
      search!.manufacture?.controller?.text = search?.manufacture!.value ?? "";
      search!.sn?.controller?.text = search?.sn?.value ?? "";
      search!.model?.controller?.text = search?.model?.value ?? "";
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    bool isEngineer = (Provider.of<UserProvider>(context, listen: false).user?.type) == UsersTypes.engineer;
    // bool isUserFMS = Provider.of<SettingProvider>(context, listen: false).isUserFMS;
    if (search == null) {
      search = SearchAllRequestsModel(
        requestNumber: SearchByRequestNumberModel(context, controller: TextEditingController()),
        assetName: SearchByAssetNameModel(context, controller: TextEditingController()),
        assetNo: SearchByAssetNoModel(context, controller: TextEditingController()),
        manufacture: SearchByManufactureModel(context, controller: TextEditingController()),
        sn: SearchBySNModel(context, controller: TextEditingController()),
        model: SearchByRequestModel(context, controller: TextEditingController()),
      );
      search!.searchBySelectedValue = search?.requestNumber;
    }
    Map<String, int> types = {};

    // switching to users permissions
    // context.userProvider.modulesPermissionsList.forEach((module) {
    //   types[module.module!.name!] = module.module!.value!;
    // });

    types = {
      context.translation.correctiveMaintenance: 1,
      context.translation.gasRefill: 2,
      context.translation.transferAsset: 3,
      context.translation.preventiveMaintenance: 4,
      context.translation.task: 6,
    };

    if (isEngineer) {
      types[context.translation.recurrentWo] = 5;
      if (context.settingProvider.isUserFlowMedical) types["Equipment Internal Audit".addTranslation] = 10;
      if (context.settingProvider.isUserFlowMedical) types["System Internal Audit".addTranslation] = 11;
      if (context.settingProvider.isUserFlowMedical) types["Medical Gas Inspection".addTranslation] = 14;
    }

    if (context.settingProvider.isUserFlowMedical && isEngineer) {
      types['Recall and Alert'] = 7;
    }

    // switching asset inventory to users permissions
    context.userProvider.modulesPermissionsList.forEach((module) {
      if (module.module!.value! == 8 || module.module!.value! == 9 || module.module!.value! == 15) {
        types[module.module!.name!] = module.module!.value!;
      }
    });
//Hide traf
//     if (!isEngineer && context.settingProvider.isUserFlowMedical) {
//       types['TRAF'] = 9;
//     }
//
//     if (context.settingProvider.isUserFlowMedical && context.userProvider.isAssessor) {
//       types = {"TRAF": 9};
//     }
    if (context.userProvider.isQualityUser) {
      if (context.settingProvider.isUserFlowMedical) types = {'Recall and Alert': 7};
      if (context.settingProvider.isUserFlowMedical) types['Equipment Internal Audit'] = 10;
      if (context.settingProvider.isUserFlowMedical) types['System Internal Audit'] = 11;
    }

    if (context.settingProvider.isUserFlowMedical) {
      types['Loan Equipment'] = 12;
      // types['Demo'] = 15; moved to permission api
    }

    if (context.userProvider.isCommissioningEngineer && context.settingProvider.isUserFlowMedical) {
      ///TODO need to check what other requests type needed here.
      types = {'Asset Delivery': 13};
    }

    ///TODO need add accessor filter as well.
    if (context.settingProvider.isUserFlowMedical && context.userProvider.isAssessor) {
      types = {
        // 'TRAF': 9,
        //Traf name changed as per client requirements
        'Assessment of Need & Technology': 9,
        // 'Demo': 15, moved to permission api
      };
    }
    if (context.settingProvider.isUserFlowMedical && !context.userProvider.isNurse) {
      types['Incidents'] = 16;
    }
//No need to add check for assetgroup type as this role  will only for FMS
    if (context.userProvider.isHouseKeeper) {
      types = {context.translation.recurrentWo: 5};
    }
    var statuses = {
      "All WO": 0,
      context.translation.open: 1,
      context.translation.inProgress: 2,
      context.translation.completed: 4,
      context.translation.closed: 3,
      "Canceled": 5,
    };
    if (context.userProvider.isHouseKeeper) {
      statuses = {
        "All WO": 0,
        // context.translation.open: 1,
        context.translation.inProgress: 2,
        // context.translation.completed: 4,
        context.translation.closed: 3,
        // "Canceled": 5,
      };
    }
    return Scaffold(
      appBar: DefaultAppBar(
        title: context.translation.filter,showBackButtonAsCancel: true,
        actions: [
          if (_showResetButton())
            TextButton(
              onPressed: () {
                setState(() {
                  search?.statuses?.clear();
                  search?.typeTransaction?.clear();
                  search?.startDate = null;
                  search?.endDate = null;
                  search?.isArchived = false;
                  selectedSortOption = SortOrder.descending;
                });
              },
              style: TextButton.styleFrom(padding: EdgeInsets.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap),
              child: Text(
                'Clear Filters',
                style: AppTextStyles.bodyText2.copyWith(color: AppColor.red30),
              ),
            ).paddingOnly(start: 16, end: 16)
        ],
      ),
      body: Column(
        children: [
          SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                "WO Status".heading5(context).custom(color: AppColor.textStyleColor(context)),
                8.height,
                RequestsTypeFilter(
                  initialValues: search?.statuses ?? [],
                  items: statuses,
                  onSelect: (value) {
                    if (value.isNotEmpty && value.last == 0) {
                      search!.statuses = [0];
                    } else if (value.contains(0)) {
                      search?.statuses?.remove(0);
                    } else {
                      search?.statuses = value;
                    }
                    setState(() {});
                  },
                ),
                16.height,
                "Type of WO".heading5(context).custom(color: AppColor.textStyleColor(context)),
                8.height,
                RequestsTypeFilter(
                  initialValues: search?.typeTransaction ?? [],
                  items: types,
                  onSelect: (value) {
                    search?.typeTransaction = value;
                    setState(() {});
                  },
                ),
                16.height,
                RichText(
                    text: TextSpan(text: "Sort ", style: AppTextStyles.heading5.copyWith(color: AppColor.textStyleColor(context)), children: [
                  TextSpan(text: "(By Date)", style: AppTextStyles.bodyText2.copyWith(color: AppColor.textStyleColor(context))),
                ])),
                8.height,
                Row(
                  children: [
                    for (var element in SortOrder.values)
                      Padding(
                        padding: const EdgeInsets.only(right: 16),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: 24,
                              height: 24,
                              child: Radio(
                                value: element,
                                activeColor: AppColor.primary10,
                                fillColor: WidgetStateColor.resolveWith((states) {
                                  if (states.contains(WidgetState.selected)) {
                                    return AppColor.primary10;
                                  }
                                  return Colors.grey;
                                }),
                                groupValue: selectedSortOption,
                                onChanged: (state) {
                                  setState(() {
                                    selectedSortOption = element;
                                  });
                                },
                              ),
                            ),
                            8.width,
                            Text(
                              element.label,
                              style: AppTextStyles.tinyFont.copyWith(color: AppColor.filterButtonTextColor(context)),
                            ),
                          ],
                        ),
                      )
                  ],
                ),
                16.height,
                context.translation.pickDate.heading5(context).custom(color: AppColor.textStyleColor(context)),
                8.height,
                Row(
                  children: [
                    ADatePicker(
                      label: context.translation.from,
                      from: DateTime(2000),
                      date: search!.startDate,
                      onDatePicker: (date) {
                        setState(() {
                          search!.startDate = date;
                        });
                      },
                    ).expanded,
                    8.width,
                    ADatePicker(
                      label: context.translation.to,
                      from: DateTime(2000),
                      date: search!.endDate,
                      onDatePicker: (date) {
                        if (search!.startDate != null && date.isBefore(search!.startDate!)) {
                          "End Date time must be greater then start date".showToast;
                          return;
                        }
                        setState(() {
                          search!.endDate = date;
                        });
                      },
                    ).expanded,
                  ],
                ),
                16.height,
                // "Archived WO".heading5(context).custom(color: AppColor.textStyleColor(context)),
                // //  8.height,
                // Row(
                //   children: [
                //     Checkbox(
                //         value: search?.isArchived ?? false,
                //         activeColor: AppColor.blueStatus(context),
                //         onChanged: (value) {
                //           if (search?.isArchived != value) {
                //             search?.isArchived = value!;
                //           }
                //           if (mounted) setState(() {});
                //        }),
                //     "View Archived Requests".bodyText(context).expanded,
                //   ],
                // ).onPress(() {
                //   search?.isArchived = !search!.isArchived;
                //   setState(() {});
                // }),
              ],
            ),
          ).expanded,
          FooterActionButton.footerContainer(context: context, child: AppFilledButton(onPressed: _search, label: context.translation.applyFilter))
        ],
      ),
    );
  }

  void _search() async {
    final requestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);

    // Save the enum name (ascending or descending) instead of label
    search!.selectedSortOption = selectedSortOption.name;

    if (search?.startDate != null) search?.endDate ??= DateTime.now();
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    requestsProvider.reset();
    requestsProvider.searchedModel = search;
    await requestsProvider.getAllRequests(context, search: search, isAscending: selectedSortOption == SortOrder.ascending);
    Navigator.pop(context);
    Navigator.of(context).pop(search);
  }

  bool _showResetButton() {
    return (search?.statuses?.isNotEmpty ?? false) ||
        (search?.typeTransaction?.isNotEmpty ?? false) ||
        (search?.startDate != null) ||
        (search?.endDate != null) ||
        (search?.isArchived ?? false) ||
        selectedSortOption != SortOrder.descending;
  }
}
