// ignore_for_file: use_build_context_synchronously

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'show_direction_widget.dart';
import 'show_nearest_place.dart';
import '../../../product/constant/icon/icon_constants.dart';
import '../../../product/extention/context_extention.dart';
import '../map_bloc.dart';
import '../../../product/services/api_services.dart';
import '../../../product/services/language_services.dart';
import '../../../product/utils/device_utils.dart';

import '../../devices/device_model.dart';

onTapMarker(
  BuildContext context,
  Completer<GoogleMapController> controller,
  MapBloc mapBloc,
  LatLng myLocation,
  Iterable<Device> devices,
  List<String> imageAssets,
  List<Marker> otherMarkers,
  BitmapDescriptor hospitalIcon,
  BitmapDescriptor fireStationIcon,
) {
  showModalBottomSheet(
    context: context,
    builder: (BuildContext modalBottomSheetContext) {
      if (devices.length == 1) {
        List<Device> devicesList = devices.toList();
        final device = devicesList[0];
        String deviceState = DeviceUtils.instance
            .checkStateDevice(modalBottomSheetContext, device.state ?? 3);
        String imgStringAsset;
        if (device.state == 0) {
          imgStringAsset = imageAssets[0];
        } else if (device.state == 1) {
          imgStringAsset = imageAssets[2];
        } else {
          imgStringAsset = imageAssets[1];
        }
        return Padding(
          padding: context.paddingLow,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    "${appLocalization(context).device_title}: ${device.name}",
                    style: context.titleLargeTextStyle,
                  ),
                ],
              ),
              SizedBox(
                height: context.lowValue,
              ),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () async {
                        Navigator.pop(modalBottomSheetContext);
                        var destination = LatLng(
                          double.parse(device.settings!.latitude!),
                          double.parse(device.settings!.longitude!),
                        );
                        mapBloc.findTheWay(
                          context,
                          controller,
                          myLocation,
                          destination,
                        );
                        String deviceLocations = await DeviceUtils.instance
                            .getFullDeviceLocation(context, device.areaPath!);
                        String yourLocation =
                            appLocalization(context).map_your_location;
                        showDirections(
                          context,
                          controller,
                          otherMarkers,
                          mapBloc,
                          yourLocation,
                          deviceLocations,
                          double.parse(device.settings!.latitude!),
                          double.parse(device.settings!.longitude!),
                        );
                      },
                      style: const ButtonStyle(
                        backgroundColor: MaterialStatePropertyAll(Colors.blue),
                        foregroundColor: MaterialStatePropertyAll(Colors.white),
                      ),
                      child: Row(
                        children: [
                          IconConstants.instance
                              .getMaterialIcon(Icons.turn_right),
                          Text(appLocalization(modalBottomSheetContext)
                              .map_show_direction),
                        ],
                      ),
                    ),
                    SizedBox(
                      width: context.lowValue,
                    ),
                    ElevatedButton.icon(
                      onPressed: () {
                        Navigator.pop(modalBottomSheetContext);
                        showNearPlacesSideSheet(
                          context,
                          double.parse(device.settings!.latitude!),
                          double.parse(device.settings!.longitude!),
                          "Bệnh viện gần nhất",
                          5000,
                          "hospital",
                          mapBloc,
                          controller,
                          otherMarkers,
                          hospitalIcon,
                          fireStationIcon,
                        );
                      },
                      style: const ButtonStyle(
                        backgroundColor: MaterialStatePropertyAll(Colors.pink),
                        foregroundColor: MaterialStatePropertyAll(Colors.white),
                      ),
                      icon: IconConstants.instance
                          .getMaterialIcon(Icons.local_hospital),
                      label: Text(appLocalization(modalBottomSheetContext)
                          .map_nearby_hospital),
                    ),
                    SizedBox(
                      width: context.lowValue,
                    ),
                    ElevatedButton.icon(
                      onPressed: () {
                        Navigator.pop(modalBottomSheetContext);
                        showNearPlacesSideSheet(
                          context,
                          double.parse(device.settings!.latitude!),
                          double.parse(device.settings!.longitude!),
                          "đội pccc gần nhất",
                          5000,
                          "fire_station",
                          mapBloc,
                          controller,
                          otherMarkers,
                          hospitalIcon,
                          fireStationIcon,
                        );
                      },
                      style: const ButtonStyle(
                        backgroundColor: MaterialStatePropertyAll(Colors.red),
                        foregroundColor: MaterialStatePropertyAll(Colors.white),
                      ),
                      icon: IconConstants.instance
                          .getMaterialIcon(Icons.fire_truck_outlined),
                      label: Text(appLocalization(modalBottomSheetContext)
                          .map_nearby_firestation),
                    ),
                  ],
                ),
              ),
              SizedBox(height: context.lowValue),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                      '${appLocalization(modalBottomSheetContext).paginated_data_table_column_deviceStatus}: '),
                  SizedBox(
                    height: 25,
                    width: 25,
                    child: CircleAvatar(
                      minRadius: 20,
                      maxRadius: 20,
                      backgroundImage: AssetImage(imgStringAsset),
                    ),
                  ),
                  SizedBox(width: context.lowValue),
                  Text(
                    deviceState,
                    style: context.bodyMediumTextStyle,
                  ),
                ],
              ),
            ],
          ),
        );
        // Tiếp tục xử lý mảng devices
      } else if (devices.length > 1) {
        DeviceSource deviceSource = DeviceSource(
          DeviceUtils.instance.sortDeviceByState(devices.toList()),
          modalBottomSheetContext,
          controller,
          mapBloc,
        );
        // Devices là một phần tử
        return Padding(
          padding: context.paddingLow,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Center(
                child: Text(
                  appLocalization(modalBottomSheetContext)
                      .paginated_data_table_title,
                  style: context.titleLargeTextStyle,
                ),
              ),
              PaginatedDataTable(
                columns: [
                  DataColumn(
                    label: Center(
                      child: Text(
                        appLocalization(modalBottomSheetContext)
                            .input_name_device_device,
                      ),
                    ),
                  ),
                  DataColumn(
                    label: Center(
                      child: Text(
                        appLocalization(modalBottomSheetContext)
                            .paginated_data_table_column_deviceStatus,
                      ),
                    ),
                  ),
                  DataColumn(
                    label: Center(
                      child: Text(
                        appLocalization(modalBottomSheetContext)
                            .paginated_data_table_column_deviceBaterry,
                      ),
                    ),
                  ),
                  DataColumn(
                    label: Center(
                      child: Text(
                        appLocalization(modalBottomSheetContext)
                            .paginated_data_table_column_deviceSignal,
                      ),
                    ),
                  ),
                ],
                source: deviceSource,
                rowsPerPage: 5,
              ),
            ],
          ),
        );
      } else {
        return Text(appLocalization(modalBottomSheetContext).undefine_message);
      }
    },
  );
}

class DeviceSource extends DataTableSource {
  BuildContext context;
  MapBloc mapBloc;
  final List<Device> devices;
  final Completer<GoogleMapController> controller;
  DeviceSource(this.devices, this.context, this.controller, this.mapBloc);
  APIServices apiServices = APIServices();
  @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: MaterialStatePropertyAll(
        DeviceUtils.instance.getTableRowColor(device.state ?? -1),
      ),
      index: index,
      cells: [
        DataCell(
          Text(device.name!),
          onTap: () {
            mapBloc.updateCameraPosition(
              controller,
              double.parse(device.settings!.latitude!),
              double.parse(device.settings!.longitude!),
              16,
            );
            Navigator.pop(context);
          },
        ),
        DataCell(
          Text(deviceState),
          onTap: () {
            mapBloc.updateCameraPosition(
              controller,
              double.parse(device.settings!.latitude!),
              double.parse(device.settings!.longitude!),
              16,
            );
          },
        ),
        DataCell(
          Text(sensorMap['sensorBattery'] + "%"),
          onTap: () {
            mapBloc.updateCameraPosition(
              controller,
              double.parse(device.settings!.latitude!),
              double.parse(device.settings!.longitude!),
              16,
            );
          },
        ),
        DataCell(
          Text(sensorMap['sensorCsq']),
          onTap: () {
            mapBloc.updateCameraPosition(
              controller,
              double.parse(device.settings!.latitude!),
              double.parse(device.settings!.longitude!),
              16,
            );
          },
        ),
      ],
    );
  }

  @override
  bool get isRowCountApproximate => false;
  @override
  int get rowCount => devices.length;
  @override
  int get selectedRowCount => 0;
}
