import 'dart:convert';

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 'package:shared_preferences/shared_preferences.dart';

import '../config/apiUrl.dart';
import '../services/apiService.dart';

class CustomDrawer extends StatefulWidget {
  final bool isDesktop;
  const CustomDrawer({super.key, required this.isDesktop});

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

class _CustomDrawerState extends State<CustomDrawer> {
  final ApiService apiService = ApiService();

  String? token;
  Map<String, dynamic>? userData;
  Map<String, dynamic>? fetchedUserData;
  Map<String, dynamic> userDetails = {};

  Map<String, dynamic>? selectedOrg;
  Color? layoutColor;
  Color? bodyColor;

  @override
  void initState() {
    super.initState();
    // initializeData();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      initializeData();
      getOrganizationData();
    });
  }

  Future<void> initializeData() async {
    print("initializeDatainitializeData");
    token = await getToken();
    fetchedUserData = await getUserData();

    if (token == null || fetchedUserData == null) {
      print("Token or USerId missing");
      return;
    }

    setState(() {
      userData = fetchedUserData;
    });
  }

  Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString("auth_token");
  }

  Future<Map<String, dynamic>?> getUserData() async {
    final prefs = await SharedPreferences.getInstance();
    final String? userDataString = prefs.getString('user_data');

    if (userDataString != null) {
      try {
        userDetails = jsonDecode(userDataString);

        return {
          "user_id": userDetails["user_id"].toString(),
          "name": "${userDetails["first_name"]} ${userDetails["last_name"]}",
          "email": userDetails["email"] ?? "",
          "role": userDetails["role"] ?? "",
        };
      } catch (e) {
        print("Error decoding user data: $e");
        return null;
      }
    }
    return null;
  }

  Future<void> getOrganizationData() async {
    try {
      print("getUpdatedServices");

      final prefs = await SharedPreferences.getInstance();
      final String? orgDataString = prefs.getString('org_data');

      if (orgDataString != null) {
        // final result = await apiService.fetchOrganization();

        final Map<String, dynamic> result = jsonDecode(orgDataString);
        print("UUPdatedServices - $result");

        final prefs = await SharedPreferences.getInstance();
        print("UUPdatedServices - $result");

        setState(() {
          selectedOrg = result;

          layoutColor =
              selectedOrg?['layout_color'] != null
                  ? Color(int.parse(selectedOrg!['layout_color']))
                  : Colors.white;

          bodyColor =
              selectedOrg?['color'] != null
                  ? Color(
                    int.parse(
                      selectedOrg!['color'].toString().replaceFirst('0x', ''),
                      radix: 16,
                    ),
                  )
                  : Colors.blue;

          String? rawLogoPath = selectedOrg?['logo'];
          if (rawLogoPath != null && rawLogoPath.contains('/assets')) {
            // const baseUrl = "https://apitest.tripapprovaltool.com";

            const baseUrl = apiUrl;

            final assetPath = rawLogoPath.split('/assets').last;
            selectedOrg!['logo'] = "$baseUrl/assets$assetPath";
          }
        });

        // Save to SharedPreferences
        await prefs.setString('layout_color', selectedOrg?['layout_color']);
        await prefs.setString('secondary_color', selectedOrg?['secondary_color']);
        await prefs.setString('ternary_color', selectedOrg?['ternary_color']);
        await prefs.setString('body_color', selectedOrg?['color']);
        await prefs.setString('body_color', selectedOrg?['plan_action']);

        print(
          "Layout Color- ${selectedOrg?['layout_color']} - $layoutColor ----------  bodyColor - $bodyColor",
        );
      }
    } catch (e) {
      print("Error : $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget drawerContent = Container(
      color: Colors.white,
      child: Container(
        color: Colors.white,
        margin: const EdgeInsets.all(18),
        child: Column(
          children: [
            Container(
              color: Colors.white,
              // margin: const EdgeInsets.only(left: 20),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      selectedOrg?['logo'] != null
                          ? ClipRect(
                            child: Image.network(
                              selectedOrg!['logo'],
                              width: 50,
                              height: 50,
                              fit: BoxFit.contain,
                              errorBuilder: (context, error, stackTrace) {
                                return const CircleAvatar(
                                  radius: 20,
                                  backgroundColor: Colors.redAccent,
                                  child: Icon(Icons.error, size: 10),
                                );
                              },
                            ),
                          )
                          : const CircleAvatar(
                            radius: 20,
                            backgroundColor: Colors.white,
                            child: Icon(
                              Icons.add_a_photo,
                              size: 10,
                              color: Colors.grey,
                            ),
                          ),
                    ],
                  ),
                ],
              ),
            ),

            // _buildDrawerItem(context, Icons.home_outlined, 'Home', '/home'),
            if (userData?["role"] == "Org Admin" ||
                userData?["role"] == "Travel Admin")
              _buildDrawerItem(
                context,
                Icons.dashboard,
                'Dashboard',
                '/StatusDashboard',
              ),

            if (userData?["role"] == "Org Admin" ||
                userData?["role"] == "Travel Admin")
              _buildDrawerItem(
                context,
                Icons.format_list_bulleted_rounded,
                'All Trips',
                '/listAllPlan',
              ),

            if (userDetails["role"] == "Travel Agent")
              _buildDrawerItem(
                context,
                Icons.shopping_bag_outlined,
                'Trips',
                '/listTravelAgentPlan',
              ),

            if (userDetails["role"] != "Travel Agent")
              _buildDrawerItem(
                context,
                Icons.shopping_bag_outlined,
                'My Trips',
                '/listPlan',
              ),

            if (userDetails["role"] != "Travel Agent")
              _buildDrawerItem(
                context,
                Icons.verified_outlined,
                'My Approvals',
                '/ApprovalList',
              ),
            // Spacer(),
            SizedBox(height: MediaQuery.of(context).size.height / 2),
            Container(
              margin: const EdgeInsets.only(right: 20),
              child: Align(
                alignment: Alignment.center,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Column(
                      // mainAxisAlignment: MainAxisAlignment.center,
                      // crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          "Powered by",
                          style: GoogleFonts.poppins(
                            fontSize: 11,
                            color: Colors.grey,
                            // color: Color(0xFF212121),
                          ),
                        ),
                        Image.asset(
                          'assets/images/login/logoNew.jpg',
                          // width: 90,
                          height: 45,
                          fit: BoxFit.contain,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );

    return Container(
      height: MediaQuery.of(context).size.height,
      child: Drawer(
        backgroundColor: Colors.white,
        child: ListView(
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.zero,
          children: [drawerContent],
        ),
      ),
    );

    // if (widget.isDesktop) {
    //   // Sidebar for Desktop (always visible)**
    //   return Container(
    //     width: 250, // Fixed width for sidebar
    //     color: Colors.grey.shade50,
    //     child: drawerContent,
    //   );
    // } else {
    //   // Drawer for Mobile & Tablet**
    //   return Drawer(
    //       child: ListView(padding: EdgeInsets.zero, children: [drawerContent])) ;
    // }
  }

  /// **Reusable Drawer Item**
  Widget _buildDrawerItem(
    BuildContext context,
    IconData icon,
    String title,
    String route,
  ) {
    String selectedRoute = GoRouterState.of(context).uri.toString();

    // return Container(
    //   color: selectedRoute == route ? Colors.blue.shade50 : null,
    //   child: InkWell(
    //     onTap: () async {
    //       if (route == '/') {
    //         final pref = await SharedPreferences.getInstance();
    //         await pref.clear();
    //         context.go("/");
    //       } else {
    //         context.go(route);
    //       }
    //     },
    //     child: Padding(
    //       padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12),
    //       child: Row(
    //         children: [
    //           Icon(
    //             icon,
    //             size: 20,
    //             color: Color(0xFF475569),
    //           ),
    //           // SizedBox(width: 9), // Reduce or increase this for spacing
    //           Text(
    //             title,
    //             style: TextStyle(
    //               fontSize: 14,
    //               fontWeight: FontWeight.w600,
    //               color: Color(0xFF475569),
    //               fontFamily: "Archivo",
    //             ),
    //           ),
    //         ],
    //       ),
    //     ),
    //   ),
    // );

    return Material(
      color: selectedRoute == route ? bodyColor : Colors.transparent,
      child: ListTile(
        leading: Icon(icon, size: 20),
        title: Text(
          title,

          style: GoogleFonts.poppins(
            fontSize: 12,
            fontWeight: FontWeight.w600,
            color: Color(0xFF475569),
          ),
          // style: TextStyle(
          //     fontSize: 12,
          //     fontWeight: FontWeight.w600,
          //     color: Color(0xFF475569),
          //     fontFamily: "Archivo"),
        ),

        // tileColor: selectedRoute == route ? Colors.blue.shade50 : null,
        onTap: () async {
          if (route == '/') {
            // Handle logout separately
            final pref = await SharedPreferences.getInstance();
            await pref.clear(); // Clear stored token or session data
            context.go("/"); // Redirect to login instead of home
          } else {
            context.go(route);
          }
        },
      ),
    );
  }

  Widget _buildExpandableItem(
    BuildContext context,
    IconData icon,
    String title,
    List<Widget> children,
    String routeToMatch,
  ) {
    String selectedRoute = GoRouterState.of(context).uri.toString();
    return Theme(
      data: Theme.of(context).copyWith(
        dividerColor:
            Colors.transparent, // Removes default ExpansionTile divider
      ),
      child: Material(
        color: selectedRoute == routeToMatch ? bodyColor : Colors.transparent,
        child: ExpansionTile(
          tilePadding: EdgeInsets.symmetric(horizontal: 16),
          // childrenPadding: EdgeInsets.only(left: 36),
          leading: Icon(icon, size: 20, color: Color(0xFF475569)),
          title: Row(
            children: [
              // You could manually build this instead of using `leading`, but it's simpler here
              // SizedBox(width: 8),
              Text(
                title,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF475569),
                  fontFamily: "Archivo",
                ),
              ),
            ],
          ),
          collapsedBackgroundColor: Colors.transparent,
          shape: const Border(),
          children: children,
        ),
      ),
    );
  }

  Widget _buildSubDrawerItem(BuildContext context, String title, String route) {
    String selectedRoute = GoRouterState.of(context).uri.toString();

    return InkWell(
      onTap: () {
        context.go(route);
        if (!widget.isDesktop) Navigator.pop(context);
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 44.0, vertical: 8.0),
        child: Row(
          children: [
            Icon(Icons.circle_rounded, color: Color(0xFF475569), size: 6),
            SizedBox(width: 8),
            Text(
              title,
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w400,
                color: selectedRoute == route ? Colors.blue : Color(0xFF475569),
                fontFamily: "Archivo",
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildExpandableItem1(
    BuildContext context,
    IconData icon,
    String title,
    List<Widget> children,
  ) {
    return ExpansionTile(
      leading: Icon(icon, size: 20),
      title: Text(
        title,
        style: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w600,
          color: Color(0xFF475569),
          fontFamily: "Archivo",
        ),
      ),
      collapsedBackgroundColor: Colors.transparent,
      shape: const Border(), // Removes top and bottom dividers
      // childrenPadding: const EdgeInsets.only(left: 40), // Indent sub-items
      childrenPadding: EdgeInsets.only(left: 24),
      children: children,
    );
  }

  Widget _buildSubDrawerItem1(
    BuildContext context,
    String title,
    String route,
  ) {
    return ListTile(
      leading: Icon(Icons.circle_rounded, color: Color(0xFF475569), size: 8),
      title: Text(
        title,
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w400,
          color: Color(0xFF475569),
          fontFamily: "Archivo",
        ),
      ),
      onTap: () {
        context.go(route);
        if (!widget.isDesktop) Navigator.pop(context);
      },
    );
  }
}
