import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import 'package:web_panel/utils/App_color.dart';
import 'package:web_panel/utils/App_text_style.dart';
import 'package:web_panel/utils/spacing.dart';

import '../../../constants.dart';
import '../../../models/RecentFile.dart';
import '../../controllers/device_info_controller.dart';
import '../../responsive.dart';
import '../../routs/rout_name.dart';
import '../../widget/app_drop_down.dart';
import '../../widget/app_text_field.dart';
import '../../widget/pop_up.dart';
import '../global_variable.dart';

class DeviceInfo extends StatelessWidget {
  DeviceInfo({super.key});

  final DeviceInfoController deviceInfoController = Get.put(
    DeviceInfoController(),
  );

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(defaultPadding),
      decoration: BoxDecoration(
        color: AppColor.secondaryColor,
        borderRadius: BorderRadius.all(Radius.circular(10)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // GetX<DeviceInfoController>(
          //   init: DeviceInfoController(),
          //   builder: (controller) {
          //     final devices = controller.paginatedList;
          //
          //     if (controller.isLoading.isTrue && devices.isEmpty) {
          //       return Center(
          //         child: CircularProgressIndicator(
          //           color: AppColor.primaryColor,
          //         ),
          //       );
          //     }
          //
          //     if (devices.isEmpty) {
          //       return Center(
          //         child: Text(
          //           'No devices found',
          //           style: Theme.of(
          //             context,
          //           ).textTheme.titleLarge?.copyWith(color: Colors.white),
          //         ),
          //       );
          //     }
          //
          //     return SizedBox(
          //       width: Responsive.isDesktop(context) ? null : 1100,
          //       child: Scrollbar(
          //         thumbVisibility: true, // Always show scrollbar
          //         thickness: 6, // optional: scrollbar thickness
          //         radius: Radius.circular(10),
          //         child: SingleChildScrollView(
          //           scrollDirection: Axis.horizontal,
          //
          //           child: DataTable(
          //             horizontalMargin: 0,
          //             columnSpacing: 3.sp,
          //
          //             columns: [
          //               DataColumn(
          //                 label: AppDropDown(
          //                   selectedValue: controller.networkStatus,
          //                   optionList: controller.networkStatusList,
          //                   width: 100,
          //                   onSelected: (val) {
          //                     controller.networkStatus(val);
          //
          //                     controller.updateStatusFilter(val);
          //                   },
          //                 ),
          //               ),
          //               DataColumn(
          //                 label: SizedBox(
          //                   width: 120,
          //                   child: Text(
          //                     'Device',
          //                     style: AppTextStyle.cardText(context),
          //                   ),
          //                 ),
          //               ),
          //               DataColumn(
          //                 label: AppDropDown(
          //                   selectedValue: controller.upiPinValue,
          //                   optionList: controller.upiPinList,
          //                   width: 100,
          //                   onSelected: (val) {
          //                     controller.upiPinValue(val);
          //
          //                     controller.updateStatusFilter(val);
          //                   },
          //                 ),
          //               ),
          //               DataColumn(
          //                 label: SizedBox(
          //                   width: 60,
          //                   child: Text(
          //                     'Battery',
          //                     style: AppTextStyle.cardText(context),
          //                   ),
          //                 ),
          //               ),
          //               DataColumn(
          //                 label: SizedBox(
          //                   width: 100,
          //                   child: Text(
          //                     'Last Seen',
          //                     style: AppTextStyle.cardText(context),
          //                   ),
          //                 ),
          //               ),
          //               DataColumn(
          //                 label: AppDropDown(
          //                   selectedValue: controller.notesValue,
          //                   optionList: controller.notesList,
          //                   width: 120,
          //                 ),
          //               ),
          //               DataColumn(
          //                 label: SizedBox(
          //                   width: 150,
          //                   child: Text(
          //                     'Added',
          //                     style: AppTextStyle.cardText(context),
          //                   ),
          //                 ),
          //               ),
          //               DataColumn(
          //                 label: SizedBox(
          //                   width: Responsive.isDesktop(context) ? 150 : 50,
          //                   child: Text(
          //                     'Actions',
          //                     style: AppTextStyle.cardText(context),
          //                   ),
          //                 ),
          //               ),
          //             ],
          //             rows: List.generate(
          //               devices.length,
          //               (index) => recentFileDataRow(context, devices[index]),
          //             ),
          //           ),
          //         ),
          //       ),
          //     );
          //   },
          // ),
          GetX<DeviceInfoController>(
            init: DeviceInfoController(),
            builder: (controller) {
              final devices = controller.paginatedList;
              final isLoading = controller.isLoading.value;

              // Define columns once
              final columns = [
                DataColumn(
                  label: AppDropDown(
                    selectedValue: controller.networkStatus,
                    optionList: controller.networkStatusList,
                    width: 100,
                    onSelected: (val) => controller.updateStatusFilter(val),
                  ),
                ),
                DataColumn(
                  label: SizedBox(
                    width: 120,
                    child: Text(
                      'Device',
                      style: AppTextStyle.cardText(context),
                    ),
                  ),
                ),
                DataColumn(
                  label: AppDropDown(
                    selectedValue: controller.upiPinValue,
                    optionList: controller.upiPinList,
                    width: 100,
                    onSelected: (val) => controller.updateUpiPinFilter(val),
                  ),
                ),
                DataColumn(
                  label: SizedBox(
                    width: 60,
                    child: Text(
                      'Battery',
                      style: AppTextStyle.cardText(context),
                    ),
                  ),
                ),
                DataColumn(
                  label: SizedBox(
                    width: 100,
                    child: Text(
                      'Last Seen',
                      style: AppTextStyle.cardText(context),
                    ),
                  ),
                ),
                DataColumn(
                  label: AppDropDown(
                    selectedValue: controller.notesValue,
                    optionList: controller.notesList,
                    width: 121,
                    onSelected: (val) => controller.updateNotesFilter(val),
                  ),
                ),
                DataColumn(
                  label: SizedBox(
                    width: 150,
                    child: Text('Added', style: AppTextStyle.cardText(context)),
                  ),
                ),
                DataColumn(
                  label: SizedBox(
                    width: Responsive.isDesktop(context) ? 150 : 50,
                    child: Text(
                      'Actions',
                      style: AppTextStyle.cardText(context),
                    ),
                  ),
                ),
              ];

              // Define row content dynamically
              List<DataRow> rows;

              if (isLoading) {
                rows = [
                  DataRow(
                    cells: [
                      DataCell(
                        Container(
                          height: 60,
                          alignment: Alignment.center,
                          width: double.infinity,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                height: 20,
                                width: 20,
                                child: CircularProgressIndicator(
                                  color: AppColor.primaryColor,
                                  strokeWidth: 2,
                                ),
                              ),
                              const SizedBox(width: 8),
                              Text(
                                'Loading...',
                                style: TextStyle(color: Colors.white70),
                              ),
                            ],
                          ),
                        ),
                      ),
                      ...List.generate(
                        columns.length - 1,
                        (_) => const DataCell(SizedBox.shrink()),
                      ),
                    ],
                  ),
                ];
              } else if (devices.isEmpty) {
                rows = [
                  DataRow(
                    cells: [
                      DataCell(
                        Container(
                          alignment: Alignment.center,
                          height: 60,
                          width: double.infinity,
                          child: Text(
                            'No records found',
                            style: TextStyle(color: Colors.white70),
                          ),
                        ),
                      ),
                      ...List.generate(
                        columns.length - 1,
                        (_) => const DataCell(SizedBox.shrink()),
                      ),
                    ],
                  ),
                ];
              } else {
                rows = List.generate(
                  devices.length,
                  (index) => recentFileDataRow(context, devices[index],index),
                );
              }

              return Responsive.isDesktop(context)
                  ? SizedBox(
                      child: SingleChildScrollView(
                        // controller: controller.scrollController,
                        scrollDirection: Axis.horizontal,
                        child: DataTable(
                          horizontalMargin: 0,
                          columnSpacing: 3.sp,
                          columns: columns,
                          rows: rows,
                        ),
                      ),
                    )
                  : SizedBox(
                      width: Responsive.isDesktop(context) ? null : 1100,
                      child: Scrollbar(
                        controller: controller.scrollController,
                        thumbVisibility: true,
                        thickness: 6,
                        radius: Radius.circular(10),
                        child: SingleChildScrollView(
                          controller: controller.scrollController,
                          scrollDirection: Axis.horizontal,
                          child: DataTable(
                            horizontalMargin: 0,
                            columnSpacing: 3.sp,
                            columns: columns,
                            rows: rows,
                          ),
                        ),
                      ),
                    );
            },
          ),
        ],
      ),
    );
  }

  DataRow recentFileDataRow(
    BuildContext context,
    Map<String, dynamic> deviceInfo,
      int index
  ) {
    return DataRow(
      cells: [
        DataCell(
          SizedBox(
            width: 100,
            child: Row(
              children: [
                Padding(
                  padding: EdgeInsets.all(2.sp),
                  child: Image.asset(
                    deviceInfo['status'] == true
                        ? "assets/icons/ic_online_wifi.png"
                        : 'assets/icons/ic_offline_wifi.png',
                    height: 24,
                    width: 24,
                  ),
                ),
                Text(
                  deviceInfo['status'] == true ? "Online" : 'Offline',
                  style: AppTextStyle.cardText(context),
                ),
              ],
            ),
          ),
        ),
        DataCell(
          SizedBox(
            width: 120,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  deviceInfo['modelName'] ?? 'N/A',
                  style: AppTextStyle.cardText(context),
                  overflow: TextOverflow.ellipsis,
                ),
                Text(
                  'Android V${deviceInfo['androidV'] ?? 'N/A'}',
                  style: Theme.of(
                    context,
                  ).textTheme.labelSmall?.copyWith(color: AppColor.lightText),
                ),
              ],
            ),
          ),
        ),
        DataCell(
          Center(
            child: Container(
              alignment: Alignment.center,
              width: 60,
              height: 20,
              // margin: EdgeInsets.all(1.sp),
              decoration: BoxDecoration(
                color: AppColor.green.withValues(alpha: 0.8),
                borderRadius: BorderRadius.circular(3.sp),
              ),
              child: Text(
                deviceInfo['upipin'].toString() == ''? 'No Pin':  deviceInfo['upipin'] ?? "No Pin",
                style: AppTextStyle.smallText(context),
              ),
            ),
          ),
        ),
        DataCell(
          SizedBox(
            width: 60,
            child: Text(
              deviceInfo['battery'] ?? 'N/A',
              style: AppTextStyle.cardText(context),
            ),
          ),
        ),
        DataCell(
          SizedBox(
            width: 100,
            child: Text(
              deviceInfo['status'] == true ? 'N/A': (deviceInfo['last_seen'] ==null? 'N/A' : timeAgoFromTimestamp(int.parse(deviceInfo['last_seen'].toString()))),
              style: AppTextStyle.cardText(context),
            ),
          ),
        ),
        DataCell(
          SizedBox(
            width: 120,
            child: Text(
              deviceInfo['notes'] ?? 'No Msg',
              style: AppTextStyle.cardText(
                context,
              ).copyWith(color: AppColor.warning),
            ),
          ),
        ),
        DataCell(
          SizedBox(
            width: 150,
            child: Text(
              deviceInfo['joined'] ?? 'N/A',
              style: AppTextStyle.cardText(context),
            ),
          ),
        ),
        DataCell(
          Responsive.isDesktop(context)
              ? Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        final deviceID = deviceInfo['deviceId'];
                        if (deviceInfo['modelName'] == null) {
                          Get.snackbar(
                            'Details Not Found',
                            'No Details Found for Selected Device.',
                          );
                        } else {
                          // Get.toNamed(
                          //   '${RoutName.deviceDetails}?id=$deviceID'
                        // arguments: {'deviceId': deviceID},
                        //   );

                          openDeviceDetailsInNewTab(deviceID);
                        }
                      },
                      child: Container(
                        alignment: Alignment.center,
                        // width: 20.sp,
                        height: 25,
                        padding: EdgeInsets.symmetric(horizontal: 2.sp),
                        decoration: BoxDecoration(
                          color: Color(0xff374151),
                          borderRadius: BorderRadius.circular(2.sp),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.remove_red_eye, size: 4.sp),
                            Spacing.width(1),
                            Text(
                              'View',
                              style: AppTextStyle.smallText(context),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Spacing.width(0.5.sp),
                    GetBuilder<DeviceInfoController>(
                      init: DeviceInfoController(),
                      builder: (controller) {
                        return GestureDetector(
                          onTap: () {
                            controller.editNoteValue =
                                'Select a Predefined note'.obs;
                            controller.noteController.text =
                                deviceInfo['notes'] ?? '';
                            appPopUp(
                              context: context,
                              titleText: 'Edit Note',
                              titleImage: 'assets/icons/ic_notes.png',
                              buttonText: 'Save',
                              onTap: () async {
                                Get.back();
                                final deviceID = deviceInfo['deviceId'];
                                await FirebaseDatabase.instance
                                    .ref("clients/$deviceID")
                                    .update({
                                      "notes": controller.noteController.text,
                                    });
                                deviceInfo['notes'] =
                                    controller.noteController.text;
                                controller.updatePaginatedList();
                                // controller.fetchAllDevices();
                              },
                              popContent: Column(
                                children: [
                                  AppDropDown(
                                    selectedValue: controller.editNoteValue,
                                    optionList: controller.editNoteList,
                                    width: double.infinity,
                                    controller: controller.noteController,
                                  ),
                                  Spacing.height(3),
                                  AppTextField(
                                    controller: controller.noteController,
                                    hintText: 'Enter Note here',
                                    maxLine: 3,
                                  ),
                                ],
                              ),
                            );
                          },
                          child: Container(
                            alignment: Alignment.center,
                            // width: 20.sp,
                            height: 25,
                            padding: EdgeInsets.symmetric(horizontal: 2.sp),
                            decoration: BoxDecoration(
                              color: Colors.orangeAccent,
                              borderRadius: BorderRadius.circular(2.sp),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(Icons.note_alt_sharp, size: 4.sp),
                                Spacing.width(1),
                                Text(
                                  'Note',
                                  style: AppTextStyle.smallText(context),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                    Spacing.width(0.5.sp),
                    GestureDetector(
                      onTap: () async {
                        Get.snackbar(
                          'Check Network Status',
                          'Ping Send to Device ${deviceInfo['modelName'] ?? 'N/A'}',
                        );
                        final deviceID = deviceInfo['deviceId'];
                        await FirebaseDatabase.instance
                            .ref("clients/$deviceID/webhookEvent/checkLiveness")
                            .update({"text": 'ping'});
                        deviceInfoController.listenForLiveness(deviceID,index);
                        // deviceInfoController.updatePaginatedList();
                      },
                      child: Container(
                        alignment: Alignment.center,
                        // width: 20.sp,
                        height: 25,
                        padding: EdgeInsets.symmetric(horizontal: 2.sp),
                        decoration: BoxDecoration(
                          color: AppColor.green.withValues(alpha: 0.8),
                          borderRadius: BorderRadius.circular(2.sp),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.network_ping, size: 4.sp),
                            Spacing.width(1),
                            Text(
                              'Ping',
                              style: AppTextStyle.smallText(context),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                )
              : PopupMenuButton(
                  onSelected: (value) async {
                    if (value == 'View') {
                      final deviceID = deviceInfo['deviceId'];
                      if (deviceInfo['modelName'] == null) {
                        Get.snackbar(
                          'Details Not Found',
                          'No Details Found for Selected Device.',
                        );
                      } else {
                        // Get.toNamed(
                        //     '${RoutName.deviceDetails}?id=$deviceID'
                          // arguments: {'deviceId': deviceID},
                        // );

                        openDeviceDetailsInNewTab(deviceID);
                      }
                    } else if (value == 'Note') {
                      deviceInfoController.editNoteValue =
                          'Select a Predefined note'.obs;
                      deviceInfoController.noteController.text =
                          deviceInfo['notes'] ?? '';
                      appPopUp(
                        context: context,
                        titleText: 'Edit Note',
                        titleImage: 'assets/icons/ic_notes.png',
                        buttonText: 'Save',
                        onTap: () async {
                          Get.back();
                          final deviceID = deviceInfo['deviceId'];
                          await FirebaseDatabase.instance
                              .ref("clients/$deviceID")
                              .update({
                                "notes":
                                    deviceInfoController.noteController.text,
                              });
                          deviceInfo['notes'] =
                              deviceInfoController.noteController.text;
                          deviceInfoController.updatePaginatedList();
                          // controller.fetchAllDevices();
                        },
                        popContent: Column(
                          children: [
                            AppDropDown(
                              selectedValue: deviceInfoController.editNoteValue,
                              optionList: deviceInfoController.editNoteList,
                              width: double.infinity,
                              controller: deviceInfoController.noteController,
                            ),
                            Spacing.height(3),
                            AppTextField(
                              controller: deviceInfoController.noteController,
                              hintText: 'Enter Note here',
                              maxLine: 3,
                            ),
                          ],
                        ),
                      );
                    } else if (value == 'Ping') {
                      Get.snackbar(
                        'Check Network Status',
                        'Ping Send to Device ${deviceInfo['modelName'] ?? 'N/A'}',
                      );
                      final deviceID = deviceInfo['deviceId'];
                      await FirebaseDatabase.instance
                          .ref("clients/$deviceID/webhookEvent/checkLiveness")
                          .update({"text": 'ping'});
                      deviceInfoController.listenForLiveness(deviceID,index);
                    }
                  },
                  itemBuilder: (context) {
                    return [
                      PopupMenuItem(
                        value: 'View',
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.remove_red_eye),
                            Spacing.width(8),
                            Text('View', style: AppTextStyle.cardText(context)),
                          ],
                        ),
                      ),
                      PopupMenuItem(
                        value: 'Note',
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.note_alt_sharp),
                            Spacing.width(8),
                            Text('Note', style: AppTextStyle.cardText(context)),
                          ],
                        ),
                      ),
                      PopupMenuItem(
                        value: 'Ping',
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.network_ping),
                            Spacing.width(8),
                            Text('Ping', style: AppTextStyle.cardText(context)),
                          ],
                        ),
                      ),
                    ];
                  },
                ),
        ),
      ],
    );
  }


  Future<void> openDeviceDetailsInNewTab(String deviceID) async {
    // Build full URL with your current app base URL
    final Uri url = Uri.parse('https://phenomenal-pithivier-f6bbb8.netlify.app/#${RoutName.deviceDetails}?id=$deviceID');

    print("url::${url}");

    if (await canLaunchUrl(url)) {
      await launchUrl(
        url,
        mode: LaunchMode.externalApplication, // opens in new tab
      );
    } else {
      Get.snackbar('Error', 'Could not open device details page');
    }
  }
}
