import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/urls.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/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/asset_inventory_module/models/asset_inventory_model.dart';
import 'package:test_sa/modules/asset_inventory_module/provider/asset_inventory_provider.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.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 SearchAssetView extends StatefulWidget {
  static const String id = "asset_search_view";
  final num sessionId;

  const SearchAssetView({Key? key, required this.sessionId}) : super(key: key);

  @override
  State<SearchAssetView> createState() => _SearchAssetViewState();
}

class _SearchAssetViewState extends State<SearchAssetView> {
  int _selectedIndex = 0;
  DeviceSearch? search;
  late TextEditingController _searchController;
  late AssetInventoryProvider _assetInventoryProvider;
  final List<AssetInventoryModel> _searchableList = [];
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool _isFirst = true;

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

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

  @override
  Widget build(BuildContext context) {
    List<String> searchBy = [
      context.translation.assetName,
      context.translation.model,
      context.translation.manufacture,
      context.translation.snNumber,
      context.translation.siteName,
      // 'Building Name'.addTranslation,
      // 'Floor Name'.addTranslation,
      'Department Name'.addTranslation,

      ///need to check if want to add more filters
    ];

    _assetInventoryProvider = Provider.of<AssetInventoryProvider>(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: _assetInventoryProvider.nextPage,
                      onLazyLoad: () async {
                        if (_searchController.text.isNotEmpty) {
                          await _assetInventoryProvider.getAssets(search: search, isSearchBy: true, sessionId: widget.sessionId);
                          setState(() {
                            _searchableList.clear();
                            _searchableList.addAll(_assetInventoryProvider.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 InventoryAssetItemListView(
                                device: _searchableList[itemIndex],
                                // isSelected: isSelected,
                                onPressed: (device) {
                                  // Navigator.of(context).pop();
                                  Navigator.of(context).pop(device);
                                },
                                // selectButton: Text(title, style: AppTextStyles.bodyText.copyWith(color: AppColor.blueStatus(context))),
                              );
                            },
                          ).expanded,
                        ],
                      ),
                    ),
            )
          ],
        ));
  }

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

  _setValue(value) {
    /// todo : check oracle code (no matched parameter)
    /// //ontext.translation.assetName,
    //       context.translation.model,
    //       context.translation.manufacture,
    //       context.translation.snNumber,
    //       context.translation.siteName,
    //       // 'Building Name'.addTranslation,
    //       // 'Floor Name'.addTranslation,
    //       'Department Name'.addTranslation,
    switch (_selectedIndex) {
      case 0:
        search!.assetName = value;
        break;
      case 1:
        search!.model = value;
        break;
      case 2:
        search!.manufacturer = value;
        break;
      case 3:
        search!.assetSerialNumber = value;
        break;
      case 4:
        search!.site = value;
        break;
      case 5:
        search!.department = value;
        break;
      default:
        break;
    }
  }

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

class InventoryAssetItemListView extends StatelessWidget {
  final AssetInventoryModel device;
  final Function(AssetInventoryModel) onPressed;
  final Widget? selectButton;
  final bool isSelected;

  const InventoryAssetItemListView({Key? key, required this.device, required this.onPressed, this.selectButton, this.isSelected = false}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: 95,
          height: 95,
          decoration: ShapeDecoration(
              color: context.isDark ? AppColor.neutral50 : AppColor.neutral30,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
              image: DecorationImage(
                fit: BoxFit.cover,
                image: NetworkImage(device.photo != null ? URLs.getFileUrl(device.photo!)! : "https://www.lasteelcraft.com/images/no-image-available.png"),
              )),
        ),
        15.width,
        Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                device.assetName!.cleanupWhitespace.capitalizeFirstOfEach.heading6(context),
                8.height,
                "${context.translation.assetNumber} : ${device.assetNumber}".bodyText(context),
                "${context.translation.modelName} : ${device.model}".cleanupWhitespace.capitalizeFirstOfEach.bodyText(context),
              ],
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                "${context.translation.serialNo} : ${device.serialNo}".bodyText(context).expanded,
                4.width,
                selectButton ??
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          context.translation.viewDetails,
                          style: AppTextStyles.bodyText.copyWith(color: AppColor.blueStatus(context)),
                        ),
                        4.width,
                        Icon(
                          Icons.arrow_forward,
                          color: AppColor.blueStatus(context),
                          size: 14,
                        )
                      ],
                    ),
              ],
            )
          ],
        ).expanded
      ],
    ).toShadowContainer(context, padding: 12, borderColor: isSelected ? AppColor.blueStatus(context) : Colors.transparent).onPress(() => onPressed(device));
  }
}
