import 'dart:async';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'add_new_device_widget.dart';
import 'delete_device_widget.dart';
import 'device_model.dart';
import 'devices_manager_bloc.dart';
import '../../product/base/bloc/base_bloc.dart';
import '../../product/constant/enums/app_route_enums.dart';
import '../../product/constant/enums/role_enums.dart';
import '../../product/constant/icon/icon_constants.dart';
import '../../product/extention/context_extention.dart';
import '../../product/services/api_services.dart';
import '../../product/services/language_services.dart';
import '../../product/utils/device_utils.dart';

class DevicesManagerScreen extends StatefulWidget {
  const DevicesManagerScreen({super.key});

  @override
  State<DevicesManagerScreen> createState() => _DevicesManagerScreenState();
}

class _DevicesManagerScreenState extends State<DevicesManagerScreen> {
  late DevicesManagerBloc devicesManagerBloc;
  String role = "Undefine";
  APIServices apiServices = APIServices();
  List<Device> devices = [];
  Timer? getAllDevicesTimer;

  @override
  void initState() {
    super.initState();
    devicesManagerBloc = BlocProvider.of(context);
    getUserRole();
    // devicesManagerBloc.getDevice();
    // getAllOwnerDevices();
    // const duration = Duration(seconds: 10);
    // getAllDevicesTimer =
    //     Timer.periodic(duration, (Timer t) => devicesManagerBloc.getDevice());
  }

  @override
  void dispose() {
    getAllDevicesTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: StreamBuilder<List<Device>>(
          stream: devicesManagerBloc.streamAllDevices,
          initialData: devices,
          builder: (context, allDeviceSnapshot) {
            if (allDeviceSnapshot.data?.isEmpty ?? devices.isEmpty) {
              devicesManagerBloc.getDevice();
              return const Center(child: CircularProgressIndicator());
            } else {
              return SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    StreamBuilder<String>(
                        stream: devicesManagerBloc.streamUserRole,
                        initialData: role,
                        builder: (context, roleSnapshot) {
                          return PaginatedDataTable(
                              header: Center(
                                child: Text(
                                  appLocalization(context)
                                      .paginated_data_table_title,
                                  style: context.titleLargeTextStyle,
                                ),
                              ),
                              columns: [
                                if (roleSnapshot.data == RoleEnums.ADMIN.name ||
                                    roleSnapshot.data == RoleEnums.USER.name)
                                  DataColumn(
                                      label: Center(
                                          child: Text(appLocalization(context)
                                              .paginated_data_table_column_action))),
                                DataColumn(
                                    label: Center(
                                        child: Text(appLocalization(context)
                                            .paginated_data_table_column_deviceName))),
                                DataColumn(
                                    label: Center(
                                        child: Text(appLocalization(context)
                                            .paginated_data_table_column_deviceStatus))),
                                DataColumn(
                                    label: Center(
                                        child: Text(appLocalization(context)
                                            .paginated_data_table_column_deviceBaterry))),
                                DataColumn(
                                    label: Center(
                                        child: Text(appLocalization(context)
                                            .paginated_data_table_column_deviceSignal))),
                                DataColumn(
                                    label: Center(
                                        child: Text(appLocalization(context)
                                            .paginated_data_table_column_deviceTemperature))),
                                DataColumn(
                                    label: Center(
                                        child: Text(appLocalization(context)
                                            .paginated_data_table_column_deviceHump))),
                                DataColumn(
                                    label: Center(
                                        child: Text(appLocalization(context)
                                            .paginated_data_table_column_devicePower))),
                              ],
                              onPageChanged: (int pageIndex) {
                                // log('Chuyen page: $pageIndex');
                              },
                              rowsPerPage: 5,
                              actions: [
                                if (roleSnapshot.data == RoleEnums.USER.name ||
                                    roleSnapshot.data == RoleEnums.ADMIN.name)
                                  IconButton(
                                      style: ButtonStyle(
                                          backgroundColor:
                                              MaterialStateProperty.all<Color>(
                                                  Colors.green),
                                          iconColor:
                                              MaterialStateProperty.all<Color>(
                                                  Colors.white)),
                                      onPressed: () {
                                        ScaffoldMessenger.of(context)
                                            .clearSnackBars();
                                        addNewDevice(
                                            context, roleSnapshot.data ?? role);
                                      },
                                      icon: IconConstants.instance
                                          .getMaterialIcon(Icons.add))
                              ],
                              source: DeviceSource(
                                  devices: allDeviceSnapshot.data ?? devices,
                                  context: context,
                                  devicesBloc: devicesManagerBloc,
                                  role: role));
                        })
                  ],
                ),
              );
            }
          }),
    );
  }

  void getUserRole() async {
    role = await apiServices.getUserRole();
    devicesManagerBloc.sinkUserRole.add(role);
  }
}

class DeviceSource extends DataTableSource {
  String role;
  APIServices apiServices = APIServices();
  List<Device> devices;
  final DevicesManagerBloc devicesBloc;
  final BuildContext context;
  DeviceSource(
      {required this.devices,
      required this.context,
      required this.devicesBloc,
      required this.role});
  @override
  DataRow? getRow(int index) {
    if (index >= devices.length) {
      return null;
    }
    final device = devices[index];
    Map<String, dynamic> sensorMap = DeviceUtils.instance
        .getDeviceSensors(context, device.status?.sensors ?? []);
    String deviceState =
        DeviceUtils.instance.checkStateDevice(context, device.state!);
    return DataRow.byIndex(
      // color: getTableRowColor(device.state!),
      index: index,
      cells: [
        if (role == RoleEnums.USER.name || role == RoleEnums.ADMIN.name)
          DataCell(
            Center(
              child: Row(
                children: [
                  IconButton(
                      // style: ButtonStyle(),
                      hoverColor: Colors.black,
                      onPressed: () {
                        context.pushNamed(AppRoutes.DEVICE_UPDATE.name,
                            pathParameters: {'thingID': device.thingId!});
                      },
                      icon: const Icon(Icons.build, color: Colors.blue)),
                  IconButton(
                      onPressed: () async {
                        handleDeleteDevice(context, device.thingId!, role);
                      },
                      icon: const Icon(Icons.delete, color: Colors.red)),
                ],
              ),
            ),
          ),
        DataCell(
            Text(device.name!,
                style: TextStyle(
                    color: DeviceUtils.instance
                        .getTableRowColor(device.state!))), onTap: () {
          // log(device.thingId.toString());
          context.pushNamed(AppRoutes.DEVICE_DETAIL.name,
              pathParameters: {'thingID': device.thingId!});
        }),
        DataCell(
            Center(
                child: Text(deviceState,
                    style: TextStyle(
                        color: DeviceUtils.instance
                            .getTableRowColor(device.state!)))), onTap: () {
          // log(device.thingId.toString());
          context.pushNamed(AppRoutes.DEVICE_DETAIL.name,
              pathParameters: {'thingID': device.thingId!});
        }),
        DataCell(
          Center(
              child: Center(
                  child: Text(sensorMap['sensorBattery'] + "%",
                      style: TextStyle(
                          color: DeviceUtils.instance
                              .getTableRowColor(device.state!))))),
          onTap: () => context.pushNamed(AppRoutes.DEVICE_DETAIL.name,
              pathParameters: {'thingID': device.thingId!}),
        ),
        DataCell(
          Center(
              child: Center(
                  child: Text(sensorMap['sensorCsq'],
                      style: TextStyle(
                          color: DeviceUtils.instance
                              .getTableRowColor(device.state!))))),
        ),
        DataCell(
          Center(
              child: Text(sensorMap['sensorTemp'],
                  style: TextStyle(
                      color: DeviceUtils.instance
                          .getTableRowColor(device.state!)))),
        ),
        DataCell(
          Center(
              child: Text(sensorMap['sensorHum'],
                  style: TextStyle(
                      color: DeviceUtils.instance
                          .getTableRowColor(device.state!)))),
        ),
        DataCell(
          Center(
              child: Text(sensorMap['sensorVolt'],
                  style: TextStyle(
                      color: DeviceUtils.instance
                          .getTableRowColor(device.state!)))),
        ),
      ],
    );
  }

  @override
  int get rowCount => devices.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => 0;
}
