import 'dart:convert';
import 'dart:core';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:frontend/config/apiUrl.dart';
import 'package:intl/intl.dart';
import 'package:responsive_builder/responsive_builder.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

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

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

class _ReportListState extends State<ReportList> {
  final ApiService apiService = ApiService();

  Color? layoutColor;

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

  void loadInitialData() async {
    String? layoutString = await getLayoutColor();
    // String? bodyStringColor = await getBodyColor();

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

  void _checkAuthAndLoadData() async {
    final String? token = await getToken(); // Your async function to get token
    final roleUser = await getRoleUser();
    if (token == null || token.isEmpty) {
      // Token doesn't exist → redirect to login
      context.go(
        "/",
      ); // or use: router.go("/") if you're using `GoRouter` directly
      return;
    }
    print('_checkAuthAndLoadDataSS - $roleUser');

    if (!mounted) return;
    try {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (roleUser != null &&
            (roleUser == 'Org Admin' || roleUser == 'Travel Admin')) {
          loadInitialData();
        } else {
          apiService.logout(context);
        }
      });
    } catch (e) {
      print("service report : $e");
    }
  }

  @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': '/advancePurchase',
        'icon': Icons.trolley,
        'label': 'Advance Purchase Report',
        'description': 'View Advance Purchase Report',
      },
      {
        'value': '/misServicesAnalysis',
        'icon': Icons.miscellaneous_services,
        'label': 'MIS Services Analysis',
        'description': 'View MIS Services Analysis',
      },
      {
        'value': '/misAirReport',
        'icon': Icons.flight,
        'label': 'MIS Air Report',
        'description': 'View MIS Air Report',
      },
      {
        'value': '/misHotelReport',
        'icon': Icons.add_business,
        'label': 'MIS Hotel Report',
        'description': 'View MIS Hotel Report',
      },

      {
        'value': '/misForexReport',
        'icon': Icons.credit_card,
        'label': 'MIS Forex Report',
        'description': 'View MIS Forex Report',
      },
      // {
      //   'value': '/guestHouseReport',
      //   'icon': Icons.home_work,
      //   'label': 'Guest House Report',
      //   'description': 'View Guest House Report',
      // },
    ];

    return Container(
      padding: EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Report List',
            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 {
                                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(),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
