import 'package:dio/dio.dart';
import 'package:farm_tpf/custom_model/Device.dart';
import 'package:farm_tpf/data/api/app_exception.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_loading.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart';
import 'package:farm_tpf/presentation/screens/control_device/bloc/device_bloc.dart';
import 'package:farm_tpf/utils/const_common.dart';
import 'package:farm_tpf/utils/pref.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class WidgetDeviceList extends StatefulWidget {
  final DeviceBloc deviceBloc;
  final List<Device> devices;
  WidgetDeviceList({required this.devices, required this.deviceBloc});
  @override
  _WidgetDeviceListState createState() => _WidgetDeviceListState();
}

class _WidgetDeviceListState extends State<WidgetDeviceList> {
  List<Device> currentDevices = <Device>[];
  late BuildContext _context;
  var pref = LocalPref();
  var token;
  var client;

  Future<Null> getSharedPrefs() async {
    token = await pref.getString(DATA_CONST.TOKEN_KEY);
    var options = BaseOptions(baseUrl: ConstCommon.baseUrl);
    options.headers["Authorization"] = "Bearer $token";
    client = Dio(options);
  }

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

  @override
  Widget build(BuildContext context) {
    _context = context;
    if (widget.devices.isNotEmpty) {
      currentDevices = widget.devices;
      return widgetDeviceList(widget.devices.map((show) => ItemDeviceVM.fromDevice(show)).toList(), _context);
    } else {
      return Container(
        child: const Center(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 32),
            child: Text('Không có dữ liệu'),
          ),
        ),
      );
    }
  }

  Widget widgetDeviceList(List<ItemDeviceVM> items, BuildContext context) {
    return RefreshIndicator(
      child: ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          return _widgetItemDevice(items[index], context);
        },
        itemCount: items.length,
      ),
      onRefresh: () async {
        widget.deviceBloc.add(OpenScreen());
      },
    );
  }

  Widget _widgetItemDevice(ItemDeviceVM item, BuildContext context) {
    return GestureDetector(
      onTap: () {
        //Navigator.of(context).push(MaterialPageRoute(builder: (context) => DeviceDetail(device: _device,)));
      },
      child: Container(
          decoration: const BoxDecoration(border: Border(bottom: BorderSide(color: Colors.grey, width: 0.35))),
          child: ListTile(
            title: Text(
              '${item.name} - ${item.location ?? ''}',
              style: const TextStyle(color: Colors.black54, fontSize: 15, fontWeight: FontWeight.bold),
            ),
            subtitle: widgetStatus(item),
            trailing: powerBtn(item, context),
          )),
    );
  }

  Widget powerBtn(ItemDeviceVM item, BuildContext _context) {
    return BlocConsumer<DeviceBloc, DeviceState>(
      listener: (context, state) {},
      buildWhen: (prev, current) {
        return current is DisplayDevice;
      },
      builder: (context, state) {
        if (state is DisplayDevice) {
          if (state.devices != null) {
            currentDevices = state.devices ?? <Device>[];
            //mode = 1: auto -> cho phep dieu khien
            if (item.mode == 1) {
              if (item.status == "0") {
                //tat
                return IconButton(
                    icon: const Icon(Icons.power_settings_new),
                    color: Colors.grey,
                    onPressed: () async {
                      //bat
                      _controlSwitchDevice(item, context);
                    });
              } else if (item.status == "1") {
                //Bat
                return IconButton(
                    icon: const Icon(Icons.power_settings_new),
                    color: Colors.blue,
                    onPressed: () async {
                      //tat
                      _controlSwitchDevice(item, context);
                    });
              } else {
                //loi
                return IconButton(icon: const Icon(Icons.power_settings_new), color: Colors.grey, onPressed: () {});
              }
            } else {
              return IconButton(icon: const Icon(Icons.power_settings_new), color: Colors.grey, onPressed: () {});
            }
          }
          return IconButton(icon: const Icon(Icons.power_settings_new), color: Colors.grey, onPressed: () {});
        } else {
          return IconButton(icon: const Icon(Icons.power_settings_new), color: Colors.grey, onPressed: () {});
        }
      },
    );
  }

  Widget widgetStatus(ItemDeviceVM item) {
    var manualModeString = (item.mode != 1) ? ' - Điều khiển thủ công' : '';
    if (item.status == "0") {
      return RichText(
        text: TextSpan(
          text: 'Đang Tắt',
          style: const TextStyle(color: Colors.black54, fontSize: 13),
          children: <TextSpan>[
            TextSpan(text: manualModeString, style: const TextStyle(color: Colors.black54, fontSize: 13)),
          ],
        ),
      );
    } else if (item.status == "1") {
      return RichText(
        text: TextSpan(
          text: 'Đang Bật',
          style: const TextStyle(color: Colors.green, fontSize: 13),
          children: <TextSpan>[
            TextSpan(text: '$manualModeString', style: const TextStyle(color: Colors.black54, fontSize: 13)),
          ],
        ),
      );
    } else {
      return const Text(
        "Không kết nối",
        style: TextStyle(color: Colors.red, fontSize: 13),
      );
    }
  }

  _controlSwitchDevice(ItemDeviceVM item, BuildContext context) {
    //neu status =1 ->tat . Neu Khong = bat
    var deviceOnOff = (item.status == "1") ? "0" : "1";
    var idDevice = item.id;
    var statusDialogView = (item.status == "1") ? "Tắt" : "Bật";
    Widget cancelButton = CupertinoDialogAction(
      child: const Text("Huỷ"),
      onPressed: () {
        Navigator.of(context).pop();
      },
    );
    Widget continueButton = CupertinoDialogAction(
      child: const Text("Ok"),
      onPressed: () async {
        Navigator.of(context).pop();
        LoadingDialog.showLoadingDialog(_context);
        try {
          var urlTurnOff = "/api/equipment-of-customers-on-off/$idDevice/$deviceOnOff";
          var response = await client.put(urlTurnOff);

          if (200 <= response.statusCode && response.statusCode < 299) {
            LoadingDialog.hideLoadingDialog(_context);
            widget.deviceBloc.add(
              ControlDevice(
                currentDevices: currentDevices,
                updatedDeviceId: (item.id ?? -1).toInt(),
              ),
            );
            Utils.showSnackBarSuccess(message: 'Điều khiển thành công thiết bị ${item.name}');
          }
        } catch (error) {
          LoadingDialog.hideLoadingDialog(_context);
          var errorMessage = AppException.handleError(error,
              customMessageError: "Thiết bị ${item.name} đã được $statusDialogView.\nTải lại để cập nhật trạng thái mới nhất");
          Utils.showSnackBarError(message: errorMessage);
        }
      },
    );
    var alert = CupertinoAlertDialog(
      title: const Text("Điều khiển thiết bị"),
      content: Text("$statusDialogView thiết bị ${item.name}?"),
      actions: [
        cancelButton,
        continueButton,
      ],
    );
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
}

class ItemDeviceVM {
  Device? device;
  num? id;
  String? name;
  String? status;
  String? location;
  num? mode;

  ItemDeviceVM(this.id, this.name, this.status, this.location, this.mode);
  ItemDeviceVM.fromDevice(Device device) {
    this.device = device;
    id = device.id;
    name = device.name.toString();
    status = device.status;
    location = device.location;
    mode = device.mode;
  }
}
