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/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/equipment/asset_item_listview.dart';
import 'package:test_sa/views/widgets/horizontal_list_widget.dart';
import 'package:test_sa/views/widgets/loaders/lazy_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';

import '../../../models/device/asset.dart';
import '../../../models/device/asset_search.dart';
import '../../../new_views/app_style/app_color.dart';
import '../../../new_views/common_widgets/app_lazy_loading.dart';
import '../../../new_views/common_widgets/custom_app_bar.dart';

class SearchDevicePage extends StatefulWidget {
  /// add on route
  static const String id = "asset_search_page";
  final bool multiSelection;

  const SearchDevicePage({Key? key, this.multiSelection = false}) : super(key: key);

  @override
  State<SearchDevicePage> createState() => _SearchDevicePageState();
}

class _SearchDevicePageState extends State<SearchDevicePage> {
  int _selectedIndex = 0;
  DeviceSearch? search;
  late TextEditingController _searchController;
  late AssetProvider _deviceProvider;
  final List<Asset> _searchableList = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool _isFirst = true;

  List<num> selectedAssets = [];

  @override
  void initState() {
    _searchController = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _searchController.dispose();
    _deviceProvider.searchReset();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    List<String> searchBy = [
      context.translation.assetName,
      context.translation.assetNumber,
      context.translation.oracleCode,
      context.translation.snNumber,
    ];

    _deviceProvider = Provider.of<AssetProvider>(context, listen: false);

    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: DefaultAppBar(title: context.translation.searchAsset),
        body: Column(
          children: [
            HorizontalListWidget(
              list: searchBy,
              callBackFunction: (index) {
                setState(() {
                  _selectedIndex = index;
                });
              },
            ).paddingOnly(top: 16, bottom: 0),
            Form(
              key: _formKey,
              child: AppTextFormField(
                controller: _searchController,
                textInputAction: TextInputAction.search,
                labelText: "${context.translation.searchBy} ${searchBy[_selectedIndex]}",
                onAction: _search,
                onChange: (text) {
                  _searchController.text = text;
                  _searchController.selection = TextSelection.fromPosition(TextPosition(offset: _searchController.text.length));
                  setState(() {});
                },
                onSaved: (value) {
                  setState(() {
                    search = DeviceSearch();
                  });
                  _setValue(value);
                },
                suffixIcon: IconButton(
                  icon: Icon(Icons.search, color: AppColor.icon2Color(context)),
                  splashColor: Colors.transparent,
                  onPressed: _searchController.text.isNotEmpty ? _search : null,
                  color: AppColor.icon2Color(context),
                ).paddingOnly(end: 0),
              ).paddingOnly(top: 16, start: 16, end: 16, bottom: 8),
            ),
            Expanded(
              child: _searchableList.isEmpty
                  ? _isFirst
                      ? const SizedBox()
                      : NoDataFound(message: context.translation.noDeviceFound)
                  : LazyLoading(
                      nextPage: _deviceProvider.nextPage,
                      onLazyLoad: () async {
                        if (_searchController.text.isNotEmpty) {
                          await _deviceProvider.getAssets(search: search, isSearchBy: true);
                          setState(() {
                            _searchableList.clear();
                            _searchableList.addAll(_deviceProvider.searchDevices);
                          });
                        }
                      },
                      child: Column(
                        children: [
                          ListView.separated(
                            itemCount: _searchableList.length,
                            separatorBuilder: (listContext, itemIndex) => 8.height,
                            padding: const EdgeInsets.all(16),
                            itemBuilder: (listContext, itemIndex) {
                              bool isSelected = selectedAssets.contains(_searchableList[itemIndex].id!);
                              String title = isSelected ? "UnSelect" : "Select";
                              return AssetItemListView(
                                device: _searchableList[itemIndex],
                                isSelected: isSelected,
                                onPressed: (device) {
                                  if (widget.multiSelection) {
                                    if (selectedAssets.contains(device.id!)) {
                                      selectedAssets.remove(device.id!);
                                    } else {
                                      selectedAssets.add(device.id!);
                                    }
                                    setState(() {});
                                  } else {
                                    Navigator.of(context).pop();
                                    Navigator.of(context).pop(device);
                                  }
                                },
                                selectButton: Text(title, style: AppTextStyles.bodyText.copyWith(color: AppColor.primary10)),
                              );
                            },
                          ).expanded,
                          if (widget.multiSelection && selectedAssets.isNotEmpty)
                            FooterActionButton.footerContainer(
                                context: context,
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Expanded(
                                      child: AppFilledButton(
                                        label: "Clear",
                                        buttonColor: AppColor.white60,
                                        textColor: AppColor.black10,
                                        loading: false,
                                        onPressed: () async {
                                          selectedAssets.clear();
                                          setState(() {});
                                        },
                                      ),
                                    ),
                                    12.width,
                                    Expanded(
                                      child: AppFilledButton(
                                        label: context.translation.select,
                                        buttonColor: AppColor.primary10,
                                        loading: false,
                                        onPressed: () async {
                                          Navigator.of(context).pop();
                                          List<Asset> assets = _searchableList.where((asset) => selectedAssets.contains(asset.id)).toList();
                                          Navigator.of(context).pop(assets);
                                        },
                                      ),
                                    ),
                                  ],
                                )),
                          // Row(
                          //   mainAxisSize: MainAxisSize.min,
                          //   children: [
                          //     Expanded(
                          //       child: AppFilledButton(
                          //         label: "Clear",
                          //         buttonColor: AppColor.white60,
                          //         textColor: AppColor.black10,
                          //         loading: false,
                          //         onPressed: () async {
                          //           selectedAssets.clear();
                          //           setState(() {});
                          //         },
                          //       ),
                          //     ),
                          //     12.width,
                          //     Expanded(
                          //       child: AppFilledButton(
                          //         label: context.translation.select,
                          //         buttonColor: AppColor.primary10,
                          //         loading: false,
                          //         onPressed: () async {
                          //           Navigator.of(context).pop();
                          //           List<Asset> assets = _searchableList.where((asset) => selectedAssets.contains(asset.id)).toList();
                          //           Navigator.of(context).pop(assets);
                          //         },
                          //       ),
                          //     ),
                          //   ],
                          // ).toShadowContainer(context),
                        ],
                      ),
                    ),
            )
          ],
        ));
  }

  void _search() async {
    FocusScope.of(context).unfocus();
    _formKey.currentState!.save();
    _deviceProvider.searchReset();
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    await _deviceProvider.getAssets(search: search, isSearchBy: true);
    setState(() {
      _searchableList.clear();
      _searchableList.addAll(_deviceProvider.searchDevices);
      _isFirst = false;
    });
    Navigator.pop(context);
  }

  _setValue(value) {
    /// todo : check oracle code (no matched parameter)
    switch (_selectedIndex) {
      case 0:
        search!.assetName = value;
        break;
      case 1:
        search!.assetNo = value;
        break;
      case 2:
        search!.oracleCodeValue = value;
        search!.oracleCodeTypeId = 412;
        break;
      case 3:
        search!.assetSerialNumber = value;
        break;
      default:
        break;
    }
  }

// bool _showResetButton() {
//   return (_searchController?.text?.isNotEmpty ?? false);
// }
}
