import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

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

import '../../controllers/device_details_controller.dart';
import '../../controllers/device_info_controller.dart';
import '../../responsive.dart';
import '../../utils/App_color.dart';
import '../../widget/app_drop_down.dart';
import '../../widget/app_text_field.dart';
import '../../widget/pop_up.dart';
import '../dashboard/components/search_field.dart';

class MessageTable extends StatelessWidget {
  const MessageTable({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DeviceDetailsController>(
      init: DeviceDetailsController(),
      builder: (controller) {
        return Responsive.isDesktop(context)
            ? SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: childWidget(context, controller),
              )
            : Scrollbar(
                controller: controller.scrollController,
                thumbVisibility: true,
                // Always show scrollbar
                thickness: 6,
                // optional: scrollbar thickness
                radius: Radius.circular(10),
                child: SingleChildScrollView(
                  controller: controller.scrollController,
                  scrollDirection: Axis.horizontal,
                  child: childWidget(context, controller),
                ),
              );
      },
    );
  }

  Widget childWidget(BuildContext context, DeviceDetailsController controller) {
    return Container(
      width: Responsive.isDesktop(context)
          ? MediaQuery.of(context).size.width - 14.sp
          : 1200,

      padding: EdgeInsets.symmetric(vertical: 2.sp, horizontal: 5.sp),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: AppColor.secondaryColor,
        borderRadius: BorderRadius.circular(4),
        // border: Border.all(color: Colors.grey.shade700),
      ),
      child: GetX<DeviceDetailsController>(
        init: DeviceDetailsController(),
        builder: (controller) {
          //  controller.filteredMessages;
          // final isLoading = controller.isLoading;

          // Define columns once
          final columns = [
            DataColumn(label: Text('#')),
            DataColumn(label: Text('Type')),
            DataColumn(label: Text('Sender')),
            DataColumn(label: Text('Message')),
            DataColumn(
              label: SizedBox(
                width: 100,
                child: GestureDetector(
                  onTap: () {
                    controller.filteredMessages.value = controller
                        .filteredMessages
                        .reversed
                        .toList();
                    controller.filteredMessages.refresh();
                  },
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text('Date Time'),
                      SizedBox(width: 5),
                      Icon(Icons.sort, color: Colors.white, size: 16),
                    ],
                  ),
                ),
              ),
            ),
          ];

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

          if (controller.isLoading.isTrue) {
            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 (controller.filteredMessages.isEmpty) {
            rows = [
              DataRow(
                cells: [
                  DataCell(
                    Container(
                      alignment: Alignment.center,
                      height: 60,
                      width: double.infinity,
                      child: Text(
                        'No Message found',
                        style: TextStyle(color: Colors.white70),
                      ),
                    ),
                  ),
                  ...List.generate(
                    columns.length - 1,
                    (_) => const DataCell(SizedBox.shrink()),
                  ),
                ],
              ),
            ];
          } else {
            rows = List.generate(
              controller.pageSize.value < 20 ||
                      controller.filteredMessages.length <
                          controller.pageSize.value
                  ? controller.filteredMessages.length
                  : controller.pageSize.value,
              (index) => DataRow(
                cells: [
                  DataCell(
                    Text(
                      '${index + 1}',
                      // controller.filteredMessages[index]['id'].toString() ??
                      //     'N/A',
                      style: Theme.of(context).textTheme.titleSmall,
                    ),
                  ),
                  DataCell(
                    Text(
                      controller.filteredMessages[index]['type'] ?? 'N/A',
                      style: Theme.of(context).textTheme.titleSmall?.copyWith(
                        color:
                            controller.filteredMessages[index]['type'] ==
                                'incoming'
                            ? AppColor.red
                            : AppColor.green,
                      ),
                    ),
                  ),
                  DataCell(
                    Text(
                      controller.filteredMessages[index]['sender'] ?? 'N/A',
                      style: Theme.of(
                        context,
                      ).textTheme.titleSmall?.copyWith(color: Colors.white),
                    ),
                  ),
                  DataCell(
                    SizedBox(
                      width: Responsive.isDesktop(context) ? null : 700,
                      child: Text(
                        controller.filteredMessages[index]['message'] ?? 'N/A',
                        style: Theme.of(context).textTheme.labelSmall?.copyWith(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),
                  DataCell(
                    SizedBox(
                      width: 100,
                      child: Text(
                        controller.filteredMessages[index]['dateTime'] ?? 'N/A',
                        style: Theme.of(context).textTheme.titleSmall,
                      ),
                    ),
                  ),
                ],
              ),
            );
          }
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    'Messages',
                    style: Theme.of(context).textTheme.titleLarge,
                  ),
                  Spacer(),
                  GestureDetector(
                    onTap: () {
                      controller.messageController.clear();
                      controller.toNumber.clear();
                      appPopUp(
                        context: context,
                        titleText: 'Send SMS',
                        titleImage: 'assets/icons/ic_send_sms.png',
                        buttonText: 'Send',
                        onTap: () {
                          Get.back();
                          if (controller.singleDeviceDetails['status'] ==
                              true) {
                            controller.sendSMS();
                            Get.snackbar(
                              'Send SMS',
                              'Message send successfully to ${controller.toNumber.text}',
                            );
                          } else {
                            Get.snackbar(
                              'Message Not Send',
                              'Device is offline.',
                            );
                          }
                        },
                        popContent: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              spacing: 2.sp,
                              children: [
                                Image.asset(
                                  'assets/icons/ic_call.png',
                                  height: 20,
                                  width: 20,
                                ),
                                Text(
                                  'Recipient Number',
                                  style: Theme.of(context).textTheme.labelLarge,
                                ),
                              ],
                            ),
                            Spacing.height(1),
                            AppTextField(
                              controller: controller.toNumber,
                              hintText: '+91...  ',
                              maxLine: 1,
                            ),
                            Spacing.height(4),
                            Row(
                              spacing: 2.sp,
                              children: [
                                Image.asset(
                                  'assets/icons/ic_message.png',
                                  height: 20,
                                  width: 20,
                                ),
                                Text(
                                  'Message',
                                  style: Theme.of(context).textTheme.labelLarge,
                                ),
                              ],
                            ),
                            Spacing.height(1),
                            AppTextField(
                              controller: controller.messageController,
                              hintText: 'Type your message....',
                              maxLine: 3,
                            ),
                            Spacing.height(4),
                            Row(
                              spacing: 2.sp,
                              children: [
                                Image.asset(
                                  'assets/icons/ic_simCard.png',
                                  height: 20,
                                  width: 20,
                                ),
                                Text(
                                  'Select SIM',
                                  style: Theme.of(context).textTheme.labelLarge,
                                ),
                              ],
                            ),
                            Spacing.height(1),
                            AppDropDown(
                              selectedValue: controller.simValue,
                              optionList: controller.simList,
                              width: double.infinity,
                            ),
                            Spacing.height(3),
                          ],
                        ),
                      );
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 2.sp,
                        vertical: 1.sp,
                      ),
                      decoration: BoxDecoration(
                        color: AppColor.warning.withValues(alpha: 0.8),
                        borderRadius: BorderRadius.circular(2.sp),
                      ),
                      child: Row(
                        spacing: 2.sp,
                        children: [
                          Image.asset(
                            'assets/icons/ic_send_sms.png',
                            height: 20,
                            width: 20,
                          ),
                          Text(
                            'Send SMS',
                            style: Theme.of(context).textTheme.bodyMedium
                                ?.copyWith(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w500,
                                ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Spacing.width(3),
                  GestureDetector(
                    onTap: () {
                      Get.snackbar(
                        'Under Development',
                        'This Feature is under development.',
                      );

                      // appPopUp(
                      //   context: context,
                      //   titleText: 'SMS Forwarder',
                      //   titleImage: 'assets/icons/ic_forward_sms.png',
                      //   buttonText: 'Send',
                      //   onTap: () {},
                      //   popContent: Column(
                      //     crossAxisAlignment: CrossAxisAlignment.start,
                      //     children: [
                      //       Row(
                      //         spacing: 2.sp,
                      //         children: [
                      //           Image.asset(
                      //             'assets/icons/ic_call.png',
                      //             height: 20,
                      //             width: 20,
                      //           ),
                      //           Text(
                      //             'Forwarder Number',
                      //             style: Theme.of(context).textTheme.labelLarge,
                      //           ),
                      //         ],
                      //       ),
                      //       Spacing.height(1),
                      //       AppTextField(
                      //         controller: TextEditingController(),
                      //         hintText: '+91...  ',
                      //         maxLine: 1,
                      //       ),
                      //       Spacing.height(4),
                      //
                      //       Row(
                      //         spacing: 2.sp,
                      //         children: [
                      //           Image.asset(
                      //             'assets/icons/ic_setting.png',
                      //             height: 20,
                      //             width: 20,
                      //           ),
                      //           Text(
                      //             'Status',
                      //             style: Theme.of(context).textTheme.labelLarge,
                      //           ),
                      //         ],
                      //       ),
                      //       Spacing.height(1),
                      //       AppDropDown(
                      //         selectedValue: controller.forwardStatusValue,
                      //         optionList: controller.forwardStatusList,
                      //         width: double.infinity,
                      //       ),
                      //       Spacing.height(3),
                      //     ],
                      //   ),
                      // );
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 2.sp,
                        vertical: 1.sp,
                      ),
                      decoration: BoxDecoration(
                        color: AppColor.green.withValues(alpha: 0.8),
                        borderRadius: BorderRadius.circular(2.sp),
                      ),
                      child: Row(
                        spacing: 2.sp,
                        children: [
                          Image.asset(
                            'assets/icons/ic_forward_sms.png',
                            height: 20,
                            width: 20,
                          ),
                          Text(
                            'Forwarder',
                            style: Theme.of(context).textTheme.bodyMedium
                                ?.copyWith(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w500,
                                ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Spacing.width(3),
                  GestureDetector(
                    onTap: () {
                      Get.snackbar(
                        'Under Development',
                        'This Feature is under development.',
                      );
                      // appPopUp(
                      //   context: context,
                      //   titleText: 'Call Forwarding',
                      //   titleImage: 'assets/icons/ic_call.png',
                      //   buttonText: 'Send',
                      //   onTap: () {},
                      //   popContent: Column(
                      //     crossAxisAlignment: CrossAxisAlignment.start,
                      //     children: [
                      //       Container(
                      //         padding: EdgeInsets.symmetric(
                      //           horizontal: 12,
                      //           vertical: 10,
                      //         ),
                      //         decoration: BoxDecoration(
                      //           color: AppColor.secondaryColor,
                      //           borderRadius: BorderRadius.circular(2.sp),
                      //           border: Border.all(color: Colors.grey.shade700),
                      //         ),
                      //         child: Column(
                      //           children: [
                      //             Text(
                      //               'Current Info',
                      //               style: Theme.of(context)
                      //                   .textTheme
                      //                   .labelLarge
                      //                   ?.copyWith(fontWeight: FontWeight.w600),
                      //             ),
                      //             Spacing.height(1),
                      //             Row(
                      //               children: [
                      //                 Text(
                      //                   'Status: ',
                      //                   style: Theme.of(context)
                      //                       .textTheme
                      //                       .labelLarge
                      //                       ?.copyWith(
                      //                         fontWeight: FontWeight.w600,
                      //                       ),
                      //                 ),
                      //                 Text(
                      //                   'Disable',
                      //                   style: Theme.of(context)
                      //                       .textTheme
                      //                       .labelLarge
                      //                       ?.copyWith(
                      //                         color: AppColor.red,
                      //                         fontWeight: FontWeight.w500,
                      //                       ),
                      //                 ),
                      //               ],
                      //             ),
                      //             Spacing.height(1),
                      //             Row(
                      //               children: [
                      //                 Text(
                      //                   'Number: ',
                      //                   style: Theme.of(context)
                      //                       .textTheme
                      //                       .labelLarge
                      //                       ?.copyWith(
                      //                         fontWeight: FontWeight.w600,
                      //                       ),
                      //                 ),
                      //                 Text(
                      //                   'N/A',
                      //                   style: Theme.of(context)
                      //                       .textTheme
                      //                       .labelLarge
                      //                       ?.copyWith(
                      //                         fontWeight: FontWeight.w500,
                      //                       ),
                      //                 ),
                      //               ],
                      //             ),
                      //             Spacing.height(1),
                      //             Row(
                      //               children: [
                      //                 Text(
                      //                   'SIM Slot: ',
                      //                   style: Theme.of(context)
                      //                       .textTheme
                      //                       .labelLarge
                      //                       ?.copyWith(
                      //                         fontWeight: FontWeight.w600,
                      //                       ),
                      //                 ),
                      //                 Text(
                      //                   'SIM 1',
                      //                   style: Theme.of(context)
                      //                       .textTheme
                      //                       .labelLarge
                      //                       ?.copyWith(
                      //                         fontWeight: FontWeight.w500,
                      //                       ),
                      //                 ),
                      //               ],
                      //             ),
                      //           ],
                      //         ),
                      //       ),
                      //       Spacing.height(4),
                      //       Row(
                      //         spacing: 2.sp,
                      //         children: [
                      //           Image.asset(
                      //             'assets/icons/ic_simCard.png',
                      //             height: 20,
                      //             width: 20,
                      //           ),
                      //           Text(
                      //             'Select SIM',
                      //             style: Theme.of(context).textTheme.labelLarge,
                      //           ),
                      //         ],
                      //       ),
                      //       Spacing.height(1),
                      //       AppDropDown(
                      //         selectedValue: controller.simValue,
                      //         optionList: controller.simList,
                      //         width: double.infinity,
                      //       ),
                      //       Spacing.height(4),
                      //       Row(
                      //         spacing: 2.sp,
                      //         children: [
                      //           Image.asset(
                      //             'assets/icons/ic_call.png',
                      //             height: 20,
                      //             width: 20,
                      //           ),
                      //           Text(
                      //             'Number to Forward To',
                      //             style: Theme.of(context).textTheme.labelLarge,
                      //           ),
                      //         ],
                      //       ),
                      //       Spacing.height(1),
                      //       AppTextField(
                      //         controller: TextEditingController(),
                      //         hintText: '+91...  ',
                      //         maxLine: 1,
                      //       ),
                      //       Spacing.height(4),
                      //
                      //       Row(
                      //         spacing: 2.sp,
                      //         children: [
                      //           Image.asset(
                      //             'assets/icons/ic_setting.png',
                      //             height: 20,
                      //             width: 20,
                      //           ),
                      //           Text(
                      //             'Status',
                      //             style: Theme.of(context).textTheme.labelLarge,
                      //           ),
                      //         ],
                      //       ),
                      //       Spacing.height(1),
                      //       AppDropDown(
                      //         selectedValue: controller.forwardStatusValue,
                      //         optionList: controller.forwardStatusList,
                      //         width: double.infinity,
                      //       ),
                      //       Spacing.height(3),
                      //     ],
                      //   ),
                      // );
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 2.sp,
                        vertical: 1.sp,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.pinkAccent.withValues(alpha: 0.8),
                        borderRadius: BorderRadius.circular(2.sp),
                      ),
                      child: Row(
                        spacing: 2.sp,
                        children: [
                          Image.asset(
                            'assets/icons/ic_call_forward.png',
                            height: 20,
                            width: 20,
                          ),
                          Text(
                            'Call Forward',
                            style: Theme.of(context).textTheme.bodyMedium
                                ?.copyWith(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w500,
                                ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              Spacing.height(5),
              SearchField(
                onChanged: (value) {
                  controller.searchQuery(value);
                  controller.applyFilters();
                },
              ),

              SizedBox(
                width: double.infinity,
                child: DataTable(
                  horizontalMargin: 0,
                  columnSpacing: 5.w,
                  columns: columns,
                  rows: rows,
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
