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

import '../../controllers/device_info_controller.dart';
import '../../controllers/ticket_controller.dart';
import '../../responsive.dart';
import '../../utils/App_color.dart';
import '../../utils/spacing.dart';
import '../../widget/app_drop_down.dart';
import '../../widget/app_text_field.dart';
import '../../widget/pop_up.dart';
import '../dashboard/components/header.dart';

class TicketScreen extends StatelessWidget {
  const TicketScreen({super.key,required this.scaffoldKey});
  final GlobalKey<ScaffoldState> scaffoldKey;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SelectableRegion(
        focusNode: FocusNode(),
        selectionControls: materialTextSelectionControls,
        child: SingleChildScrollView(
          primary: false,
          padding: EdgeInsets.all(16),
          child: GetX<TicketController>(
            init: TicketController(),
            builder: (controller) {


              // Define columns once
              final columns = [
                DataColumn(label: Text('#')),
                DataColumn(label: Text('Priority')),
                DataColumn(label: Text('Subject')),
                DataColumn(label: Text('Message')),
                DataColumn(
                  label: SizedBox(
                    width: 100,
                    child: GestureDetector(
                      onTap: () {
                        controller.ticketList.value =
                            controller.ticketList.reversed.toList();
                        controller.ticketList.refresh();
                      },
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text('Create AT'),
                          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.ticketList.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(
                  controller.ticketList.length,
                      (index) => DataRow(
                        cells: [
                          DataCell(
                            Text(
                              controller.ticketList[index]['id'].toString(),
                              style: Theme.of(context).textTheme.titleSmall,
                            ),
                          ),
                          DataCell(
                            Text(
                              controller.ticketList[index]['priority']??'N/A',
                              style: Theme.of(context).textTheme.titleSmall,
                            ),
                          ),
                          DataCell(
                            Text(
                              controller.ticketList[index]['subject']??'N/A',
                              style: Theme.of(context).textTheme.titleSmall
                                  ?.copyWith(color: Colors.white),
                            ),
                          ),
                          DataCell(
                            SizedBox(
                              width: 700,
                              child: Text(
                                controller.ticketList[index]['message']??'N/A',
                                style: Theme.of(context)
                                    .textTheme
                                    .titleSmall
                                    ?.copyWith(color: Colors.white),
                              ),
                            ),
                          ),
                          DataCell(
                            SizedBox(
                              width: 100,
                              child: Text(
                                DateFormat('dd/MM/yyyy hh:mm:ss a').format(DateTime.parse(controller.ticketList[index]['create_at']??DateTime.now().toString()),),
                               style: Theme.of(
                                  context,
                                ).textTheme.titleSmall,
                              ),
                            ),
                          ),
                        ],
                      ),
                );
              }

              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      if (!Responsive.isMobile(context))
                        Padding(
                          padding: EdgeInsets.only(right: 3.sp),
                          child: Image.asset(
                            'assets/icons/ic_ticket.png',
                            height: 30,
                            width: 30,
                          ),
                        ),

                      Expanded(child: Header(title: 'My Support Tickets',scaffoldKey: scaffoldKey,)),
                      GestureDetector(
                        onTap: () {
                          controller.subjectController.clear();
                          controller.messageController.clear();
                          controller.priorityValue = 'Select priority'.obs;
                          appPopUp(
                            context: context,
                            titleText: 'Create New Ticket',
                            titleImage: 'assets/icons/ic_ticket.png',
                            buttonText: 'Submit',
                            onTap: () {
                              Get.back();
                              controller.createTicket();

                            },
                            popContent: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  'Subject',
                                  style: Theme.of(context).textTheme.labelLarge,
                                ),
                                Spacing.height(1),
                                AppTextField(
                                  controller: controller.subjectController,
                                  hintText: "e.g Can't access dashboard",
                                  maxLine: 1,
                                ),
                                Spacing.height(4),
                                Text(
                                  'Priority',
                                  style: Theme.of(context).textTheme.labelLarge,
                                ),
                                Spacing.height(1),
                                AppDropDown(
                                  selectedValue: controller.priorityValue,
                                  optionList: controller.priorityList,
                                  width: double.infinity,
                                ),

                                Spacing.height(4),
                                Text(
                                  'Message',
                                  style: Theme.of(context).textTheme.labelLarge,
                                ),
                                Spacing.height(1),
                                AppTextField(
                                  controller: controller.messageController,
                                  hintText: "Describe your issue...",
                                  maxLine: 3,
                                ),
                              ],
                            ),
                          );
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            vertical: 1.sp,
                            horizontal: 2.sp,
                          ),
                          decoration: BoxDecoration(
                            color: AppColor.green,
                            borderRadius: BorderRadius.circular(2.sp),
                          ),

                          child: Row(
                            children: [
                              Icon(Icons.add, color: Colors.white),
                              Text(
                                "Create Ticket",
                                style: Theme.of(context).textTheme.bodyMedium,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),

                  // if (!Responsive.isMobile(context))
                  //   Text(
                  //     "Device management",
                  //     style: Theme.of(context).textTheme.titleLarge,
                  //   ),
                  Spacing.height(1),
                  if (!Responsive.isMobile(context))
                    Text(
                      "View and create support ticket",
                      style: Theme.of(context).textTheme.labelSmall?.copyWith(
                        color: AppColor.lightText,
                        fontWeight: FontWeight.w100,
                      ),
                    ),
                  Spacing.height(3),
                  Divider(height: 1, color: AppColor.divider),

                  Responsive.isDesktop(context) ?
                  SizedBox(
                    // width: double.infinity,
                    // width: Responsive.isDesktop(context) ? double.infinity : 1100,
                    child: SingleChildScrollView(
                      // controller: controller.scrollController,

                      scrollDirection: Axis.horizontal,
                      child: DataTable(
                        horizontalMargin: 0,
                        columnSpacing: 5.w,
                        columns: columns,
                        rows: rows
                      ),
                    ),
                  )
                  :
                  SizedBox(
                    // width: double.infinity,
                    width: Responsive.isDesktop(context) ? double.infinity : 1100,
                    child: 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: DataTable(
                          horizontalMargin: 0,
                          columnSpacing: 5.w,
                          columns: columns,
                          rows: rows
                        ),
                      ),
                    ),
                  )

                  ,
                ],
              );
            },
          ),
        ),
      ),
    );
  }
}
