//All request page

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/all_requests_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/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/app_text_form_field.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';

import '../../../../models/search_all_requests_model.dart';
import '../../../../models/enums/sort_order.dart';
import '../../../common_widgets/app_lazy_loading.dart';
import '../../../common_widgets/default_app_bar.dart';
import '../widgets/request_search_buttons.dart';

class AllRequestsSearchPage extends StatefulWidget {
  static const String id = "all_requests_search_page";
  final SearchAllRequestsModel? data;

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

  @override
  State<AllRequestsSearchPage> createState() => _AllRequestsSearchPageState();
}

class _AllRequestsSearchPageState extends State<AllRequestsSearchPage> {
  SearchAllRequestsModel? search;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  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) {
    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;
    }

    return Scaffold(
      /// todo @zaid : FM asked if this button is doable
      // floatingActionButton: FloatingActionButton(
      //   child: "qr".toSvgAsset(height: 32, fit: BoxFit.fitHeight, color: Theme.of(context).scaffoldBackgroundColor),
      //   onPressed: () async {
      //     String result = await Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ScanQr())) as String;
      //     // _getDevice(result, isQr: true);
      //   },
      // ).paddingOnly(bottom: 75),
      appBar: DefaultAppBar(
        title: context.translation.search,
        showBackButtonAsCancel: true,
        actions: [
          if (_showResetButton())
            TextButton(
              onPressed: () {
                setState(() {
                  // search!.resetSearchValues();
                  search?.resetSearchValuesAndController(except: null);
                  search!.startDate = null;
                  search!.endDate = null;
                  selectedSortOption = SortOrder.descending;
                });
              },
              style: TextButton.styleFrom(padding: EdgeInsets.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap),
              child: Text(
                'Clear',
                style: AppTextStyles.bodyText2.copyWith(color: AppColor.red30),
              ),
            ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(context.translation.searchBy, style: AppTextStyles.heading5.copyWith(color: AppColor.labelTextStyleColor(context))),
                  8.height,
                  RequestsSearchButtons(
                    items: [search!.requestNumber!, search!.assetName!, search!.assetNo!, search!.manufacture!, search!.sn!, search!.model!],
                    initialValue: search!.searchBySelectedValue!,
                    onSelect: (value) {
                      if (search!.searchBySelectedValue != value) {
                        search!.searchBySelectedValue = value;
                        // search!.resetSearchValues();
                        search?.resetSearchValuesAndController(except: value.label);

                        setState(() {});
                      }
                    },
                  ),
                  16.height,
                  AppTextFormField(
                    controller: search!.searchBySelectedValue?.controller,
                    labelText: search!.searchBySelectedValue?.label,
                    textInputType: search!.searchBySelectedValue?.inputType,
                    labelStyle: AppTextStyles.textFieldLabelStyle,
                    hintStyle: AppTextStyles.textFieldLabelStyle,
                    showBorder: true,
                    onChange: (text) {
                      search!.searchBySelectedValue?.controller?.text = text;
                      search!.searchBySelectedValue?.controller?.selection = TextSelection.fromPosition(TextPosition(offset: search!.searchBySelectedValue!.controller!.text.length));
                      setState(() {});
                    },
                    onSaved: (value) {
                      search!.searchBySelectedValue!.value = value;
                    },
                  ),
                  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,
                  Text(context.translation.pickDate, style: AppTextStyles.heading5.copyWith(color: AppColor.labelTextStyleColor(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,
                    ],
                  ),
                ],
              ),
            ).expanded,
            FooterActionButton.footerContainer(context: context, child: AppFilledButton(onPressed: _search, label: context.translation.search)),
          ],
        ),
      ),
    );
  }

  void _search() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();

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

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

  bool _showResetButton() {
    return (search?.requestNumber?.controller?.text.isNotEmpty ?? false) ||
        (search?.assetName?.controller?.text.isNotEmpty ?? false) ||
        (search?.assetNo?.controller?.text.isNotEmpty ?? false) ||
        (search?.manufacture?.controller?.text.isNotEmpty ?? false) ||
        (search?.sn?.controller?.text.isNotEmpty ?? false) ||
        (search?.model?.controller?.text.isNotEmpty ?? false) ||
        (search?.startDate != null) ||
        (search?.endDate != null) ||
        selectedSortOption != SortOrder.descending;
  }
}
