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

class SearchAssetPage extends StatefulWidget {
  /// add on route
  static const String id = "asset_search_page";

  const SearchAssetPage({Key? key}) : super(key: key);

  @override
  State<SearchAssetPage> createState() => _SearchAssetPageState();
}

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

  @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: CustomAppBar(
          title: context.translation.searchAsset,

          /// comment reset button because it isn't exist in new design
          // actions: [
          //   if (_showResetButton())
          //     Row(
          //       crossAxisAlignment: CrossAxisAlignment.center,
          //       children: [
          //         Text(
          //           context.translation.reset,
          //           style: AppTextStyles.bodyText2.copyWith(color: const Color(0xFF4A8DB7)),
          //         ).paddingAll(8).onPress(() {
          //           setState(() {
          //             _searchController.text = "";
          //           });
          //         }),
          //       ],
          //     )
          // ],
        ),
        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 = AssetSearch();
                  });
                  _setValue(value);
                },
                suffixIcon: IconButton(
                  icon: const Icon(Icons.search),
                  splashColor: Colors.transparent,
                  onPressed: _searchController.text.isNotEmpty ? _search : null,
                  color: AppColor.neutral20,
                ).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: ListView.separated(
                        itemCount: _searchableList.length,
                        separatorBuilder: (listContext, itemIndex) => 8.height,
                        padding: const EdgeInsets.all(16),
                        itemBuilder: (listContext, itemIndex) {
                          return AssetItemListView(
                            device: _searchableList[itemIndex],
                            onPressed: (device) {
                              Navigator.of(context).pop();
                              Navigator.of(context).pop(device);
                            },
                            selectButton: Text(context.translation.select, style: AppTextStyles.bodyText.copyWith(color: AppColor.blueStatus(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);
// }
}
