import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:supplier_new/common/settings.dart';
import 'package:supplier_new/common/zoom_image.dart';
import 'package:supplier_new/financials/financial_main_screen.dart';
import 'package:supplier_new/orders/all_orders.dart';
import 'package:supplier_new/orders/order_requests.dart';
import 'package:supplier_new/orders/search_order_appbar.dart';
import 'package:supplier_new/plans/all_plans.dart';
import 'package:supplier_new/plans/calendar.dart';
import 'package:supplier_new/plans/plan_requests.dart';
import 'package:supplier_new/plans/search_plan_appbar.dart';
import 'package:supplier_new/set_rates/set_rates.dart';

import '../login/login.dart';
import '../profile/fleet.dart';
import '../resources/drivers_model.dart';
import '../resources/resources_fleet.dart';
import '../resources/resources_main.dart';
import '../resources/tankers_model.dart';
import '../users/my_users.dart';

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

  @override
  State<DashboardScreen> createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen> {


  int _currentIndex = 0;
  final ImagePicker _picker = ImagePicker();
  final storage = FlutterSecureStorage(
    aOptions: AndroidOptions(
      resetOnError: true,
      encryptedSharedPreferences: true,
    ),
  );
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final TextEditingController orderSearchController = TextEditingController();
  final TextEditingController planSearchController = TextEditingController();
  Widget _getScreen(){

    switch(_currentIndex){

      case 0:
        return HomeScreen();

      case 1:
        return AllOrders(

          navigationFrom: 'bottombar',

          externalSearchController: orderSearchController,

        );

      case 2:
        return AllPlans(

          navigationFrom: 'bottombar',

        );

      case 3:
        return ResourcesMainScreen();

      case 4:
        return FinancialMainScreen();

      default:
        return HomeScreen();

    }

  }

  // Define a list of widgets for each screen
 /* final List<Widget> _screens = [
    HomeScreen(),
    AllOrders(

      navigationFrom: 'bottombar',

      externalSearchController: orderSearchController,

    ),
    AllPlans(navigationFrom: 'bottombar',),
    ResourcesMainScreen(),
    FinancialMainScreen(),
  ];*/

  late List<Widget> _screens;
  // List of bottom navigation bar items
  final List<BottomNavigationBarItem> _bottomNavItems =  [
    BottomNavigationBarItem(
      icon:Padding(
        padding: EdgeInsets.fromLTRB(0,5,0,0), // Adjust height to control spacing
        child:ImageIcon(AssetImage('images/homeBottomIcon.png')),),
      // Replace with your image path

      label: "Home",
    ),
    BottomNavigationBarItem(
      icon: Padding(
        padding: EdgeInsets.fromLTRB(0,5,0,0), // Adjust height to control spacing
        child: ImageIcon(AssetImage('images/ordersBottomIcon.png')),
      ),

      label: "Orders",
    ),
    BottomNavigationBarItem(
      icon: Padding(
        padding: EdgeInsets.fromLTRB(0,5,0,0), // Adjust height to control spacing
        child: ImageIcon(AssetImage('images/plansBottomIcon.png')),
      ), // Replace with your image path

      label: "Plans",
    ),


    BottomNavigationBarItem(
      icon: Padding(
        padding: EdgeInsets.fromLTRB(0,5,0,0), // Adjust height to control spacing
        child:ImageIcon(AssetImage('images/resourcesBottomIcon.png')),),

      // Replace with your image path

      label: "Resources",
    ),
    BottomNavigationBarItem(
      icon:Padding(
        padding: EdgeInsets.fromLTRB(0,5,0,0), // Adjust height to control spacing
        child:ImageIcon(AssetImage('images/financialsBottomIcon.png')),),
      // Replace with your image path

      label: "Financials",
    ),


  ];

  void _onItemTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  Future pickImageFromGallery() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.gallery);
      if (image == null) return;
      final imageTemp = File(image.path);

      AppSettings.preLoaderDialog(context);
      bool isOnline = await AppSettings.internetConnectivity();
      if(isOnline) {
        var res = await AppSettings.uploadrofileImageHTTPNew(image);
        print(jsonDecode(res));
        Navigator.of(context, rootNavigator: true).pop();
        setState(() {
          AppSettings.profilePictureUrl = jsonDecode(res)['picture'];
        });
        AppSettings.saveData('profile', jsonDecode(res)['picture'], 'STRING');
      }
      else{
        Navigator.of(context, rootNavigator: true).pop();
        AppSettings.longFailedToast('Please check interent');
      }
    } on PlatformException catch (e) {
      Navigator.of(context, rootNavigator: true).pop();
      AppSettings.longFailedToast('Failed to pick image: $e');
    }
  }

  Future takeImageFromCamera() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.camera);
      if (image == null) return;
      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);


      bool isOnline = await AppSettings.internetConnectivity();
      if(isOnline){
        var res = await AppSettings.uploadrofileImageHTTPNew(image);
        print(jsonDecode(res));
        Navigator.of(context, rootNavigator: true).pop();
        setState(() {
          AppSettings.profilePictureUrl = jsonDecode(res)['picture'];
        });
        AppSettings.saveData('profile', jsonDecode(res)['picture'], 'STRING');
      }
      else{
        Navigator.of(context, rootNavigator: true).pop();
        AppSettings.longFailedToast('Please check interent');
      }


    } on PlatformException catch (e) {
      Navigator.of(context, rootNavigator: true).pop();
      AppSettings.longFailedToast('Failed to pick image: $e');
    }
  }

  showLogoutAlertDialog(context) {
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
                return AlertDialog(
                    backgroundColor: Color(0XFFFFFFFF),// Set your desired background color
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12), // Optional: Rounded corners
                    ),
                    title: Center(child: Text('Logout?',style:fontTextStyle(16,Color(0XFF101214),FontWeight.w700)),),
                    actions: <Widget>[
                      Center(
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Expanded(child: GestureDetector(
                              onTap: (){
                                Navigator.of(context).pop();
                              },
                              child: Container(
                                decoration: BoxDecoration(
                                    shape: BoxShape.rectangle,
                                    color: Color(0XFFFFFFFF),
                                    border: Border.all(
                                        width: 1,
                                        color: Color(0XFF1D7AFC)),
                                    borderRadius: BorderRadius.circular(
                                      12,
                                    )),
                                alignment: Alignment.center,
                                child: Visibility(
                                  visible: true,
                                  child: Padding(
                                    padding: EdgeInsets.fromLTRB(16,12,16,12),
                                    child: Text(
                                        'Cancel',
                                        style: fontTextStyle(
                                            12,
                                            Color(0XFF1D7AFC),
                                            FontWeight.w600)),
                                  ),
                                ),
                              ),
                            ),),
                            SizedBox(width:MediaQuery.of(context).size.width * .016,),
                            Expanded(child: GestureDetector(
                                onTap: ()async{
                                  await storage.deleteAll();
                                  await Navigator.pushAndRemoveUntil(
                                    context,
                                    MaterialPageRoute(builder: (context) => Login()),
                                        (Route<dynamic> route) => false,
                                  );
                                },
                                child: Container(
                                  decoration: BoxDecoration(
                                      shape: BoxShape.rectangle,
                                      color: Color(0XFFE2483D),
                                      border: Border.all(
                                          width: 1,
                                          color: Color(0XFFE2483D)),
                                      borderRadius: BorderRadius.circular(
                                        12,
                                      )),
                                  alignment: Alignment.center,
                                  child: Visibility(
                                    visible: true,
                                    child: Padding(
                                      padding: EdgeInsets.fromLTRB(16,12,16,12),
                                      child: Text(
                                          'Logout',
                                          style: fontTextStyle(
                                              12,
                                              Color(0XFFFFFFFF),
                                              FontWeight.w600)),
                                    ),
                                  ),
                                )
                            ),)


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

  final List<String> _screenTitles = [
    'Aquick Supplier', // index 0
    'Orders',          // index 1
    'Plans',           // index 2
    'Resources',       // index 3
    'Financials',      // index 4
  ];

  String getScreenTitle(int index) {
    if (index < 0 || index >= _screenTitles.length) return '';
    return _screenTitles[index];
  }

  PreferredSizeWidget? _buildAppBar() {
    // 👉 Orders tab (index 1): Custom Search AppBar
    if (_currentIndex == 1) {
      return
      SearchOrderAppBar(

        controller: orderSearchController,

        onBack: () {
          setState(() {
            _currentIndex = 0; // go back to Home
          });
        },

        onHelp: () {},

        onSearch: (value){

          orderSearchController.text = value;

        },

      );
    }

    if (_currentIndex == 2) {
      return SearchPlanAppBar(
        controller: planSearchController,
        onBack: () {
          setState(() {
            _currentIndex = 0; // go back to Home
          });
        },
        onHelp: () {
          // handle help button action
          debugPrint("Help tapped");
        },
      );
    }

    // 👉 Home tab (index 0): Main AppBar
    if (_currentIndex == 0) {
      return AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        scrolledUnderElevation: 0,
        titleSpacing: 0,
        title: Text(
          'Aquick Supplier',
          style: fontTextStyle(
              16, const Color(0XFF515253), FontWeight.w600),
        ),
        iconTheme: const IconThemeData(color: Color(0XFF2A2A2A)),
        actions: [
          Row(
            children: [
              Padding(
                padding: const EdgeInsets.fromLTRB(10, 10, 0, 10),
                child: IconButton(
                  icon: Image.asset('images/calendar_appbar.png'),
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => SupplierCalendar(),
                      ),
                    );
                  },
                ),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(0, 10, 10, 10),
                child: IconButton(
                  icon: Image.asset('images/notification_appbar.png'),
                  onPressed: () {},
                ),
              ),
            ],
          )
        ],
        leading: IconButton(
          icon: Image.asset(
            'images/profile_appbar.png',
            height: 20,
            width: 20,
          ),
          onPressed: () {
            _scaffoldKey.currentState?.openDrawer();
          },
        ),
      );
    }

    // 👉 Other tabs (index 2,3,4): Simple AppBar with Back to Home
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      scrolledUnderElevation: 0,
      titleSpacing: 0,
      title: Text(
        getScreenTitle(_currentIndex),
        style: fontTextStyle(
            16, const Color(0XFF515253), FontWeight.w600),
      ),
      leading: GestureDetector(
        onTap:(){
          setState(() {
            _currentIndex = 0; // Back → Home
          });
        }, // 👉 use callback from parent
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Image.asset(
            'images/backbutton_appbar.png',
            height: 24,
            width: 24,
            fit: BoxFit.contain,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (_scaffoldKey.currentState?.isDrawerOpen ?? false) {
            // If the drawer is open, close it
            _scaffoldKey.currentState?.openEndDrawer();
            return false; // Prevent the default back action (exit the app)
          }
          else if (_currentIndex == 0) {
            final shouldPop = await showDialog<bool>(
              context: context,
              builder: (context) {
                return AlertDialog(
                  backgroundColor: Color(0XFFFFFFFF),// Set your desired background color
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12), // Optional: Rounded corners
                  ),
                  title: Center(child: Text('Do you want to exit app?',style:fontTextStyle(16,Color(0XFF101214),FontWeight.w700)),),
                  actionsAlignment: MainAxisAlignment.spaceBetween,
                  actions: [
                    Center(
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Expanded(child: GestureDetector(
                            onTap: (){
                              Navigator.of(context).pop(false);
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                  shape: BoxShape.rectangle,
                                  color: Color(0XFFFFFFFF),
                                  border: Border.all(
                                      width: 1,
                                      color: Color(0XFF1D7AFC)),
                                  borderRadius: BorderRadius.circular(
                                    12,
                                  )),
                              alignment: Alignment.center,
                              child: Visibility(
                                visible: true,
                                child: Padding(
                                  padding: EdgeInsets.fromLTRB(16,12,16,12),
                                  child: Text(
                                      'Cancel',
                                      style: fontTextStyle(
                                          12,
                                          Color(0XFF1D7AFC),
                                          FontWeight.w600)),
                                ),
                              ),
                            ),
                          ),),
                          SizedBox(width:MediaQuery.of(context).size.width * .016,),
                          Expanded(child: GestureDetector(
                              onTap: ()async{
                                SystemNavigator.pop();
                              },
                              child: Container(
                                decoration: BoxDecoration(
                                    shape: BoxShape.rectangle,
                                    color: Color(0XFF1D7AFC),
                                    border: Border.all(
                                        width: 1,
                                        color: Color(0XFF1D7AFC)),
                                    borderRadius: BorderRadius.circular(
                                      12,
                                    )),
                                alignment: Alignment.center,
                                child: Visibility(
                                  visible: true,
                                  child: Padding(
                                    padding: EdgeInsets.fromLTRB(16,12,16,12),
                                    child: Text(
                                        'Confirm',
                                        style: fontTextStyle(
                                            12,
                                            Color(0XFFFFFFFF),
                                            FontWeight.w600)),
                                  ),
                                ),
                              )
                          ),)


                        ],
                      ),
                    ),
                  ],
                );
              },
            );
            return shouldPop!;
          }
          else {
            setState(() {
              _currentIndex = 0;
            });
            return false;
          }
        },
        child: Scaffold(
            key: _scaffoldKey,
            backgroundColor: Colors.white,
            appBar: _buildAppBar(),

            drawer: Drawer(
                width: MediaQuery.of(context).size.width,
                backgroundColor: Colors.white,
                child: Padding(
                  padding: EdgeInsets.all(8),
                  child: Container(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        SizedBox(height:MediaQuery.of(context).size.height * .05,),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                           /* GestureDetector(
                              onTap: (){
                                Navigator.of(context).pop(true);
                              },
                              child: Image.asset('images/appbar_backbutton.png',height: 25,width: 25,color: Color(0XFF2A2A2A),),
                            ),*/
                            SizedBox(width:MediaQuery.of(context).size.width * .04,),
                            Text(
                              'Menu',
                              style: fontTextStyle(14,Color(0XFF2A2A2A),FontWeight.w500),
                            ),
                          ],
                        ),
                        SizedBox(height:MediaQuery.of(context).size.height * .016,),
                        Padding( padding: EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              /*CircleAvatar(
                         radius: 50, // Adjust the size of the circle
                         backgroundColor: Colors.grey[200],
                         backgroundImage:AppSettings.profilePictureUrl !=
                             '' &&
                             AppSettings.profilePictureUrl !=
                                 'null'?NetworkImage(AppSettings
                             .profilePictureUrl) as ImageProvider: AssetImage('images/profile_pic.png',), // Your profile image
                       ),*/
                              GestureDetector(
                                onTap: () {
                                  Navigator.push(
                                      context,
                                      new MaterialPageRoute(
                                          builder: (__) => new ImageZoomPage(
                                              imageName: 'Profile',
                                              imageDetails: AppSettings.profilePictureUrl)));
                                },
                                child: Stack(
                                  alignment: Alignment.center, // Centers the stack's children
                                  children: [

                                    // CircleAvatar background
                                    ClipOval(
                                      child: Container(
                                        height: 100, // Ensure the container's height is the same as the profile image
                                        width: 100,

                                        decoration: BoxDecoration(
                                          color: (AppSettings.profilePictureUrl == '' ||
                                              AppSettings.profilePictureUrl == 'null')
                                              ? Color(0XFFF3F1FB)
                                              : Colors.transparent,

                                          shape: BoxShape.circle,
                                        ),

                                        child: (AppSettings.profilePictureUrl != '' &&
                                            AppSettings.profilePictureUrl != 'null')
                                            ? Image.network(
                                          AppSettings.profilePictureUrl,
                                          fit: BoxFit.cover,
                                          height: 100,
                                          width: 100,
                                        )
                                            : Center(
                                          child: Image.asset(
                                            "images/profile_pic.png",
                                            height: 40,
                                            width: 40,
                                            color: primaryColor,
                                          ),
                                        ),
                                      ),
                                    ),
                                    // Positioned image on top of CircleAvatar
                                    Positioned(
                                      bottom: 0, // Adjust position as needed
                                      right: 0, // Adjust position as needed
                                      child: Container(
                                        width: 30,
                                        height: 30,
                                        decoration: BoxDecoration(
                                          boxShadow: [
                                            BoxShadow(
                                              color: Colors.black.withOpacity(0.3),
                                              blurRadius: 4,
                                              offset: Offset(0, 2), // Shadow to make the edit icon pop
                                            ),
                                          ],
                                          shape: BoxShape.circle,
                                          color: Colors.white, // Background for the overlay
                                        ),

                                        child: GestureDetector(
                                          onTap: (){
                                            showModalBottomSheet<void>(
                                                context: context,
                                                builder: (BuildContext context) {
                                                  return SizedBox(
                                                    height: 200,
                                                    child: Center(
                                                      child: Row(
                                                        mainAxisAlignment:
                                                        MainAxisAlignment.center,
                                                        children: <Widget>[
                                                          GestureDetector(
                                                            child: Icon(
                                                              Icons.camera_alt_outlined,
                                                              size: 100,
                                                              color: primaryColor,
                                                            ),
                                                            onTap: () async {
                                                              await takeImageFromCamera();
                                                              Navigator.pop(context);
                                                            },
                                                          ),
                                                          SizedBox(
                                                            width: MediaQuery.of(context)
                                                                .size
                                                                .width *
                                                                .20,
                                                          ),
                                                          GestureDetector(
                                                            child: Icon(
                                                              Icons.photo,
                                                              size: 100,
                                                              color: primaryColor,
                                                            ),
                                                            onTap: () async {
                                                              await pickImageFromGallery();
                                                              Navigator.pop(context);
                                                            },
                                                          ),
                                                        ],
                                                      ),
                                                    ),
                                                  );
                                                });
                                          },
                                          child: Center(
                                            child: Image.asset(
                                              'images/edit.png',
                                              width: 14,
                                              height: 14,
                                              fit: BoxFit.contain,
                                              color: primaryColor,
                                            ),
                                          )
                                        ),
                                      ),
                                    ),
                                  ],
                                ),

                              ),
                              SizedBox(height:MediaQuery.of(context).size.height * .016,),
                              Text(
                                AppSettings.userName,
                                style: fontTextStyle(20,Color(0XFF2A2A2A),FontWeight.w500),
                              ),
                              Visibility(
                                visible:true,
                                child:   Text(
                                  AppSettings.email,
                                  style: fontTextStyle(14,Color(0XFF2A2A2A),FontWeight.w400),
                                ),),
                              Text(
                                AppSettings.phoneNumber,
                                style: fontTextStyle(14,Color(0XFF2A2A2A),FontWeight.w400),
                              ),
                            ],
                          ),),
                        SizedBox(height:MediaQuery.of(context).size.height * .024,),
                        ListTile(
                          title: Row(
                            children:  [
                              Image(
                                  image: const AssetImage('images/manage_users_drawer.png'),
                                  height: 25,
                                  width: 25,
                                  fit: BoxFit.fill,),
                              SizedBox(width:MediaQuery.of(context).size.width * .04,),
                              Text('Users', style: fontTextStyle(14,Color(0XFF2A2A2A),FontWeight.w400),),
                            ],
                          ),
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => MyUsers()),
                            );
                          },
                        ),
                        ListTile(
                          title: Row(
                            children:  [
                              Image(
                                  image: const AssetImage('images/logout_drawer.png'),
                                  height: 25,
                                  width: 25,
                                  fit: BoxFit.fill),
                              SizedBox(width:MediaQuery.of(context).size.width * .04,),
                              Text('Logout', style: fontTextStyle(16,Color(0XFFE2483D),FontWeight.w400),),
                            ],
                          ),
                          onTap: () {
                            showLogoutAlertDialog(context);
                          },
                        ),



                      ],
                    ),
                  ),
                )

            ),
            body:
            _getScreen(),
            /*_body(),,*/
            bottomNavigationBar: Padding(
              padding:EdgeInsets.fromLTRB(0, 0, 0, 0) ,
              child: BottomNavigationBar(
                backgroundColor: Color(0XFFFFFFFF),
                items: _bottomNavItems,
                selectedItemColor: primaryColor, // Color of selected icon and text
                unselectedItemColor: Color(0XFF939495), // Color of unselected icon and text
                selectedLabelStyle: fontTextStyleHeight(10,primaryColor,FontWeight.w400,MediaQuery.of(context).size.height * .0032,),
                unselectedLabelStyle: fontTextStyleHeight(10,Color(0XFF939495),FontWeight.w400,MediaQuery.of(context).size.height * .0032,),
                currentIndex: _currentIndex,
                onTap: _onItemTapped,
                /*onTap: (index) {
              switch (index) {
                case 0:
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Resources()),
                  );
                  break;
                case 1:
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => TankLevels()),
                  );
                  break;

                case 3:
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => Consumption()),
                  );
                  break;
                case 4:
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => SupplierManagementDashboard()),
                  );
                  break;
              }
            },*/
                type: BottomNavigationBarType
                    .fixed, // Ensures all 6 items are visible
              ),
            )
        ));
  }
}



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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  int todaysOrdersCount = 0;
  int yesterdayPendingOrders = 0;
  double todaysRevenue = 0;
  double yesterdayRevenue = 0;
  String revenueChangeText = "0% from yesterday";
  Color revenueChangeColor = Colors.grey;
  int orderRequestsCount = 0;
  int planRequestsCount = 0;

  @override
  void initState() {
    super.initState();
    _fetchDriverCounts();
    _fetchTankerCounts();
    _fetchTodayOrders();
    _fetchTodayRevenue();
    _fetchOrderRequestsCount();
    _fetchPlanRequestsCount();
  }

  Future<void> _fetchOrderRequestsCount() async {

    try{

      final response =
      await AppSettings.getOrderRequestsFromUsers();

      final List data =
          jsonDecode(response)['data'] ?? [];

      int count = 0;

      for(var order in data){

        String status =
        (order['my_supplier_entry']['status'] ?? "")
            .toString()
            .toLowerCase();

        /// Only pending/new requests
        if(status == "pending"){
          count++;
        }

      }

      if(!mounted) return;

      setState(() {

        orderRequestsCount = count;

      });

    }
    catch(e){

      debugPrint("Order requests error $e");

    }

  }

  Future<void> _fetchPlanRequestsCount() async {

    try{

      final response =
      await AppSettings.getPlanRequestsFromUsers();

      final List data =
          jsonDecode(response)['data'] ?? [];

      int count = 0;

      for(var plan in data){

        String status =
        (plan['status'] ?? "")
            .toString()
            .toLowerCase();

        /// only pending requests
        if(status == "pending"){
          count++;
        }

      }

      if(!mounted) return;

      setState(() {

        planRequestsCount = count;

      });

    }
    catch(e){

      debugPrint("Plan requests error $e");

    }

  }


  Future<void> _fetchDriverCounts() async {
    try {
      final response = await AppSettings.getDrivers();
      final data = (jsonDecode(response)['data'] as List)
          .map((e) => DriversModel.fromJson(e))
          .toList();

      int available = 0;
      int onDelivery = 0;
      int offline = 0;

      for (final d in data) {
        switch (d.status) {
          case 'available':
            available++;
            break;
          case 'on delivery':
            onDelivery++;
            break;
          case 'offline':
            offline++;
            break;
        }
      }

      if (!mounted) return;
      setState(() {
        AppSettings.driverAvailableCount = available;
        AppSettings.driverOnDeliveryCount = onDelivery;
        AppSettings.driverOfflineCount = offline;
        AppSettings.totalDrivers = data.length;
      });
    } catch (e) {
      debugPrint("Driver dashboard error: $e");
    }
  }

  // ================= TANKERS =================
  Future<void> _fetchTankerCounts() async {
    try {
      final response = await AppSettings.getTankers();
      final data = (jsonDecode(response)['data'] as List)
          .map((e) => TankersModel.fromJson(e))
          .toList();

      int active = 0;
      int maintenance = 0;

      for (final t in data) {
        final statusList = List<String>.from(t.availability);
        if (statusList.contains('undermaintanence')) {
          maintenance++;
        } else {
          active++;
        }
      }

      if (!mounted) return;
      setState(() {
        AppSettings.tankerActiveCount = active;
        AppSettings.tankerMaintenanceCount = maintenance;
        AppSettings.totalTankers = data.length;
      });
    } catch (e) {
      debugPrint("Tanker dashboard error: $e");
    }
  }

  Future<void> _fetchTodayOrders() async {
    try {
      final response = await AppSettings.getAcceptedOrdersFromUsers();
      final data = jsonDecode(response)['data'] as List;

      String todayStr = DateFormat("dd-MMM-yyyy").format(DateTime.now());
      String yesterdayStr =
      DateFormat("dd-MMM-yyyy").format(DateTime.now().subtract(Duration(days: 1)));

      int todayCount = 0;
      int yesterdayPending = 0;

      for (var order in data) {
        String orderDate = order['expectedDateOfDelivery'].toString().trim();
        String status = order['status'].toString().toLowerCase();

        // today orders
        if (orderDate == todayStr) {
          todayCount++;
        }

        // yesterday but not completed
        if (orderDate == yesterdayStr &&
            status != "delivered" &&
            status != "completed") {
          yesterdayPending++;
        }
      }

      if (!mounted) return;

      setState(() {
        todaysOrdersCount = todayCount;
        yesterdayPendingOrders = yesterdayPending;
      });
    } catch (e) {
      debugPrint("Dashboard orders error: $e");
    }
  }

  Future<void> _fetchTodayRevenue() async {

    try{

      final response = await AppSettings.getSupplierTransactions();

      final decoded = jsonDecode(response);

      final List data = decoded["data"] ?? [];

      String todayStr =
      DateFormat("dd-MMM-yyyy").format(DateTime.now());

      String yesterdayStr =
      DateFormat("dd-MMM-yyyy")
          .format(DateTime.now().subtract(Duration(days: 1)));

      double today = 0;
      double yesterday = 0;

      for(var e in data){

        final orderStatus =
        (e["orderStatus"] ?? "").toString().toLowerCase();

        final date =
        (e["dateOfOrder"] ?? "").toString();

        final price =
            double.tryParse(e["price"].toString()) ?? 0;

        final advance =
            double.tryParse(e["amount_paid"].toString()) ?? 0;

        double amount = 0;

        if(orderStatus == "completed"){
          amount = price;
        }
        else if(orderStatus == "advance_paid"){
          amount = advance;
        }
        else if(orderStatus == "cancelled" ||
            orderStatus == "refunded"){
          amount = -advance;
        }

        if(date == todayStr){
          today += amount;
        }

        if(date == yesterdayStr){
          yesterday += amount;
        }

      }

      /// percentage calculation
      double percent = 0;

      if(yesterday > 0){

        percent =
            ((today - yesterday) / yesterday) * 100;

      }
      else if(today > 0){

        percent = 100;

      }

      String text;
      Color color;

      if(today > yesterday){

        if(yesterday == 0){

          text = "↑ New revenue";

        }
        else{

          text =
          "↑ ${percent.abs().toStringAsFixed(0)}% from yesterday";

        }

        color = Colors.green;

      }
      else if(today < yesterday){

        text =
        "↓ ${percent.abs().toStringAsFixed(0)}% from yesterday";

        color = Colors.red;

      }
      else{

        text = "0% from yesterday";

        color = Colors.grey;

      }

      if(!mounted) return;

      setState(() {

        todaysRevenue = today;

        yesterdayRevenue = yesterday;

        revenueChangeText = text;

        revenueChangeColor = color;

      });

    }
    catch(e){

      debugPrint("Revenue error $e");

    }

  }

  @override
  Widget build(BuildContext context) {
    return  SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          /// Profile Completion Section
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                "Complete your Profile",
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
              ),
              TextButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => FleetStep1Page(),
                    ),
                  );
                },
                child: const Text(
                  "Edit Profile",
                  style: TextStyle(color: Colors.blue, fontSize: 14),
                ),
              )
            ],
          ),
          const SizedBox(height: 4),
          LinearProgressIndicator(
            value: 0.4,
            backgroundColor: Colors.grey[300],
            valueColor: AlwaysStoppedAnimation<Color>(Colors.deepPurple),
            minHeight: 6,
            borderRadius: BorderRadius.circular(8),
          ),
          const SizedBox(height: 6),
          const Text(
            "40% Complete\nComplete updating your profile in 5 minutes",
            style: TextStyle(fontSize: 12, color: Colors.grey),
          ),

          const SizedBox(height: 16),

          /// Orders + Revenue
          GridView.count(
            crossAxisCount: 2,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            crossAxisSpacing: 12,
            mainAxisSpacing: 12,
            childAspectRatio: 1.5,
            children:  [
              DashboardCard(
                title: "Today's Orders",
                value: "$todaysOrdersCount",
                subtitle: "+$yesterdayPendingOrders from yesterday",
                icon: Icons.shopping_cart_outlined,
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => AllOrders(navigationFrom: 'dashboard',)),
                  );
                },
              ),
              DashboardCard(
                title: "Today's Revenue",
                value: "₹${todaysRevenue.toStringAsFixed(0)}",
                subtitle: revenueChangeText,
                icon: Icons.currency_rupee,
                onTap: () {

                  final dashboardState =
                  context.findAncestorStateOfType<_DashboardScreenState>();

                  dashboardState?.setState(() {

                    dashboardState._currentIndex = 4;

                  });

                },
              ),
            ],
          ),

          const SizedBox(height: 12),

          /// Vehicles + Drivers
          GridView.count(
            crossAxisCount: 2,
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            crossAxisSpacing: 12,
            mainAxisSpacing: 12,
            childAspectRatio: 1.5,
            children: [
              GestureDetector(
                onTap: () async {
                  // 👉 Switch to Resources tab (index = 3)
                  final dashboardState =
                  context.findAncestorStateOfType<_DashboardScreenState>();

                  dashboardState?.setState(() {
                    dashboardState._currentIndex = 3;
                  });

                  // 👉 Wait for user to come back to Home
                  await Future.delayed(const Duration(milliseconds: 300));

                  // 👉 Refresh counts when back
                  _fetchTankerCounts();
                  _fetchDriverCounts();
                },
                child: DashboardCard(
                  title: "Active Vehicles",
                  value:
                  "${AppSettings.tankerActiveCount}/${AppSettings.totalTankers}",
                  subtitle:
                  "${AppSettings.tankerMaintenanceCount} in maintenance",
                  icon: Icons.local_shipping_outlined,
                ),
              ),
              GestureDetector(
                onTap: () async {
                  // 👉 Tell Resources to open Drivers tab
                  AppSettings.resourcesInitialTab = 1; // DRIVERS

                  // 👉 Switch to Resources screen
                  final dashboardState =
                  context.findAncestorStateOfType<_DashboardScreenState>();

                  dashboardState?.setState(() {
                    dashboardState._currentIndex = 3;
                  });

                  // 👉 When user comes back to dashboard
                  await Future.delayed(const Duration(milliseconds: 300));

                  _fetchDriverCounts();
                  _fetchTankerCounts();
                },
                child: DashboardCard(
                  title: "Available Drivers",
                  value:
                  "${AppSettings.driverAvailableCount}/${AppSettings.totalDrivers}",
                  subtitle:
                  "${AppSettings.driverOnDeliveryCount} on delivery, "
                      "${AppSettings.driverOfflineCount} offline",
                  icon: Icons.person_outline,
                ),
              ),
            ],
          ),

          const SizedBox(height: 20),

          /// Quick Actions
          const Text(
            "Quick Actions",
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(height: 12),

          GestureDetector(
            onTap: (){
              Navigator.push(
                  context,
                  new MaterialPageRoute(
                      builder: (__) => new SetRatesScreen()));
            },
            child: Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.deepPurple,
                borderRadius: BorderRadius.circular(16),
              ),
              child: Row(
                children: [
                  const Icon(Icons.currency_rupee, color: Colors.white),
                  const SizedBox(width: 12),
                  const Expanded(
                    child: Text(
                      "Set Rates\nSet your water rates and delivery rates for the day in just a few taps",
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    ),
                  ),
                  Icon(Icons.arrow_forward_ios, color: Colors.white, size: 18),
                ],
              ),
            ),
          ),

          const SizedBox(height: 16),

          /// Requests Section
          Row(
            children:  [
              Expanded(
                child: GestureDetector(
                  onTap: (){
                    Navigator.push(
                        context,
                        new MaterialPageRoute(
                            builder: (__) => new OrderRequestsPage()));
                  },
                  child: RequestCard(
                    title: "Order Requests",
                    subtitle: orderRequestsCount > 0
                        ? "$orderRequestsCount new request"
                        : null,
                  ),
                ),
              ),
              SizedBox(width: 12),
              Expanded(
                child: GestureDetector(
                  onTap: (){
                    Navigator.push(
                        context,
                        new MaterialPageRoute(
                            builder: (__) => new PlanRequestsPage()));
                  },
                  child: RequestCard(
                    title: "Plan Requests",
                    subtitle: planRequestsCount > 0
                        ? "$planRequestsCount new request"
                        : null,
                  ),
                )
              ),
            ],
          )
        ],
      ),
    );
  }
}

class DashboardCard extends StatelessWidget {
  final String title;
  final String value;
  final String subtitle;
  final IconData icon;
  final VoidCallback? onTap; // 👈 add callback

  const DashboardCard({
    super.key,
    required this.title,
    required this.value,
    required this.subtitle,
    required this.icon,
    this.onTap, // 👈 optional
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap, // 👈 handle tap
      borderRadius: BorderRadius.circular(16), // ripple effect follows shape
      child: Container(
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.shade300,
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Align(
                  alignment: Alignment.topRight,
                  child: Icon(icon, color: Colors.deepPurple),
                ),
              ],
            ),
            const SizedBox(height: 6),
            Text(
              value,
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              subtitle,
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class RequestCard extends StatelessWidget {
  final String title;
  final String? subtitle;

  const RequestCard({
    super.key,
    required this.title,
    this.subtitle,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
          ),
          const SizedBox(height: 8),
          if(subtitle != null)
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.green[50],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                subtitle!,
                style: const TextStyle(
                  color: Colors.green,
                  fontSize: 12,
                ),
              ),
            ),
        ],
      ),
    );
  }
}