import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:sfm_app/feature/device_log/device_logs_model.dart';
import 'package:sfm_app/product/constant/image/image_constants.dart';
import 'package:sfm_app/product/shared/shared_line_chart.dart';
import 'package:simple_ripple_animation/simple_ripple_animation.dart';
import '../../../product/shared/shared_curve.dart';
import '../device_model.dart';
import '../../../product/base/bloc/base_bloc.dart';
import '../../../product/extention/context_extention.dart';
import '../../../product/services/language_services.dart';
import '../../../product/utils/device_utils.dart';

import '../../../product/constant/icon/icon_constants.dart';
import '../../../bloc/device_detail_bloc.dart';

class DetailDeviceScreen extends StatefulWidget {
  const DetailDeviceScreen({super.key, required this.thingID});
  final String thingID;
  @override
  State<DetailDeviceScreen> createState() => _DetailDeviceScreenState();
}

class _DetailDeviceScreenState extends State<DetailDeviceScreen> {
  List<String> imageAssets = [
    IconConstants.instance.getIcon("normal_icon"),
    IconConstants.instance.getIcon("offline_icon"),
    IconConstants.instance.getIcon("flame_icon"),
  ];

  String stateImgAssets(int state) {
    String imgStringAsset;
    if (state == 0) {
      imgStringAsset = imageAssets[0];
    } else if (state == 1) {
      imgStringAsset = imageAssets[2];
    } else {
      imgStringAsset = imageAssets[1];
    }
    return imgStringAsset;
  }

  late DetailDeviceBloc detailDeviceBloc;
  Completer<GoogleMapController> controller = Completer();
  CameraPosition initialCamera = const CameraPosition(
      target: LatLng(20.966048511844402, 105.74977710843086), zoom: 15);
  @override
  void initState() {
    super.initState();
    detailDeviceBloc = BlocProvider.of(context);
  }

  TextStyle textstyle = const TextStyle(
    fontSize: 25,
    fontWeight: FontWeight.w600,
  );

  BoxDecoration boxDecoration = BoxDecoration(
    borderRadius: BorderRadius.circular(15),
    color: Colors.grey.withValues(alpha: 0.1),
    border: Border.all(
      width: 1,
      color: Colors.grey.withValues(alpha: 0.6),
    ),
  );

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<Device>(
      stream: detailDeviceBloc.streamDeviceInfo,
      builder: (context, deviceSnapshot) {
        if (deviceSnapshot.data?.extId == null) {
          detailDeviceBloc.getDeviceDetail(
            context,
            widget.thingID,
            controller,
          );
          return const Center(
            child: CircularProgressIndicator(),
          );
        } else {
          return StreamBuilder<Map<String, dynamic>>(
            stream: detailDeviceBloc.streamDeviceSensor,
            builder: (context, sensorSnapshot) {
              if (sensorSnapshot.data != null) {
                return Scaffold(
                  appBar: AppBar(
                    title: Text(appLocalization(context).detail_message),
                    centerTitle: true,
                  ),
                  body: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        Stack(
                          children: [
                            ClipPath(
                              clipper: CuveEdgesCustom(),
                              child: Container(
                                padding: const EdgeInsets.all(0),
                                child: SizedBox(
                                  height: context.dynamicHeight(0.25),
                                  child: Stack(
                                    children: [
                                      Positioned.fill(
                                        child: Image.asset(
                                          ImageConstants.instance
                                              .getImage('smoke-detector'),
                                          fit: BoxFit.fill,
                                        ),
                                      ),
                                      Center(
                                        child: Container(
                                          height: 50,
                                          width: 400,
                                          // color: Colors.blueAccent,
                                          alignment: Alignment.centerRight,
                                          margin: const EdgeInsets.fromLTRB(
                                              0, 0, 0, 50),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              const SizedBox(),
                                              Text(
                                                deviceSnapshot.data?.name ?? "",
                                                style: const TextStyle(
                                                  fontSize: 25,
                                                  fontWeight: FontWeight.w600,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                            Positioned(
                              bottom: 0,
                              left: MediaQuery.of(context).size.width / 2 - 100,
                              child: Container(
                                height: context.dynamicHeight(0.08),
                                width: context.dynamicWidth(0.5),
                                decoration: BoxDecoration(
                                  color: DeviceUtils.instance.getTableRowColor(
                                      deviceSnapshot.data?.state ?? 3),
                                  borderRadius: BorderRadius.circular(50),
                                ),
                                alignment: Alignment.bottomCenter,
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  children: [
                                    SizedBox(
                                      height: context.mediumValue,
                                      width: context.mediumValue,
                                      child: deviceSnapshot.data?.state == 1
                                          ? RippleAnimation(
                                              color: Colors.red,
                                              delay: context
                                                  .dynamicMilliSecondDuration(
                                                800,
                                              ),
                                              repeat: true,
                                              minRadius: 10,
                                              ripplesCount: 5,
                                              duration: context
                                                  .dynamicMilliSecondDuration(
                                                1800,
                                              ),
                                              child: CircleAvatar(
                                                minRadius: context.mediumValue,
                                                maxRadius: context.mediumValue,
                                                backgroundImage: AssetImage(
                                                  stateImgAssets(
                                                    deviceSnapshot.data!.state!,
                                                  ),
                                                ),
                                              ),
                                            )
                                          : CircleAvatar(
                                              backgroundColor: DeviceUtils
                                                  .instance
                                                  .getTableRowColor(
                                                deviceSnapshot.data?.state ?? 3,
                                              ),
                                              minRadius: context.mediumValue,
                                              maxRadius: context.mediumValue,
                                              backgroundImage: AssetImage(
                                                stateImgAssets(
                                                  deviceSnapshot.data!.state!,
                                                ),
                                              ),
                                            ),
                                    ),
                                    Center(
                                      child: Text(
                                        DeviceUtils.instance.checkStateDevice(
                                          context,
                                          deviceSnapshot.data!.state!,
                                        ),
                                        style: const TextStyle(
                                          fontSize: 20,
                                          fontWeight: FontWeight.w600,
                                          color: Colors.white,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: context.normalValue,
                        ),
                        // Muc song va muc pin
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Container(
                              height: context.dynamicHeight(0.18),
                              width: context.dynamicWidth(0.45),
                              decoration: boxDecoration,
                              child: Padding(
                                padding: context.paddingLow,
                                child: Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          appLocalization(context)
                                              .paginated_data_table_column_deviceSignal,
                                          style: const TextStyle(
                                            fontSize: 18,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        SizedBox(
                                          height: context.dynamicWidth(0.12),
                                          width: context.dynamicWidth(0.12),
                                          child: Icon(
                                            DeviceUtils.instance.getSignalIcon(
                                              context,
                                              sensorSnapshot.data!['sensorCsq'],
                                            ),
                                            size: 30,
                                            color: DeviceUtils.instance
                                                .getSignalIconColor(
                                              context,
                                              sensorSnapshot.data!['sensorCsq'],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: <Widget>[
                                        Container(
                                          height: context.dynamicHeight(0.09),
                                          alignment: Alignment.centerLeft,
                                          child: Text(
                                            sensorSnapshot.data!['sensorCsq'],
                                            style: TextStyle(
                                              color: DeviceUtils.instance
                                                  .getSignalIconColor(
                                                context,
                                                sensorSnapshot
                                                    .data!['sensorCsq'],
                                              ),
                                              fontSize: 40,
                                              fontWeight: FontWeight.w900,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Container(
                              height: context.dynamicHeight(0.18),
                              width: context.dynamicWidth(0.45),
                              decoration: boxDecoration,
                              child: Padding(
                                padding: context.paddingLow,
                                child: Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          appLocalization(context)
                                              .paginated_data_table_column_deviceBaterry,
                                          style: const TextStyle(
                                            fontSize: 18,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        SizedBox(
                                          height: context.dynamicWidth(0.12),
                                          width: context.dynamicWidth(0.12),
                                          child: Image.asset(
                                            DeviceUtils.instance
                                                .getDeviceBatteryImg(
                                              int.parse(
                                                sensorSnapshot
                                                    .data!['sensorBattery'],
                                              ),
                                            ),
                                            color: DeviceUtils.instance
                                                .getDeviceBatteryColor(
                                              int.parse(
                                                sensorSnapshot
                                                    .data!['sensorBattery'],
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: <Widget>[
                                        Container(
                                          height: context.dynamicHeight(0.09),
                                          alignment: Alignment.centerLeft,
                                          child: Text(
                                            sensorSnapshot
                                                .data!['sensorBattery'],
                                            style: TextStyle(
                                              color: DeviceUtils.instance
                                                  .getDeviceBatteryColor(
                                                int.parse(
                                                  sensorSnapshot
                                                      .data!['sensorBattery'],
                                                ),
                                              ),
                                              fontSize: 50,
                                              fontWeight: FontWeight.w900,
                                            ),
                                          ),
                                        ),
                                        SizedBox(
                                          width: context.lowValue,
                                        ),
                                        Container(
                                          height: context.dynamicHeight(0.09),
                                          width: 60,
                                          alignment: Alignment.centerLeft,
                                          child: Text(
                                            '%',
                                            style: TextStyle(
                                              color: DeviceUtils.instance
                                                  .getDeviceBatteryColor(
                                                int.parse(
                                                  sensorSnapshot
                                                      .data!['sensorBattery'],
                                                ),
                                              ),
                                              fontSize: 30,
                                              fontWeight: FontWeight.w900,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        // Nhiet do
                        Padding(
                          padding: context.paddingLow,
                          child: Container(
                            height: 150,
                            width: MediaQuery.of(context).size.width,
                            decoration: boxDecoration,
                            child: Padding(
                              padding: context.paddingLow,
                              child: Column(
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        appLocalization(context)
                                            .paginated_data_table_column_deviceTemperature,
                                        style: const TextStyle(
                                          fontSize: 18,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                      SizedBox(
                                        height: context.dynamicWidth(0.12),
                                        width: context.dynamicWidth(0.12),
                                        child: Image.asset(
                                          'assets/icons/temperature.png',
                                          color: DeviceUtils.instance
                                              .getDeviceTempColor(
                                            int.parse(
                                              sensorSnapshot
                                                  .data!['sensorTemp'],
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 10,
                                  ),
                                  Stack(
                                    children: [
                                      Container(
                                        width: double.infinity,
                                        height: 20,
                                        decoration: BoxDecoration(
                                          color: Colors.grey
                                              .withValues(alpha: 0.3),
                                          borderRadius:
                                              BorderRadius.circular(10),
                                        ),
                                      ),
                                      LayoutBuilder(
                                        builder: (context, constraints) =>
                                            Container(
                                          width: constraints.maxWidth *
                                              (int.parse(sensorSnapshot
                                                      .data!['sensorTemp']) /
                                                  75),
                                          height: 20,
                                          decoration: BoxDecoration(
                                            color: DeviceUtils.instance
                                                .getDeviceTempColor(
                                              int.parse(sensorSnapshot
                                                  .data!['sensorTemp']),
                                            ),
                                            borderRadius:
                                                BorderRadius.circular(10),
                                          ),
                                        ),
                                      )
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 5,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        "${sensorSnapshot.data!['sensorTemp']} °C",
                                        style: TextStyle(
                                          color: DeviceUtils.instance
                                              .getDeviceTempColor(
                                            int.parse(
                                              sensorSnapshot
                                                  .data!['sensorTemp'],
                                            ),
                                          ),
                                          fontSize: 30,
                                          fontWeight: FontWeight.w900,
                                        ),
                                      ),
                                      const Text(
                                        "75 °C",
                                        style: TextStyle(
                                          fontSize: 20,
                                        ),
                                      ),
                                    ],
                                  )
                                ],
                              ),
                            ),
                          ),
                        ),
                        // Dien ap
                        Padding(
                          padding: context.paddingLow,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                appLocalization(context)
                                    .paginated_data_table_column_devicePower,
                                style: const TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              SizedBox(
                                height: context.dynamicWidth(0.12),
                                width: context.dynamicWidth(0.12),
                                child: Image.asset(
                                  'assets/icons/volt.png',
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(
                          height: context.lowValue,
                        ),
                        // Bieu do dien ap
                        StreamBuilder<List<SensorLogs>>(
                          stream: detailDeviceBloc.streamSensorTemps,
                          builder: (context, sensorTempsSnapshot) {
                            if (sensorTempsSnapshot.data == null) {
                              detailDeviceBloc
                                  .getNearerSensorValue(widget.thingID);
                              return const AspectRatio(
                                aspectRatio: 3,
                                child: Center(
                                  child: CircularProgressIndicator(),
                                ),
                              );
                            } else if (sensorTempsSnapshot.data!.isEmpty) {
                              return Center(
                                child: Text(
                                  appLocalization(context).no_data_message,
                                ),
                              );
                            } else {
                              return AspectRatio(
                                aspectRatio: 3,
                                child: Container(
                                  margin: context.paddingLow,
                                  child: sharedLineChart(
                                    appLocalization(context)
                                        .detail_device_volt_message,
                                    sensorTempsSnapshot.data ?? [],
                                  ),
                                ),
                              );
                            }
                          },
                        ),
                        SizedBox(
                          height: context.lowValue,
                        ),
                        // Map
                        Padding(
                          padding: context.paddingLow,
                          child: Container(
                            decoration: boxDecoration,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                  height: context.dynamicHeight(0.3),
                                  padding: context.paddingLow,
                                  decoration: const BoxDecoration(
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(15),
                                    ),
                                  ),
                                  child: deviceSnapshot
                                              .data!.settings!.latitude !=
                                          ""
                                      ? StreamBuilder<String>(
                                          stream: detailDeviceBloc
                                              .streamDeviceLocation,
                                          builder: (context, locationSnapshot) {
                                            if (locationSnapshot.data == null) {
                                              detailDeviceBloc.findLocation(
                                                  context,
                                                  deviceSnapshot
                                                      .data!.areaPath!);
                                            }
                                            return GoogleMap(
                                              initialCameraPosition:
                                                  initialCamera,
                                              mapType: MapType.normal,
                                              markers: {
                                                Marker(
                                                  infoWindow: InfoWindow(
                                                    title:
                                                        locationSnapshot.data ??
                                                            "",
                                                  ),
                                                  markerId: MarkerId(
                                                      deviceSnapshot
                                                          .data!.thingId!),
                                                  position: LatLng(
                                                    double.parse(deviceSnapshot
                                                        .data!
                                                        .settings!
                                                        .latitude!),
                                                    double.parse(deviceSnapshot
                                                        .data!
                                                        .settings!
                                                        .longitude!),
                                                  ),
                                                ),
                                              },
                                              onMapCreated: (mapcontroller) {
                                                controller
                                                    .complete(mapcontroller);
                                              },
                                              mapToolbarEnabled: false,
                                              zoomControlsEnabled: false,
                                              liteModeEnabled: true,
                                            );
                                          })
                                      : Center(
                                          child: Text(
                                            appLocalization(context)
                                                .detail_device_dont_has_location_message,
                                          ),
                                        ),
                                ),
                                Text(
                                  appLocalization(context)
                                      .device_update_location,
                                  style: const TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              } else {
                return Scaffold(
                  appBar: AppBar(),
                  body: const Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              }
            },
          );
        }
      },
    );
  }
}
