import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

import '../../utils/auth_utils.dart';

class MiscellaneousListWidget extends StatefulWidget {
  final List<Map<String, dynamic>> miscellaneousList;
  final Function(bool, Map<String, dynamic>, String) onOpen;
  final Function(Map<String, dynamic>) onDeleteMiscellaneous;
  final Map<String, dynamic>? apiData;
  final Function(String, bool) onAddNew;
  final bool isViewMode;

  const MiscellaneousListWidget({
    super.key,
    required this.miscellaneousList,
    required this.onOpen,
    required this.onDeleteMiscellaneous,
    required this.apiData,
    required this.onAddNew,
    required this.isViewMode,
  });

  @override
  State<MiscellaneousListWidget> createState() =>
      _MiscellaneousListWidgetState();
}

class _MiscellaneousListWidgetState extends State<MiscellaneousListWidget> {
  Color? layoutColor;
  Color? secondColor;
  Color? thridColor;
  bool orgHasService = false;

  @override
  void initState() {
    super.initState();
    loadInitialData();
    getOrgServices();
  }

  void getOrgServices() async {
    final services = await getOrgServicesName();
    print("getOrgServices storage: $services");

    // just names
    final names = services.map((s) => s['name']).toList();
    print("Names only: $names");
    final hasFlight = names.contains("Miscellaneous");

    setState(() {
      orgHasService = hasFlight;
    });

    print("orgHasService: $orgHasService");
  }

  void loadInitialData() async {
    String? layoutString = await getLayoutColor();
    String? secondString = await getSecondaryColor();
    String? thridString = await getTernaryColor();

    // String? bodyStringColor = await getBodyColor();

    setState(() {
      layoutColor =
          layoutString != null
              ? Color(int.parse(layoutString))
              : Colors.redAccent;

      secondColor =
          layoutString != null
              ? Color(int.parse(secondString!))
              : Colors.orange;

      thridColor =
          layoutString != null
              ? Color(int.parse(thridString!))
              : Colors.orangeAccent;
      // bodyColor =
      // bodyStringColor != null
      //     ? Color(int.parse(bodyStringColor))
      //     : Colors.white;
    });
  }

  @override
  Widget build(BuildContext context) {
    final isDesktop = MediaQuery.of(context).size.width > 1024;

    return Padding(
      padding:
          isDesktop ? const EdgeInsets.all(16.0) : const EdgeInsets.all(5.0),
      child: Container(
        margin: const EdgeInsets.only(top: 16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Header with title and button
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                if ((!isDesktop) && widget.miscellaneousList.isNotEmpty)
                  Text(
                    " ",
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),

                if (orgHasService && widget.miscellaneousList.isNotEmpty)
                  MouseRegion(
                    cursor:
                        widget.isViewMode
                            ? SystemMouseCursors.forbidden
                            : SystemMouseCursors.click,
                    child: GestureDetector(
                      onTap:
                          widget.isViewMode
                              ? null
                              : () {
                                print("New data");
                                widget.onAddNew("Miscellaneous", true);
                              },
                      child: Row(
                        mainAxisSize:
                            MainAxisSize.min, // Ensures content fits nicely
                        children: [
                          // Text(
                          //   "Add New",
                          //   style: TextStyle(fontSize: 13),
                          // ),
                          // SizedBox(width: 8), // spacing between icon and text
                          Icon(
                            Icons.add_circle_sharp,
                            size: 30,
                            color: Color(0xFF114D8B),
                          ),
                          // Container(
                          //   decoration: BoxDecoration(
                          //     shape: BoxShape.circle,
                          //     border: Border.all(
                          //       color: Color(0xFF114D8B), // Outline color
                          //       width: 2, // Outline thickness
                          //     ),
                          //   ),
                          //   height: 30,
                          //   width: 30,
                          //   child: Center(
                          //     child: Icon(
                          //       Icons.add,
                          //       size: 20,
                          //       color: Colors.black,
                          //     ),
                          //   ),
                          // ),
                        ],
                      ),
                    ),
                    // child: ElevatedButton(
                    //   style: ElevatedButton.styleFrom(
                    //     backgroundColor: Color(0xFF114D8B),
                    //     foregroundColor: Colors.white,
                    //     disabledBackgroundColor: Color(0xFF114D8B),
                    //     disabledForegroundColor: Colors.white,
                    //     shape: RoundedRectangleBorder(
                    //       borderRadius: BorderRadius.circular(8),
                    //       side: BorderSide(color: Color(0xFF114D8B), width: 2),
                    //     ),
                    //     padding:
                    //         EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                    //   ),
                    //   onPressed: isViewMode
                    //       ? null
                    //       : () {
                    //           onAddNew("Miscellaneous", true);
                    //         },
                    //   child: Row(
                    //     mainAxisSize: MainAxisSize.min,
                    //     children: [
                    //       Icon(
                    //         Icons.add_circle_sharp,
                    //         size: 30,
                    //         color: Color(0xFF114D8B),
                    //       )
                    //     ],
                    //   ),
                    // ),
                  ),
              ],
            ),
            const SizedBox(height: 16),
            // Scroll behavior based on device
            _buildData(context, isDesktop),
          ],
        ),
      ),
    );
  }

  Widget _buildData(BuildContext context, bool isDesktop) {
    List<Map<String, dynamic>> filteredList =
        widget.miscellaneousList
            .where((item) => item["is_active"] == "1")
            .toList();

    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: filteredList.length,
      itemBuilder: (context, index) {
        final item = filteredList[index];

        String getRequestValue(String? specialRequestKey) {
          if (specialRequestKey == null) return "N/A";
          return (widget.apiData?['miscellaneous_special_request'] ?? [])
              .firstWhere(
                (element) =>
                    element["dropdown_key"].toString() == specialRequestKey,
                orElse: () => {"dropdown_value": "N/A"},
              )["dropdown_value"]
              .toString();
        }

        return Container(
          margin: EdgeInsets.symmetric(horizontal: 8, vertical: 6),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            // color: Colors.yellow.shade50,
            color: isDesktop ? Colors.white : thridColor,
            boxShadow:
                isDesktop
                    ? [
                      BoxShadow(
                        color: Colors.black12,
                        blurRadius: 3,
                        offset: Offset(0, 1),
                      ),
                    ]
                    : [],
            border: Border(
              top: BorderSide(
                color: Colors.white70, // Change color to match your theme
                width: 2,
              ),
            ),
          ),
          child: Padding(
            padding: isDesktop ? EdgeInsets.all(12) : EdgeInsets.all(8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(
                      getRequestValue(item["special_request"]?.toString()),
                      style: GoogleFonts.poppins(
                        fontSize: 14,
                        fontWeight:
                            isDesktop ? FontWeight.w800 : FontWeight.w600,
                        color: !isDesktop ? Colors.black : Color(0xFF575A74),
                      ),
                    ),
                    Spacer(),
                    if (orgHasService) ...[
                      GestureDetector(
                        onTap: () => widget.onOpen(true, item, "Miscellaneous"),
                        child: Tooltip(
                          message: 'Edit Miscellaneous Details',
                          child: Image.asset(
                            'assets/images/IconsImg/edit.png',
                            width: 20,
                            height: 15,
                            color: isDesktop ? Color(0xFF114D8B) : Colors.black,
                          ),
                        ),
                      ),
                      SizedBox(width: 10),
                      GestureDetector(
                        // onTap: () => onOpen(true, item, "Miscellaneous"),
                        onTap: () => widget.onDeleteMiscellaneous(item),
                        child: Tooltip(
                          message: 'Delete Miscellaneous Details',
                          child: Image.asset(
                            'assets/images/IconsImg/delete.png',
                            width: 20,
                            height: 15,
                            color: Colors.red,
                          ),
                        ),
                      ),
                    ],
                  ],
                ),
                // Divider(color: Colors.blueGrey.shade50),
                SizedBox(height: 4),
                isDesktop
                    ? Row(
                      children: [
                        Expanded(
                          flex: 2,
                          child: Text(
                            "Special Request",
                            style: GoogleFonts.poppins(fontSize: 11),
                          ),
                        ),
                        Expanded(
                          flex: 3,
                          child: Text(
                            " Comments",
                            style: GoogleFonts.poppins(fontSize: 11),
                          ),
                        ),
                      ],
                    )
                    : SizedBox.shrink(),
                SizedBox(height: 8),
                isDesktop
                    ? Row(
                      children: [
                        Expanded(
                          flex: 2,
                          child: Text(
                            getRequestValue(
                              item["special_request"]?.toString(),
                            ),
                            style: GoogleFonts.poppins(
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 3,
                          child: Text(
                            item["comments"],
                            style: GoogleFonts.poppins(
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ],
                    )
                    : Container(
                      color: Colors.white,
                      padding: const EdgeInsets.all(4.0),
                      child: Column(
                        children: [
                          // _buildRow(
                          //   "Special Request",
                          //   getRequestValue(item["special_request"]?.toString()),
                          // ),
                          SizedBox(width: 10),
                          _buildRow("Comments", item["comments"] ?? "N/A"),
                        ],
                      ),
                    ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildComments(String title, String value) {
    // Define character limits based on title
    Map<String, int> limits = {
      // "Special Request:": 30,
      "Comments:": 40,
      // Add more keys and limits if needed
    };

    int limit = limits[title] ?? 50; // Default limit if title not found
    bool exceedsLimit = value.length > limit;

    String wrapText(String text, int maxLineLength) {
      final pattern = RegExp('.{1,$maxLineLength}(\\s+|\$)');
      return pattern.allMatches(text).map((m) => m.group(0)!).join('\n');
    }

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          child:
              exceedsLimit
                  ? Tooltip(
                    message: wrapText(value, 50),
                    decoration: BoxDecoration(
                      color: Colors.grey.shade200, // Black background
                      borderRadius: BorderRadius.circular(6),
                    ),
                    textStyle: TextStyle(
                      color: Colors.black,
                    ), // Tooltip text color
                    padding: EdgeInsets.all(8),
                    preferBelow: false,
                    child: Text(
                      value.substring(0, limit) + "...",
                      style: GoogleFonts.poppins(
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  )
                  : Text(
                    value,
                    style: GoogleFonts.poppins(
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
        ),
      ],
    );
  }

  Widget _buildRow(String title, String value) {
    // Define character limits based on title
    Map<String, int> limits = {
      "Special Request:": 30,
      "Comments:": 70,
      // Add more keys and limits if needed
    };

    int limit = limits[title] ?? 50; // Default limit if title not found
    bool exceedsLimit = value.length > limit;

    String wrapText(String text, int maxLineLength) {
      final pattern = RegExp('.{1,$maxLineLength}(\\s+|\$)');
      return pattern.allMatches(text).map((m) => m.group(0)!).join('\n');
    }

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 100,
          child: Text(
            title,
            style: GoogleFonts.poppins(
              fontSize: 12,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
        SizedBox(width: 8),
        Expanded(
          child:
              exceedsLimit
                  ? Tooltip(
                    message: wrapText(value, 50),
                    decoration: BoxDecoration(
                      color: Colors.grey.shade200, // Black background
                      borderRadius: BorderRadius.circular(6),
                    ),
                    textStyle: TextStyle(
                      color: Colors.black,
                      fontSize: 12,
                    ), // Tooltip text color
                    padding: EdgeInsets.all(8),
                    preferBelow: false,
                    child: Text(
                      value.substring(0, limit) + "...",
                      overflow: TextOverflow.ellipsis,
                    ),
                  )
                  : Text(value),
        ),
      ],
    );
  }

  //
  // Widget _buildData(BuildContext context) {
  //   return Container(
  //     width: MediaQuery.of(context).size.width,
  //     child: DataTable(
  //       border: TableBorder(
  //         bottom: BorderSide(color: Colors.black12),
  //         horizontalInside: BorderSide(color: Colors.black12),
  //       ),
  //       columns: const [
  //         DataColumn(label: Text('Special Request')),
  //         DataColumn(label: Text('Comments')),
  //         DataColumn(label: Text('Actions')),
  //       ],
  //       rows: _buildDataRows(),
  //     ),
  //   );
  // }
  //
  // List<DataRow> _buildDataRows() {
  //   List<dynamic> purposeList = apiData?['miscellaneous_special_request'] ?? [];
  //
  //   String getRequestValue(String? specialRequestKey) {
  //     if (specialRequestKey == null) return "N/A";
  //     return purposeList
  //         .firstWhere(
  //           (element) =>
  //               element["dropdown_key"].toString() == specialRequestKey,
  //           orElse: () => {"dropdown_value": "N/A"},
  //         )["dropdown_value"]
  //         .toString();
  //   }
  //
  //   List<Map<String, dynamic>> filteredList =
  //       miscellaneousList.where((item) => item["is_active"] == "1").toList();
  //
  //   return filteredList.asMap().entries.map((entry) {
  //     Map<String, dynamic> item = entry.value;
  //
  //     return DataRow(cells: [
  //       DataCell(Text(getRequestValue(item["special_request"]?.toString()))),
  //       DataCell(Text(item["comments"] ?? "N/A")),
  //       DataCell(Row(
  //         children: [
  //           GestureDetector(
  //             onTap: () => onOpen(true, item, "Miscellaneous"),
  //             child: Image.asset('assets/images/IconsImg/edit.png',
  //                 width: 20, height: 15),
  //           ),
  //           SizedBox(width: 10),
  //           GestureDetector(
  //             onTap: () => onOpen(true, item, "Miscellaneous"),
  //             child: Image.asset('assets/images/IconsImg/delete.png',
  //                 width: 20, height: 15),
  //           ),
  //           IconButton(
  //             icon: Icon(Icons.keyboard_arrow_down_outlined,
  //                 size: 28, color: Color(0xFF475569)),
  //             onPressed: () {
  //               // Expand logic (optional)
  //             },
  //           ),
  //         ],
  //       )),
  //     ]);
  //   }).toList();
  // }
}
