import 'dart:developer';

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/string_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/device/asset.dart';
import 'package:test_sa/models/device/asset_search.dart';
import 'package:test_sa/models/device/model_definition.dart';
import 'package:test_sa/modules/asset_delivery_module/models/technical_inpection_asset_model.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/custom_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';

class TechnicalInspectionSearchAssetView extends StatefulWidget {
  /// add on route
  static const String id = "search_asset_view";
  final int? lineId;

  const TechnicalInspectionSearchAssetView({
    Key? key,
    this.lineId,
  }) : super(key: key);

  @override
  State<TechnicalInspectionSearchAssetView> createState() => _TechnicalInspectionSearchAssetViewState();
}

class _TechnicalInspectionSearchAssetViewState extends State<TechnicalInspectionSearchAssetView> {
  int _selectedIndex = 0;
  DeviceSearch? search;
  late TextEditingController _searchController;
  late AssetProvider _deviceProvider;

  //check for this list if not need remove
  final List<TechnicalInspectionAssetBasicInfoModel> _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,
      'model'.addTranslation,
      'manufacturer'.addTranslation,
      // 'assetType'.addTranslation,
      // 'assetOrigin'.addTranslation,
    ];

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

    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: CustomAppBar(
          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: 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.getAssetsForAssetDelivery(search: search, lineId: widget.lineId, isSearchBy: true);
                          setState(() {
                            _searchableList.clear();
                            _searchableList.addAll(_deviceProvider.technicalInspectionAsset);
                          });
                        }
                      },
                      child: ListView.separated(
                        itemCount: _searchableList.length,
                        separatorBuilder: (listContext, itemIndex) => 8.height,
                        padding: const EdgeInsets.all(16),
                        itemBuilder: (listContext, itemIndex) {
                          return AssetItemListView(
                            device: Asset(
                              id: _searchableList[itemIndex].id,
                              assetNumber: _searchableList[itemIndex].assetNumber,
                              assetSerialNo: _searchableList[itemIndex].assetNumber,
                              modelDefinition: ModelDefinition(assetName: _searchableList[itemIndex].assetName, modelName: _searchableList[itemIndex].model),
                            ),
                            onPressed: (device) {
                              Navigator.of(context).pop(device);
                            },
                          );
                        },
                      ),
                    ),
            )
          ],
        ));
  }

  void _search({bool loadMore = false}) async {
    FocusScope.of(context).unfocus();
    _formKey.currentState?.save();
    _searchableList.clear();
    _deviceProvider.technicalInspectionAsset.clear();
    setState(() {});
    _deviceProvider.searchReset();
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    await _deviceProvider.getAssetsForAssetDelivery(
      search: search,
      lineId: widget.lineId,
      isSearchBy: true,
    );

    setState(() {
      _searchableList.clear();
      _searchableList.addAll(_deviceProvider.technicalInspectionAsset);
      _isFirst = false;
    });

    Navigator.pop(context);
  }

  _setValue(String? value) {
    search ??= DeviceSearch();
    switch (_selectedIndex) {
      case 0:
        search!.assetName = value;
        break;
      case 1:
        search!.assetNo = value;
        break;
      case 2:
        search!.model = value;
        break;
      case 3:
        search!.manufacturer = value;
        break;
    }
  }
}
