import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_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/search_all_requests_model.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;

  @override
  void initState() {
    search = widget.data;
    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;
    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;
    }
    final types = {
      context.translation.correctiveMaintenance: 1,
      context.translation.gasRefill: 2,
      context.translation.transferAsset: 3,
      context.translation.preventiveMaintenance: 4,
      // context.translation.task: 6,// todo enable it in NextRelease
    };
    if (isEngineer) {
      types.addAll({context.translation.recurrentWo: 5});
    }
    final 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,
        actions: [
          if (_showResetButton())
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  context.translation.reset,
                  style: AppTextStyles.bodyText2.copyWith(color: AppColor.blueStatus(context)),
                ).paddingAll(8).onPress(() {
                  Provider.of<AllRequestsProvider>(context, listen: false).searchedModel = null;
                  setState(() {
                    search?.statuses?.clear();
                    search?.typeTransaction?.clear();
                    search?.startDate = null;
                    search?.endDate = null;
                    search?.isArchived = false;
                  });
                }),
              ],
            )
        ],
      ),
      body: Column(
        children: [
          SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                "WO Status".heading5(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),
                8.height,
                RequestsTypeFilter(
                  initialValues: search?.typeTransaction ?? [],
                  items: types,
                  onSelect: (value) {
                    search?.typeTransaction = value;
                    setState(() {});
                  },
                ),
                16.height,
                context.translation.pickDate.heading5(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),
                // //  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(() {});
                // }),
              ],
            ).paddingOnly(start: 16, end: 16),
          ).expanded,
          AppFilledButton(onPressed: _search, label: context.translation.applyFilter).paddingOnly(start: 16, end: 16),
        ],
      ).paddingOnly(top: 16, bottom: 16),
    );
  }

  void _search() async {
    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();
    requestsProvider.searchedModel = search;
    await requestsProvider.getAllRequests(context, search: search);
    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);
  }
}
