import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/devices_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/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 '../../../models/device/asset_search.dart';
import '../../../new_views/common_widgets/app_lazy_loading.dart';
import '../../../new_views/common_widgets/default_app_bar.dart';

class DeviceSearchScreen extends StatefulWidget {
  static const String id = "asset_search_screen";
  final DeviceSearch? data;

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

  @override
  State<DeviceSearchScreen> createState() => _DeviceSearchScreenState();
}

class _DeviceSearchScreenState extends State<DeviceSearchScreen> {
  late DeviceSearch search;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  late TextEditingController _assetNameController, _assetNumberController, _snController, _modelController, _supplierController, _siteController, _manufactureController, _mdController;

  @override
  void initState() {
    search = widget.data ?? DeviceSearch();
    _assetNameController = TextEditingController(text: search.assetName);
    _assetNumberController = TextEditingController(text: search.assetNo);
    _snController = TextEditingController(text: search.assetSerialNumber);
    _modelController = TextEditingController(text: search.model);
    _supplierController = TextEditingController(text: search.supplier);
    _siteController = TextEditingController(text: search.site);
    _manufactureController = TextEditingController(text: search.manufacturer);
    _mdController = TextEditingController(text: search.modelDefinition);
    super.initState();
  }

  @override
  void dispose() {
    _assetNameController.dispose();
    _assetNumberController.dispose();
    _snController.dispose();
    _modelController.dispose();
    _supplierController.dispose();
    _siteController.dispose();
    _manufactureController.dispose();
    _mdController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DefaultAppBar(
        title: context.translation.search,
        showBackButtonAsCancel: true,
        actions: [
          if (_showResetButton())
            TextButton(
              onPressed: () {
                setState(() {
                  _assetNameController.text = "";
                  _assetNumberController.text = "";
                  _snController.text = "";
                  _modelController.text = "";
                  _supplierController.text = "";
                  _siteController.text = "";
                  _manufactureController.text = "";
                  _mdController.text = "";
                });
              },
              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: Form(
        key: _formKey,
        child: SafeArea(
          child: Column(
            children: [
              ListView(
                padding: const EdgeInsets.all(16),
                children: [
                  context.translation.searchBy.heading5(context).custom(color: AppColor.textStyleColor(context)),
                  4.height,
                  context.translation.searchByDesc.bodyText2(context).custom(color: AppColor.lightTextColor(context)),
                  16.height,
                  AppTextFormField(
                    controller: _assetNameController,
                    labelText: context.translation.assetName,
                    onChange: (text) {
                      _assetNameController.text = text;
                      _assetNameController.selection = TextSelection.fromPosition(TextPosition(offset: _assetNameController.text.length));
                      setState(() {});
                    },
                    onSaved: (value) {
                      search.assetName = value;
                    },
                  ),
                  8.height,
                  AppTextFormField(
                    controller: _assetNumberController,
                    labelText: context.translation.assetNumber,
                    onChange: (text) {
                      _assetNumberController.text = text;
                      _assetNumberController.selection = TextSelection.fromPosition(TextPosition(offset: _assetNumberController.text.length));
                      setState(() {});
                    },
                    onSaved: (value) {
                      search.assetNo = value;
                    },
                  ),
                  8.height,

                  /// todo : TBD (no matched parameter)
                  AppTextFormField(
                    labelText: context.translation.oracleCode,
                    onSaved: (value) {},
                  ),
                  8.height,
                  AppTextFormField(
                    controller: _snController,
                    labelText: context.translation.snNumber,
                    onChange: (text) {
                      _snController.text = text;
                      _snController.selection = TextSelection.fromPosition(TextPosition(offset: _snController.text.length));
                      setState(() {});
                    },
                    onSaved: (value) {
                      search.assetSerialNumber = value;
                    },
                  ),
                  8.height,
                  AppTextFormField(
                    controller: _modelController,
                    labelText: context.translation.model,
                    onChange: (text) {
                      _modelController.text = text;
                      _modelController.selection = TextSelection.fromPosition(TextPosition(offset: _modelController.text.length));
                      setState(() {});
                    },
                    onSaved: (value) {
                      search.model = value;
                    },
                  ),
                  8.height,
                  AppTextFormField(
                    controller: _supplierController,
                    labelText: context.translation.supplier,
                    onChange: (text) {
                      _supplierController.text = text;
                      _supplierController.selection = TextSelection.fromPosition(TextPosition(offset: _supplierController.text.length));
                      setState(() {});
                    },
                    onSaved: (value) {
                      search.supplier = value;
                    },
                  ),
                  8.height,
                  AppTextFormField(
                    controller: _siteController,
                    labelText: context.translation.site,
                    onChange: (text) {
                      _siteController.text = text;
                      _siteController.selection = TextSelection.fromPosition(TextPosition(offset: _siteController.text.length));
                      setState(() {});
                    },
                    onSaved: (value) {
                      search.site = value;
                    },
                  ),
                  8.height,
                  AppTextFormField(
                    controller: _manufactureController,
                    labelText: context.translation.manufacture,
                    onChange: (text) {
                      _manufactureController.text = text;
                      _manufactureController.selection = TextSelection.fromPosition(TextPosition(offset: _manufactureController.text.length));
                      setState(() {});
                    },
                    onSaved: (value) {
                      search.manufacturer = value;
                    },
                  ),
                  8.height,
                  AppTextFormField(
                    controller: _mdController,
                    labelText: context.translation.md,
                    onChange: (text) {
                      _mdController.text = text;
                      _mdController.selection = TextSelection.fromPosition(TextPosition(offset: _mdController.text.length));
                      setState(() {});
                    },
                    onSaved: (value) {
                      search.modelDefinition = value;
                    },
                  ),
                  8.height,

                  /// todo : TBD (no matched parameter)
                  AppTextFormField(
                    labelText: context.translation.location,
                    onSaved: (value) {},
                  ),
                  8.height,
                ],
              ).expanded,
              FooterActionButton.footerContainer(context: context, child: AppFilledButton(onPressed: _search, label: context.translation.search)),
            ],
          ),
        ),
      ),
    );
  }

  void _search() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      final deviceProvider = Provider.of<AssetProvider>(context, listen: false);
      deviceProvider.reset();
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      await deviceProvider.getAssets(search: search);
      Navigator.pop(context);
      Navigator.of(context).pop(search);
    }
  }

  bool _showResetButton() {
    return (_assetNameController.text.isNotEmpty ?? false) ||
        (_assetNumberController.text.isNotEmpty ?? false) ||
        (_snController.text.isNotEmpty ?? false) ||
        (_modelController.text.isNotEmpty ?? false) ||
        (_supplierController.text.isNotEmpty ?? false) ||
        (_siteController.text.isNotEmpty ?? false) ||
        (_manufactureController.text.isNotEmpty ?? false) ||
        (_mdController.text.isNotEmpty ?? false);
  }
}
