import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/devices_provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_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/views/pages/device_transfer/device_search_screen.dart';
import 'package:test_sa/views/widgets/equipment/asset_detail_page.dart';
import 'package:test_sa/views/widgets/equipment/asset_item_gridview.dart';
import 'package:test_sa/views/widgets/equipment/asset_item_listview.dart';
import 'package:test_sa/views/widgets/loaders/lazy_loading.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/qr/scan_qr.dart';

import '../../../models/device/asset.dart';
import '../../../models/device/asset_search.dart';
import '../../../new_views/app_style/app_color.dart';
import '../../pages/device_transfer/device_filter_screen.dart';

class MyAssetsPage extends StatefulWidget {
  static const String id = "/single-device-Picker";
  final bool fromBottomBar;

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

  @override
  _MyAssetsPageState createState() => _MyAssetsPageState();
}

class _MyAssetsPageState extends State<MyAssetsPage> {
  late AssetProvider _devicesProvider;
  late UserProvider _userProvider;
  late SettingProvider _settingProvider;
  final List<Asset> _searchableList = [];
  final List<Asset> _initList = [];
  final bool _firstTime = true;
  DeviceSearch? _searchAsset;

  bool showListView = true;

  TextEditingController numberController = TextEditingController();
  TextEditingController snController = TextEditingController();

  _getDevice(String result, {bool isQr = false}) async {
    _devicesProvider.reset();
    await _devicesProvider.getAssets(
      search: DeviceSearch(assetNo: result, assetSerialNumber: ""),
      isQr: isQr,
    );
    _searchableList.clear();
    _searchableList.addAll(_devicesProvider.devices);
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    numberController.dispose();
    snController.dispose();
    _devicesProvider.reset();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _devicesProvider = Provider.of<AssetProvider>(context);
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);

    if (_firstTime) {
      _searchableList.clear();
      _searchableList.addAll(_devicesProvider.devices);
      _initList.addAll(_devicesProvider.devices);
    }

    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        titleSpacing: 0,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (!widget.fromBottomBar)
              const Icon(Icons.arrow_back_ios).onPress(() {
                Navigator.of(context).pop();
              }),
            Container(
              height: 40,
              padding: const EdgeInsets.only(left: 16, right: 8),
              alignment: Alignment.center,
              decoration: ShapeDecoration(
                color: context.isDark ? AppColor.neutral50 : AppColor.neutral30,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
              child: Row(
                children: [
                  Icon(Icons.search, color: context.isDark ? AppColor.neutral10 : AppColor.neutral20, size: 19),
                  8.width,
                  Text(
                    context.translation.search,
                    style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
                  ).expanded,
                ],
              ),
            ).onPress(() async {
              final result = await Navigator.push(context, MaterialPageRoute(builder: (context) => const DeviceSearchScreen()));
              if (result != null) {
                _searchAsset = result;
              }
              _searchableList.clear();
              _searchableList.addAll(_devicesProvider.devices);
            }).expanded,
            16.width,
            Icon(
              Icons.grid_view_outlined,
              color: context.isDark ? AppColor.neutral10 : AppColor.neutral20,
            ).onPress(() => setState(() {
                  showListView = !showListView;
                })),
            16.width,
            Text(
              context.translation.filter,
              style: AppTextStyles.bodyText2.copyWith(color: AppColor.blueStatus(context)),
            ).onPress(() async {
              final result = await Navigator.push(context, MaterialPageRoute(builder: (context) => DeviceFilterScreen(data: _searchAsset)));
              if (result != null) {
                _searchAsset = result;
              }
              _searchableList.clear();
              _searchableList.addAll(_devicesProvider.devices);
            }),
          ],
        ).paddingOnly(start: 16, end: 16),
      ),
      body: SafeArea(
        child: LoadingManager(
          isLoading: _devicesProvider.isLoading,
          stateCode: _devicesProvider.stateCode,
          isFailedLoading: _devicesProvider.devices == null,
          onRefresh: () async {
            _devicesProvider.reset();
            await _devicesProvider.getAssets(search: _searchAsset);
          },
          child: Column(
            children: [
              Expanded(
                  child: _searchableList.isEmpty
                      ? NoDataFound(message: context.translation.noDeviceFound)
                      : LazyLoading(
                          nextPage: _devicesProvider.nextPage,
                          onLazyLoad: () async {
                            await _devicesProvider.getDevicesList(
                              user: _userProvider.user!,
                              host: _settingProvider.host!,
                              hospitalId: _userProvider.user!.clientId!,
                              search: _searchAsset?.copyWith(assetSerialNumber: snController.text, assetNo: numberController.text),
                              // serialNumber: snController.text,
                              // number: numberController.text,
                            );
                          },
                          child: AnimatedSwitcher(
                            duration: const Duration(milliseconds: 500),
                            child: showListView
                                ? ListView.separated(
                                    padding: const EdgeInsets.all(16),
                                    itemCount: _searchableList.length,
                                    separatorBuilder: (listContext, itemIndex) => 8.height,
                                    itemBuilder: (listContext, itemIndex) {
                                      return AssetItemListView(
                                        device: _searchableList[itemIndex],
                                        onPressed: (device) {
                                          widget.fromBottomBar ? Navigator.of(context).pushNamed(AssetDetailPage.id, arguments: device.id) : Navigator.of(context).pop(device);
                                          //      Navigator.of(context).pushNamed(AssetDetailPage.id, arguments: device.id);
                                        },
                                      );
                                    },
                                  )
                                : GridView.builder(
                                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 188 / 261, crossAxisSpacing: 12, mainAxisSpacing: 12),
                                    itemCount: _searchableList.length,
                                    padding: const EdgeInsets.all(16),
                                    itemBuilder: (context, index) {
                                      return AssetItemGridView(
                                        device: _searchableList[index],
                                        onPressed: (device) {
                                          widget.fromBottomBar ? Navigator.of(context).pushNamed(AssetDetailPage.id, arguments: device.id) : Navigator.of(context).pop(device);
                                        },
                                      );
                                    },
                                  ),
                          ),
                        )),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        heroTag: "some tag 2",
        child: "qr".toSvgAsset(height: 32, fit: BoxFit.fitHeight, color: Theme.of(context).scaffoldBackgroundColor),
        onPressed: () async {
          String? result = await Navigator.of(context).push(
            MaterialPageRoute(builder: (_) => const ScanQr()),
          ) as String?;
          if (result != null) _getDevice(result, isQr: true);
        },
      ),
    );
  }
}
