//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/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.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 '../../../../models/search_all_requests_model.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>();

  @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) {
    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,
        actions: [
          if (_showResetButton())
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  context.translation.reset,
                  style: AppTextStyles.bodyText2.copyWith(color: const Color(0xFF4A8DB7)),
                ).paddingAll(8).onPress(() {
                  setState(() {
                    search!.resetSearchValues();
                  });
                }),
              ],
            )
        ],
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  context.translation.searchBy.heading5(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();
                        setState(() {});
                      }
                    },
                  ),
                  16.height,
                  AppTextFormField(
                    controller: search!.searchBySelectedValue?.controller,
                    labelText: search!.searchBySelectedValue?.label,
                    textInputType: search!.searchBySelectedValue?.inputType,
                    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;
                    },
                  ),
                ],
              ),
            ).expanded,
            AppFilledButton(onPressed: _search, label: context.translation.search),
          ],
        ).paddingAll(16),
      ),
    );
  }

  void _search() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      final requestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      requestsProvider.reset();
      await requestsProvider.getAllRequests(context, search: search);
      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);
  }
}
