import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/localization/localization.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/models/device/device.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/views/widgets/equipment/device_item.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_item_found.dart';

import '../app_text_form_field.dart';
import '../qr/scan_qr.dart';

class SingleDevicePicker extends StatefulWidget {
  static final String id = "/single-device-Picker";
  final bool sandraChoice = true;
  @override
  _SingleDevicePickerState createState() => _SingleDevicePickerState();
}

class _SingleDevicePickerState extends State<SingleDevicePicker> {
  DevicesProvider _devicesProvider;
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  List<Device> _searchableList = [];
  List<Device> _initList = [];
  bool _firstTime = true;
  Subtitle _subtitle;

  TextEditingController numberController = TextEditingController();
  TextEditingController snController = TextEditingController();
  _getDevice(String result) async {
    print(result);
    if (result == null) return;
    // List<Device> devices = await _devicesProvider.getDevicesListBySN(host: _settingProvider.host, user: _userProvider.user, hospitalId: _userProvider.user.clientId, sn: result);
    _devicesProvider.reset();
    await _devicesProvider.getEquipment(user: _userProvider.user, host: _settingProvider.host, hospitalId: _userProvider.user.clientId, serialNumber: "", number: result);
    _searchableList.clear();
    _searchableList.addAll(_devicesProvider.devices);
    // Navigator.of(context).pop();
    // Navigator.of(context).pop();
    // if (devices.isEmpty) {
    //   Fluttertoast.showToast(msg: _subtitle.noDeviceFound);
    //   return;
    // }
    // Navigator.of(context).pop(devices.first);
  }

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

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

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

    if (_firstTime && _devicesProvider.devices != null) {
      _searchableList.clear();
      _searchableList.addAll(_devicesProvider.devices);
      _initList.addAll(_devicesProvider.devices);
    }
    _subtitle = AppLocalization.of(context).subtitle;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: SafeArea(
        child: LoadingManager(
          isLoading: _devicesProvider.isLoading,
          stateCode: _devicesProvider.stateCode,
          isFailedLoading: _devicesProvider.devices == null,
          onRefresh: () async {
            _devicesProvider.reset();
            await _devicesProvider.getEquipment(user: _userProvider.user, host: _settingProvider.host, hospitalId: _userProvider.user.clientId);
          },
          child: Column(
            children: [
              const SizedBox(height: 16),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                child: Column(
                  children: [
                    ATextFormField(
                      hintText: "Search by Asset Number",
                      controller: numberController,
                      style: Theme.of(context).textTheme.subtitle1,
                      suffixIcon: const Icon(Icons.search_rounded),
                      textInputAction: TextInputAction.search,
                      onAction: () async {
                        _devicesProvider.reset();
                        await _devicesProvider.getEquipment(
                            user: _userProvider.user, host: _settingProvider.host, hospitalId: _userProvider.user.clientId, serialNumber: snController.text, number: numberController.text);
                        _searchableList.clear();
                        _searchableList.addAll(_devicesProvider.devices);
                      },
                    ),
                    const SizedBox(
                      height: 8,
                    ),
                    ATextFormField(
                      hintText: _subtitle.searchBySn,
                      controller: snController,
                      style: Theme.of(context).textTheme.subtitle1,
                      suffixIcon: const Icon(Icons.search_rounded),
                      textInputAction: TextInputAction.search,
                      onAction: () async {
                        _devicesProvider.reset();
                        await _devicesProvider.getEquipment(
                            user: _userProvider.user, host: _settingProvider.host, hospitalId: _userProvider.user.clientId, serialNumber: snController.text, number: numberController.text);
                        _searchableList.clear();
                        _searchableList.addAll(_devicesProvider.devices);
                      },
                    ),
                  ],
                ),
              ),
              Expanded(
                  child: _searchableList.isEmpty
                      ? NoItemFound(
                          message: _subtitle.noDeviceFound,
                        )
                      : LazyLoading(
                          nextPage: _devicesProvider.nextPage,
                          onLazyLoad: () async {
                            await _devicesProvider.getDevicesList(
                                user: _userProvider.user, host: _settingProvider.host, hospitalId: _userProvider.user.clientId, serialNumber: snController.text, number: numberController.text);
                          },
                          child: ListView.builder(
                            padding: EdgeInsets.zero,
                            shrinkWrap: true,
                            itemCount: _searchableList.length,
                            itemBuilder: (listContext, itemIndex) {
                              return DeviceItem(
                                device: _searchableList[itemIndex],
                                onPressed: (device) {
                                  Navigator.of(context).pop(device);
                                },
                              );
                            },
                          ),
                        )),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        heroTag: "some tag 2",
        child: const Icon(Icons.qr_code_scanner),
        onPressed: () async {
          String result = await Navigator.of(context).push(
            MaterialPageRoute(builder: (_) => const ScanQr()),
          ) as String;
          _getDevice(result);
        },
      ),
    );
  }
}
