import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:responsive_builder/responsive_builder.dart';

import '../services/apiService.dart';
import '../utils/auth_utils.dart';
import 'custom_appBar.dart';
import 'custom_drawer.dart';

class OrganizationSetting extends StatefulWidget {
  const OrganizationSetting({super.key});

  @override
  OrganizationSettingState createState() => OrganizationSettingState();
}

class OrganizationSettingState extends State<OrganizationSetting> {
  final ApiService apiService = ApiService();
  Color? layoutColor;
  Color? secondColor;
  Color? thridColor;

  String? roleUser = "";

  void initState() {
    super.initState();
    loadInitialData();
  }

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

    // String? bodyStringColor = await getBodyColor();
    roleUser = await getRoleUser();

    if (roleUser == 'Org Admin' || roleUser == 'Travel Admin') {
      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;
      });
    } else {
      apiService.logout(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return ResponsiveBuilder(
      builder: (context, sizingInfo) {
        bool isDesktop =
            sizingInfo.deviceScreenType == DeviceScreenType.desktop;

        return Scaffold(
          backgroundColor: Color(0xFFf5f5f5),
          // backgroundColor: Color(0xFFFCFCFC),

          // appBar: isDesktop ? null : const CustomAppBar(title: 'Home'),
          // drawer: isDesktop ? null : CustomDrawer(isDesktop: false),
          appBar: CustomAppBar(isDesktop: isDesktop),
          drawer: CustomDrawer(isDesktop: false),
          body: Padding(
            padding:
                isDesktop
                    ? EdgeInsets.symmetric(
                      horizontal:
                          MediaQuery.of(context).size.width *
                          0.1, // 30% of screen width as horizontal padding
                      vertical:
                          MediaQuery.of(context).size.height *
                          0, // 5% of screen height as vertical padding
                    )
                    : EdgeInsets.all(0),
            child: Row(
              children: [
                // if (isDesktop) CustomDrawer(isDesktop: true),
                Expanded(child: buildGroupListLayout(isDesktop)),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget buildGroupListLayout(bool isDesktop) {
    final int cardsPerRow = 3;

    final List<Map<String, dynamic>> menuItems = [
      {
        'value': '/OrganizationSetup',
        'icon': Icons.business,
        'label': 'Organization Settings',
        'description': 'Edit Logo and Email Configurations',
      },
      {
        'value': '/group',
        'icon': Icons.groups,
        'label': 'Groups',
        'description': 'Create and Edit Groups',
      },
      {
        'value': '/PolicyList',
        'icon': Icons.policy,
        'label': 'Travel Policies',
        'description': 'Create and Edit Travel Policy',
      },
      {
        'value': '/getPerdiem',
        'icon': Icons.attach_money,
        'label': 'Perdiem Amount',
        'description': 'Create and Edit Perdiem Amount',
      },
      {
        'value': '/forexTexmplate',
        'icon': Icons.credit_card,
        'label': 'Forex Documentation',
        'description': 'Edit Document',
      },
      {
        'value': '/templateList',
        'icon': Icons.email_outlined,
        'label': 'Email Templates',
        'description': ' Edit Email Template',
      },
      {
        'value': '/costcenter',
        'icon': Icons.account_balance_wallet,
        'label': 'Cost Center',
        'description': 'Create and Edit Cost Center',
      },
      {
        'value': '/PurposeOfTravel',
        'icon': Icons.mode_of_travel_sharp,
        'label': 'Purpose Of Travel',
        'description': 'Create and Edit Purpose Of Travel',
      },
      {
        'value': '/department',
        // 'icon': Icons.group_add_outlined,
        'icon': Icons.account_tree_rounded,
        'label': 'Functional Department',
        'description': 'Create and Edit Department',
      },
      {
        'value': '/hotels',
        'icon': Icons.add_business,
        'label': 'Hotels',
        'description': 'Create and Edit Hotels',
      },
      {
        'value': '/traveller',
        'icon': Icons.travel_explore,
        'label': 'Traveller (Non Employee)',
        'description': 'Create and Edit Traveller',
      },
      {
        'value': '/listTravelAgent',
        'icon': Icons.person_pin_outlined,
        'label': 'Travel Agents',
        'description': 'Create and Edit Travel Agent',
      },
    ];

    if (roleUser == "Travel Admin") {
      menuItems.removeWhere((item) => item['value'] == '/OrganizationSetup');
    }

    // List<Widget> rows = [];
    // for (int i = 0; i < menuItems.length; i += cardsPerRow) {
    //   List<Widget> cards = [];
    //   for (int j = i; j < i + cardsPerRow && j < menuItems.length; j++) {
    //     final item = menuItems[j];
    //
    //     cards.add(
    //       Expanded(
    //         child: Card(
    //           margin: EdgeInsets.all(8),
    //           color: Colors.white,
    //           child: InkWell(
    //             onTap: () {
    //               // Navigate using go_router
    //               final route = item['value'] as String;
    //               switch (route) {
    //                 case '/OrganizationSetup':
    //                 case '/group':
    //                 case '/department':
    //                 case '/PolicyList':
    //                 case '/getPerdiem':
    //                 case '/templateList':
    //                 case '/costcenter':
    //                 case '/hotels':
    //                 case '/groupDetails' :
    //                   context.go(route);
    //                   break;
    //                 default:
    //                   // Handle unknown routes or do nothing
    //                   print('Unknown route: $route');
    //               }
    //             },
    //             child: Padding(
    //               padding: EdgeInsets.all(12),
    //               child: Row(
    //                 children: [
    //                   Icon(item['icon'], size: 40, color: Color(0xFF114D8B)),
    //                   SizedBox(width: 16),
    //                   Expanded(
    //                     child: Column(
    //                       crossAxisAlignment: CrossAxisAlignment.start,
    //                       mainAxisSize: MainAxisSize.min,
    //                       children: [
    //                         Text(
    //                           item['label'],
    //                           style: GoogleFonts.poppins(
    //                               fontSize: 14, fontWeight: FontWeight.w500),
    //                         ),
    //                         SizedBox(height: 4),
    //                         Text(
    //                           item['description'],
    //                           style: TextStyle(
    //                               fontSize: 14, color: Colors.grey[700]),
    //                         ),
    //                       ],
    //                     ),
    //                   ),
    //                 ],
    //               ),
    //             ),
    //           ),
    //         ),
    //       ),
    //     );
    //   }
    //
    //   rows.add(Row(
    //     crossAxisAlignment: CrossAxisAlignment.start,
    //     children: cards,
    //   ));
    // }

    // return Container(
    //   // color: Colors.white,
    //   padding: EdgeInsets.symmetric(vertical: 16, horizontal: 12),
    //   child: Column(
    //     crossAxisAlignment: CrossAxisAlignment.start,
    //     children: [
    //       Text(
    //         'Organization Settings',
    //         style: GoogleFonts.poppins(
    //           fontSize: 15,
    //           fontWeight: FontWeight.w500,
    //           color: Colors.black87,
    //         ),
    //       ),
    //       SizedBox(height: 8),
    //       Divider(thickness: 0.2, color: Colors.blueGrey.shade100),
    //       SizedBox(height: 12),
    //       ...rows, // Spread operator to insert all row widgets
    //     ],
    //   ),
    // );

    return Container(
      padding: EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Organization Settings',
            style: GoogleFonts.poppins(
              fontSize: 15,
              fontWeight: FontWeight.w500,
              color: Colors.black87,
            ),
          ),
          SizedBox(height: 8),
          Divider(thickness: 0.2, color: Colors.blueGrey.shade100),
          SizedBox(height: 12),
          Expanded(
            child: SingleChildScrollView(
              child: Center(
                child: Wrap(
                  spacing: 16,
                  runSpacing: 16,
                  children:
                      menuItems.map((item) {
                        return SizedBox(
                          width: isDesktop ? 325 : double.infinity,
                          child: Card(
                            color: Colors.white,
                            child: InkWell(
                              onTap: () async {
                                if (item['value'] as String ==
                                    "/forexTexmplate") {
                                  final data =
                                      await apiService.getForexTemplate();
                                  print("ForexId -- $data");

                                  context.go(
                                    '/templateForex',
                                    extra: {'templateData': data},
                                  );
                                } else {
                                  final route = item['value'] as String;
                                  context.go(route);
                                }
                              },
                              child: Padding(
                                padding: EdgeInsets.all(12),
                                child: Row(
                                  children: [
                                    Icon(
                                      item['icon'],
                                      size: 40,
                                      color: layoutColor,
                                      // color: Color(0xFF114D8B),
                                    ),
                                    SizedBox(width: 16),
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          Text(
                                            item['label'],
                                            style: GoogleFonts.poppins(
                                              fontSize: 14,
                                              fontWeight: FontWeight.w500,
                                            ),
                                          ),
                                          SizedBox(height: 4),
                                          Text(
                                            item['description'],
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            softWrap: false,
                                            style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.grey[700],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
