import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/api/login_api_client.dart';

import '../../../controllers/localization/localization.dart';
import '../../../controllers/providers/api/devices_provider.dart';
import '../../../controllers/providers/settings/setting_provider.dart';
import '../../../controllers/providers/user_provider.dart';
import '../../../models/device/device.dart';
import '../../../models/subtitle.dart';
import '../../../models/user.dart';
import '../app_text_form_field.dart';
import '../loaders/loading_manager.dart';
import '../loaders/no_item_found.dart';
import '../qr/scan_qr.dart';
import 'device_item.dart';

class SingleDevicePicker extends StatefulWidget {
  static const String id = "/single-device-Picker";
  final bool sandraChoice = true;

  const SingleDevicePicker({super.key});

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

class SingleDevicePickerState extends State<SingleDevicePicker> {
  DevicesProvider? _devicesProvider;
  UserProvider? _userProvider;
  SettingProvider? _settingProvider;
  final List<Device> _searchableList = [];
  Subtitle? _subtitle;

  _getDevice(String? result) async {
    if (result == null) return;
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (dialogContext) {
          return const Center(child: CircularProgressIndicator());
        });
    List<Device> devices =
        await _devicesProvider!.getDevicesListBySN(host: _settingProvider?.host ?? "", user: UserApiClient().user ?? User(), hospitalId: UserApiClient().user?.hospital?.id ?? "", sn: result);
    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() {
    _devicesProvider?.reset();
    super.dispose();
  }

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

    _subtitle = AppLocalization.of(context)?.subtitle;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: LoadingManager(
        isLoading: _devicesProvider?.isLoading,
        stateCode: _devicesProvider?.stateCode,
        isFailedLoading: _devicesProvider?.devices == null,
        onRefresh: () async {
          _devicesProvider?.reset();
          _searchableList.clear();
          await _devicesProvider?.getEquipment(user: UserApiClient().user ?? User(), host: _settingProvider?.host ?? "", hospitalId: UserApiClient().user?.hospital?.id ?? "");
          _searchableList.addAll(_devicesProvider?.devices ?? []);
        },
        child: Column(
          children: [
            const SizedBox(height: 48),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
              child: Column(
                children: [
                  ATextFormField(
                    hintText: _subtitle?.searchBySn ?? "",
                    style: Theme.of(context).textTheme.subtitle1,
                    suffixIcon: const Icon(Icons.search_rounded),
                    onChange: (value) {
                      _searchableList.clear();
                      _searchableList.addAll(_devicesProvider!.devices!.where((element) => element.serialNumber!.toLowerCase().contains(value.toLowerCase())).toList());
                      setState(() {});
                    },
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  ATextFormField(
                    hintText: "Search by Number",
                    style: Theme.of(context).textTheme.subtitle1,
                    suffixIcon: const Icon(Icons.search_rounded),
                    onChange: (value) {
                      _searchableList.clear();
                      _searchableList.addAll(_devicesProvider!.devices!.where((element) => element.number!.toLowerCase().contains(value.toLowerCase())).toList());
                      setState(() {});
                    },
                  ),
                ],
              ),
            ),
            Expanded(
              child: _searchableList.isEmpty
                  ? NoItemFound(
                      message: _subtitle?.noDeviceFound ?? "",
                    )
                  : 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: (_) => ScanQr()),
          ) as String;
          _getDevice(result);
        },
      ),
    );
  }
}
