import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:bookatanker/common/settings.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:gallery_saver/gallery_saver.dart';
import 'package:flutter/services.dart';
import 'package:share/share.dart';
import 'package:bookatanker/supplier/favourites_model.dart';
import 'package:bookatanker/supplier/place_order.dart';
import 'package:bookatanker/supplier/supplier_details.dart';

import '../models/connected_suppliers_model.dart';
import '../models/water_suppliers_model.dart';

class MySuppliers extends StatefulWidget {
  var navigationFrom;
  MySuppliers({this.navigationFrom});
  @override
  State<MySuppliers> createState() => _MySuppliersState();
}

class _MySuppliersState extends State<MySuppliers>
    with TickerProviderStateMixin {
  late TabController _controller;
  String tabMessage = "Welcome to Tab 1";
  bool isDataLoading = false;
  bool isConnectedDataLoading = false;
  bool isFavouriteDataLoading = false;
  List<WaterSuppliersModel> suppliersList = [];
  List<ConnectedSuppliersModel> connectedSuppliersList = [];
  List<favouritesModel> favouritesList = [];
  Set<String> favouriteIds = {}; // for fast lookup

  @override
  void initState() {
    super.initState();
    _controller = TabController(vsync: this, length: 3);
    // Listen for tab changes
    _controller.addListener(() {
      if (_controller.indexIsChanging) {
        setState(() {
          // Change message or perform any other update
          tabMessage =
              _controller.index == 0 ? "Welcome to Tab 1" : "Welcome to Tab 2";
        });
      }
    });
    getAllSuppliersData();
    getConnectedSuppliersData();
    getAllFavouritesData();
  }

  Future<void> getAllSuppliersData() async {

    setState(() {
      isDataLoading = true;
    });

    try {

      String tankerResponse = await AppSettings.getAllSuppliers();

      if (tankerResponse.isEmpty) {
        setState(() {
          isDataLoading = false;
        });
        return;
      }

      var decoded = jsonDecode(tankerResponse);

      List supplierList = decoded['suppliers'] ?? [];

      List<WaterSuppliersModel> tempList = [];

      for (var item in supplierList) {

        try {

          tempList.add(WaterSuppliersModel.fromJson(item));

        } catch (e) {

          print("Supplier parse error: $e");

        }

      }

      setState(() {
        suppliersList = tempList;
        isDataLoading = false;
      });

    } catch (e) {

      print("API ERROR: $e");

      setState(() {
        isDataLoading = false;
      });

    }

  }

  Future<void> getAllFavouritesData() async {
    isFavouriteDataLoading = true;
    try {
      var tankerResponse = await AppSettings.getAllFavourites();

      setState(() {
        favouritesList =
            ((jsonDecode(tankerResponse)['data']) as List).map((dynamic model) {
          return favouritesModel.fromJson(model);
        }).toList();
        favouriteIds = favouritesList.map((e) => e.supplier_id).toSet();
        isFavouriteDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isFavouriteDataLoading = false;
      });
    }
  }

  Future<void> getConnectedSuppliersData() async {
    isConnectedDataLoading = true;

    try {
      var response = await AppSettings.getConnetcedSuppliers();

      setState(() {
        connectedSuppliersList =
            ((jsonDecode(response)['data']) as List).map((dynamic model) {
          return ConnectedSuppliersModel.fromJson(model);
        }).toList();
        isConnectedDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isConnectedDataLoading = false;
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Widget mySuppliers() {
    return isConnectedDataLoading
        ? Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          )
        : connectedSuppliersList.length != 0
            ? Padding(
                padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                        child: ListView.separated(
                            padding: EdgeInsets.all(8),
                            itemCount: connectedSuppliersList.length,
                            separatorBuilder: (context, index) => SizedBox(
                                  height:
                                      MediaQuery.of(context).size.height * .008,
                                ),
                            itemBuilder: (BuildContext context, int index) {
                              return Container(
                                decoration: BoxDecoration(
                                  color:
                                      Color(0XFFFFFFFF), // Same as Card color
                                  borderRadius: BorderRadius.circular(
                                      12), // Rounded corners
                                  border: Border.all(
                                    color: Colors.grey.shade300, // Border color
                                    width: 1, // Border width
                                  ),
                                ),
                                child: Padding(
                                  padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                                  child: Column(
                                    children: [
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          /*CircleAvatar(
                              radius: 30,
                              backgroundColor: Color(0XFFE8F2FF), // Fallback background color
                              child: usersList[index].profilePic.isNotEmpty? Image.network(usersList[index].profilePic,):

                              Text(
                                usersList[index].username.isNotEmpty ? usersList[index].username[0].toUpperCase() : '?', // First letter of name or '?'
                                style: TextStyle(
                                  fontSize: 25,
                                  fontWeight: FontWeight.bold,
                                  color:Color(0XFF9EC6FE),
                                ),
                              )
                          ),*/
                                          CircleAvatar(
                                            radius: 20,
                                            backgroundColor: Color(
                                                0XFFE8F2FF), // Fallback background color
                                            child: Image.asset(
                                              'images/profile_user.png',
                                              fit: BoxFit.cover,
                                              width:
                                                  50, // Match the diameter of the CircleAvatar
                                              height: 50,
                                            ), // Default icon if no profilePic
                                          ),
                                          SizedBox(
                                            width: MediaQuery.of(context)
                                                    .size
                                                    .width *
                                                .012,
                                          ),
                                          Expanded(
                                            flex: 2,
                                            child: Container(
                                              //width:MediaQuery.of(context).size.height * .3,
                                              //height: MediaQuery.of(context).size.height * .06,
                                              child: Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Visibility(
                                                    visible: true,
                                                    child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        Visibility(
                                                          visible:
                                                              connectedSuppliersList[
                                                                          index]
                                                                      .supplier_name !=
                                                                  '',
                                                          child: Text(
                                                            connectedSuppliersList[
                                                                    index]
                                                                .supplier_name
                                                                .toString(),
                                                            style: fontTextStyle(
                                                                16,
                                                                Color(
                                                                    0XFF2D2E30),
                                                                FontWeight
                                                                    .w600),
                                                          ),
                                                        ),
                                                        Row(
                                                          mainAxisAlignment:
                                                              MainAxisAlignment
                                                                  .center,
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .center,
                                                          children: [
                                                            Image.asset(
                                                              'images/star.png',
                                                              fit: BoxFit.cover,
                                                              width:
                                                                  16, // Match the diameter of the CircleAvatar
                                                              height: 16,
                                                            ),
                                                            Visibility(
                                                              visible: true,
                                                              child: Text(
                                                                '4.2 (20K+ Ratings)',
                                                                style: fontTextStyle(
                                                                    9,
                                                                    Color(
                                                                        0XFF515253),
                                                                    FontWeight
                                                                        .w400),
                                                              ),
                                                            ),
                                                          ],
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                  Visibility(
                                                    visible: true,
                                                    child: Text(
                                                      'Drinking | Bore Water',
                                                      style: fontTextStyle(
                                                          12,
                                                          Color(0XFF4692FD),
                                                          FontWeight.w500),
                                                    ),
                                                  ),
                                                  Visibility(
                                                    visible: true,
                                                    child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        Text(
                                                            connectedSuppliersList[
                                                                        index]
                                                                    .displayAddress +
                                                                '   ' +
                                                                connectedSuppliersList[
                                                                        index]
                                                                    .distanceInMeters
                                                                    .toString() +
                                                                ' Km',
                                                            style: fontTextStyle(
                                                                12,
                                                                Color(
                                                                    0XFF515253),
                                                                FontWeight
                                                                    .w400)),
                                                        GestureDetector(
                                                          onTap: () async {
                                                            AppSettings
                                                                .preLoaderDialog(
                                                                    context);
                                                            if (connectedSuppliersList[
                                                                    index]
                                                                .isFavorite) {
                                                              try {
                                                                bool
                                                                    tankerResponse =
                                                                    await AppSettings.removeFavourites(
                                                                        connectedSuppliersList[index]
                                                                            .supplier_id);
                                                                if (tankerResponse) {
                                                                  Navigator.of(
                                                                          context,
                                                                          rootNavigator:
                                                                              true)
                                                                      .pop();
                                                                  AppSettings
                                                                      .longSuccessToast(
                                                                          'Supplier removed from favourites');
                                                                  await getAllSuppliersData();
                                                                  await getConnectedSuppliersData();
                                                                } else {
                                                                  Navigator.of(
                                                                          context,
                                                                          rootNavigator:
                                                                              true)
                                                                      .pop();
                                                                  AppSettings
                                                                      .longFailedToast(
                                                                          'Failed to remove from favourites');
                                                                }
                                                              } catch (e) {
                                                                Navigator.of(
                                                                        context,
                                                                        rootNavigator:
                                                                            true)
                                                                    .pop();
                                                                AppSettings
                                                                    .longFailedToast(
                                                                        'Failed to remove from favourites');
                                                              }
                                                            } else {
                                                              try {
                                                                bool
                                                                    tankerResponse =
                                                                    await AppSettings.addFavourites(
                                                                        connectedSuppliersList[index]
                                                                            .supplier_id);
                                                                if (tankerResponse) {
                                                                  Navigator.of(
                                                                          context,
                                                                          rootNavigator:
                                                                              true)
                                                                      .pop();
                                                                  AppSettings
                                                                      .longSuccessToast(
                                                                          'Supplier added to favourites');
                                                                  await getAllSuppliersData();
                                                                  await getConnectedSuppliersData();
                                                                  await getAllFavouritesData();
                                                                } else {
                                                                  Navigator.of(
                                                                          context,
                                                                          rootNavigator:
                                                                              true)
                                                                      .pop();
                                                                  AppSettings
                                                                      .longFailedToast(
                                                                          'Failed to add favourites');
                                                                }
                                                              } catch (e) {
                                                                Navigator.of(
                                                                        context,
                                                                        rootNavigator:
                                                                            true)
                                                                    .pop();
                                                                AppSettings
                                                                    .longFailedToast(
                                                                        'Failed to add favourites');
                                                              }
                                                            }
                                                          },
                                                          child:
                                                              connectedSuppliersList[
                                                                          index]
                                                                      .isFavorite
                                                                  ? Image.asset(
                                                                      'images/heart_active.png',
                                                                      fit: BoxFit
                                                                          .cover,
                                                                      width:
                                                                          16, // Match the diameter of the CircleAvatar
                                                                      height:
                                                                          16,
                                                                    )
                                                                  : Image.asset(
                                                                      'images/heart_outline.png',
                                                                      fit: BoxFit
                                                                          .cover,
                                                                      width:
                                                                          16, // Match the diameter of the CircleAvatar
                                                                      height:
                                                                          16,
                                                                    ),
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                      Divider(
                                        color: Colors.grey.shade300,
                                      ),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            'Plan',
                                            style: fontTextStyle(
                                                10,
                                                Color(0XFF343637),
                                                FontWeight.w400),
                                          ),
                                          Text(
                                            '15,000 / week',
                                            style: fontTextStyle(
                                                10,
                                                Color(0XFF2D2E30),
                                                FontWeight.w500),
                                          )
                                        ],
                                      ),
                                      SizedBox(
                                        height:
                                            MediaQuery.of(context).size.height *
                                                .016,
                                      ),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Expanded(
                                            child: GestureDetector(
                                              onTap: () {},
                                              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: Padding(
                                                  padding: EdgeInsets.fromLTRB(
                                                      16, 12, 16, 12),
                                                  child: Text('Chat',
                                                      style: fontTextStyle(
                                                          12,
                                                          Color(0XFF1D7AFC),
                                                          FontWeight.w600)),
                                                ),
                                              ),
                                            ),
                                          ),
                                          SizedBox(
                                            width: MediaQuery.of(context)
                                                    .size
                                                    .width *
                                                .010,
                                          ),
                                          Expanded(
                                              child: GestureDetector(
                                            onTap: () {
                                              /* Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => PlaceOrder(details: connectedSuppliersList[index],)),
                      );*/
                                              Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                    builder: (context) =>
                                                        SupplierScreen(
                                                          details:
                                                              connectedSuppliersList[
                                                                  index],
                                                        )),
                                              );
                                            },
                                            child: Container(
                                              decoration: BoxDecoration(
                                                  shape: BoxShape.rectangle,
                                                  color: Color(0XFF1D7AFC),
                                                  border: Border.all(
                                                    width: 1,
                                                    color: Color(0XFFFFFFFF),
                                                  ),
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                    12,
                                                  )),
                                              alignment: Alignment.center,
                                              child: Padding(
                                                padding: EdgeInsets.fromLTRB(
                                                    16, 12, 16, 12),
                                                child: Text('Place Order',
                                                    style: fontTextStyle(
                                                        12,
                                                        Color(0XFFFFFFFF),
                                                        FontWeight.w600)),
                                              ),
                                            ),
                                          ))
                                        ],
                                      )
                                    ],
                                  ),
                                ),
                              );
                            })),
                    Align(
                      alignment: Alignment.center,
                      child: GestureDetector(
                        onTap: () {},
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Image.asset(
                              'images/add_icon.png',
                              fit: BoxFit.cover,
                              width:
                                  24, // Match the diameter of the CircleAvatar
                              height: 24,
                            ),
                            SizedBox(
                              width: MediaQuery.of(context).size.width * .016,
                            ),
                            Text('Find New Suppliers',
                                style: fontTextStyle(
                                    12, Color(0XFF000000), FontWeight.w400))
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              )
            : Center(
                child: Text(
                  'No Data Available',
                  style: fontTextStyle(12, Color(0XFF000000), FontWeight.w500),
                ),
              );
  }

  Widget otherSuppliers() {
    return isDataLoading
        ? Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          )
        : suppliersList.length != 0
            ? Padding(
                padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                        child: ListView.separated(
                            padding: EdgeInsets.all(8),
                            itemCount: suppliersList.length,
                            separatorBuilder: (context, index) => SizedBox(
                                  height:
                                      MediaQuery.of(context).size.height * .008,
                                ),
                            itemBuilder: (BuildContext context, int index) {
                              return Container(
                                decoration: BoxDecoration(
                                  color:
                                      Color(0XFFFFFFFF), // Same as Card color
                                  borderRadius: BorderRadius.circular(
                                      12), // Rounded corners
                                  border: Border.all(
                                    color: Colors.grey.shade300, // Border color
                                    width: 1, // Border width
                                  ),
                                ),
                                child: Padding(
                                  padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                                  child: Column(
                                    children: [
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          /*CircleAvatar(
                              radius: 30,
                              backgroundColor: Color(0XFFE8F2FF), // Fallback background color
                              child: usersList[index].profilePic.isNotEmpty? Image.network(usersList[index].profilePic,):

                              Text(
                                usersList[index].username.isNotEmpty ? usersList[index].username[0].toUpperCase() : '?', // First letter of name or '?'
                                style: TextStyle(
                                  fontSize: 25,
                                  fontWeight: FontWeight.bold,
                                  color:Color(0XFF9EC6FE),
                                ),
                              )
                          ),*/
                                          CircleAvatar(
                                            radius: 20,
                                            backgroundColor: Color(
                                                0XFFE8F2FF), // Fallback background color
                                            child: Image.asset(
                                              'images/profile_user.png',
                                              fit: BoxFit.cover,
                                              width:
                                                  50, // Match the diameter of the CircleAvatar
                                              height: 50,
                                            ), // Default icon if no profilePic
                                          ),
                                          SizedBox(
                                            width: MediaQuery.of(context)
                                                    .size
                                                    .width *
                                                .012,
                                          ),
                                          Expanded(
                                            flex: 2,
                                            child: Container(
                                              //width:MediaQuery.of(context).size.height * .3,
                                              //height: MediaQuery.of(context).size.height * .06,
                                              child: Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Visibility(
                                                    visible: true,
                                                    child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        Visibility(
                                                          visible: suppliersList[
                                                                      index]
                                                                  .supplier_name !=
                                                              '',
                                                          child: Text(
                                                            suppliersList[index]
                                                                .supplier_name
                                                                .toString(),
                                                            style: fontTextStyle(
                                                                16,
                                                                Color(
                                                                    0XFF2D2E30),
                                                                FontWeight
                                                                    .w600),
                                                          ),
                                                        ),
                                                        Row(
                                                          mainAxisAlignment:
                                                              MainAxisAlignment
                                                                  .center,
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .center,
                                                          children: [
                                                            Image.asset(
                                                              'images/star.png',
                                                              fit: BoxFit.cover,
                                                              width:
                                                                  16, // Match the diameter of the CircleAvatar
                                                              height: 16,
                                                            ),
                                                            Visibility(
                                                              visible: true,
                                                              child: Text(
                                                                '4.2 (20K+ Ratings)',
                                                                style: fontTextStyle(
                                                                    9,
                                                                    Color(
                                                                        0XFF515253),
                                                                    FontWeight
                                                                        .w400),
                                                              ),
                                                            ),
                                                          ],
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                  Visibility(
                                                    visible: true,
                                                    child: Text(
                                                      'Drinking | Bore Water',
                                                      style: fontTextStyle(
                                                          12,
                                                          Color(0XFF4692FD),
                                                          FontWeight.w500),
                                                    ),
                                                  ),
                                                  Visibility(
                                                    visible: true,
                                                    child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        Text(
                                                            suppliersList[index]
                                                                    .displayAddress +
                                                                '   ' +
                                                                suppliersList[
                                                                        index]
                                                                    .distanceInMeters
                                                                    .toString() +
                                                                ' Km',
                                                            style: fontTextStyle(
                                                                12,
                                                                Color(
                                                                    0XFF515253),
                                                                FontWeight
                                                                    .w400)),
                                                        GestureDetector(
                                                          onTap: () async {
                                                            AppSettings
                                                                .preLoaderDialog(
                                                                    context);
                                                            if (favouriteIds.contains(
                                                                suppliersList[
                                                                        index]
                                                                    .supplier_id)) {
                                                              try {
                                                                bool
                                                                    tankerResponse =
                                                                    await AppSettings.removeFavourites(
                                                                        suppliersList[index]
                                                                            .supplier_id);
                                                                if (tankerResponse) {
                                                                  Navigator.of(
                                                                          context,
                                                                          rootNavigator:
                                                                              true)
                                                                      .pop();
                                                                  AppSettings
                                                                      .longSuccessToast(
                                                                          'Supplier removed from favourites');
                                                                  await getAllSuppliersData();
                                                                  await getConnectedSuppliersData();
                                                                  await getAllFavouritesData();
                                                                } else {
                                                                  Navigator.of(
                                                                          context,
                                                                          rootNavigator:
                                                                              true)
                                                                      .pop();
                                                                  AppSettings
                                                                      .longFailedToast(
                                                                          'Failed to remove from favourites');
                                                                }
                                                              } catch (e) {
                                                                Navigator.of(
                                                                        context,
                                                                        rootNavigator:
                                                                            true)
                                                                    .pop();
                                                                AppSettings
                                                                    .longFailedToast(
                                                                        'Failed to remove from favourites');
                                                              }
                                                            } else {
                                                              try {
                                                                bool
                                                                    tankerResponse =
                                                                    await AppSettings.addFavourites(
                                                                        suppliersList[index]
                                                                            .supplier_id);
                                                                if (tankerResponse) {
                                                                  Navigator.of(
                                                                          context,
                                                                          rootNavigator:
                                                                              true)
                                                                      .pop();
                                                                  AppSettings
                                                                      .longSuccessToast(
                                                                          'Supplier added to favourites');
                                                                  await getAllSuppliersData();
                                                                  await getConnectedSuppliersData();
                                                                  await getAllFavouritesData();
                                                                } else {
                                                                  Navigator.of(
                                                                          context,
                                                                          rootNavigator:
                                                                              true)
                                                                      .pop();
                                                                  AppSettings
                                                                      .longFailedToast(
                                                                          'Failed to add favourites');
                                                                }
                                                              } catch (e) {
                                                                Navigator.of(
                                                                        context,
                                                                        rootNavigator:
                                                                            true)
                                                                    .pop();
                                                                AppSettings
                                                                    .longFailedToast(
                                                                        'Failed to add favourites');
                                                              }
                                                            }
                                                          },
                                                          child: favouriteIds.contains(
                                                                  suppliersList[
                                                                          index]
                                                                      .supplier_id)
                                                              ? Image.asset(
                                                                  'images/heart_active.png',
                                                                  fit: BoxFit
                                                                      .cover,
                                                                  width:
                                                                      16, // Match the diameter of the CircleAvatar
                                                                  height: 16,
                                                                )
                                                              : Image.asset(
                                                                  'images/heart_outline.png',
                                                                  fit: BoxFit
                                                                      .cover,
                                                                  width:
                                                                      16, // Match the diameter of the CircleAvatar
                                                                  height: 16,
                                                                ),
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                      Divider(
                                        color: Colors.grey.shade300,
                                      ),
                                      SizedBox(
                                        height:
                                            MediaQuery.of(context).size.height *
                                                .016,
                                      ),
                                      suppliersList[index].isConnected
                                          ? Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: [
                                                Expanded(
                                                  child: GestureDetector(
                                                    onTap: () {},
                                                    child: Container(
                                                      decoration: BoxDecoration(
                                                        color: Colors.white,
                                                        border: Border.all(
                                                          width: 1,
                                                          color:
                                                              Color(0XFF1D7AFC),
                                                        ),
                                                        borderRadius:
                                                            BorderRadius
                                                                .circular(12),
                                                      ),
                                                      alignment:
                                                          Alignment.center,
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              vertical: 12),
                                                      child: Text(
                                                        'Chat',
                                                        style: fontTextStyle(
                                                            12,
                                                            Color(0XFF1D7AFC),
                                                            FontWeight.w600),
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                                SizedBox(
                                                  width: MediaQuery.of(context)
                                                          .size
                                                          .width *
                                                      .010,
                                                ),
                                                Expanded(
                                                  child: GestureDetector(
                                                    onTap: () {
                                                      Navigator.push(
                                                        context,
                                                        MaterialPageRoute(
                                                          builder: (context) =>
                                                              SupplierScreen(
                                                            details:
                                                                suppliersList[
                                                                    index],
                                                          ),
                                                        ),
                                                      );
                                                    },
                                                    child: Container(
                                                      decoration: BoxDecoration(
                                                        color:
                                                            Color(0XFF1D7AFC),
                                                        border: Border.all(
                                                          width: 1,
                                                          color: Colors.white,
                                                        ),
                                                        borderRadius:
                                                            BorderRadius
                                                                .circular(12),
                                                      ),
                                                      alignment:
                                                          Alignment.center,
                                                      padding:
                                                          EdgeInsets.symmetric(
                                                              vertical: 12),
                                                      child: Text(
                                                        'Place Order',
                                                        style: fontTextStyle(
                                                            12,
                                                            Colors.white,
                                                            FontWeight.w600),
                                                      ),
                                                    ),
                                                  ),
                                                )
                                              ],
                                            )
                                          : Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Expanded(
                                                  child: GestureDetector(
                                                    onTap: () async {
                                                      var payload = new Map<
                                                          String, dynamic>();
                                                      payload["customerId"] =
                                                          AppSettings
                                                              .customerId;
                                                      payload["supplierId"] =
                                                          suppliersList[index]
                                                              .supplier_id;

                                                      bool requestStatus =
                                                          await AppSettings
                                                              .connectRequest(
                                                                  payload);

                                                      if (requestStatus) {
                                                        AppSettings
                                                            .longSuccessToast(
                                                                "Request Sent Successfully");
                                                        await getAllSuppliersData();
                                                        await getConnectedSuppliersData();
                                                      } else {
                                                        AppSettings.longFailedToast(
                                                            "Request Sent faileds");
                                                      }
                                                    },
                                                    child: Container(
                                                      decoration: BoxDecoration(
                                                          shape: BoxShape
                                                              .rectangle,
                                                          color:
                                                              Color(0XFFFFFFFF),
                                                          border: Border.all(
                                                            width: 1,
                                                            color: Color(
                                                                0XFF098603),
                                                          ),
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(
                                                            24,
                                                          )),
                                                      alignment:
                                                          Alignment.center,
                                                      child: Padding(
                                                        padding:
                                                            EdgeInsets.fromLTRB(
                                                                24, 12, 24, 12),
                                                        child: Text('Connect',
                                                            style: fontTextStyle(
                                                                12,
                                                                Color(
                                                                    0XFF098603),
                                                                FontWeight
                                                                    .w600)),
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            )
                                    ],
                                  ),
                                ),
                              );
                            })),
                  ],
                ),
              )
            : Center(
                child: Text(
                  'No Data Available',
                  style: fontTextStyle(12, Color(0XFF000000), FontWeight.w500),
                ),
              );
  }

  Widget favorites() {
    return isFavouriteDataLoading
        ? Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          )
        : favouritesList.isNotEmpty
            ? Padding(
                padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: ListView.separated(
                        padding: EdgeInsets.all(8),
                        itemCount: favouritesList.length,
                        separatorBuilder: (context, index) => SizedBox(
                          height: MediaQuery.of(context).size.height * .008,
                        ),
                        itemBuilder: (BuildContext context, int index) {
                          final supplier = favouritesList[index];
                          final currentSupplierId = supplier.supplier_id;

                          final isConnected = connectedSuppliersList.any(
                            (item) => item.supplier_id == currentSupplierId,
                          );

                          return Container(
                            decoration: BoxDecoration(
                              color: Color(0XFFFFFFFF),
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(
                                color: Colors.grey.shade300,
                                width: 1,
                              ),
                            ),
                            child: Padding(
                              padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                              child: Column(
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      CircleAvatar(
                                        radius: 20,
                                        backgroundColor: Color(0XFFE8F2FF),
                                        child: Image.asset(
                                          'images/profile_user.png',
                                          fit: BoxFit.cover,
                                          width: 50,
                                          height: 50,
                                        ),
                                      ),
                                      SizedBox(
                                        width:
                                            MediaQuery.of(context).size.width *
                                                .012,
                                      ),
                                      Expanded(
                                        flex: 2,
                                        child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Visibility(
                                                  visible:
                                                      supplier.supplier_name !=
                                                          '',
                                                  child: Text(
                                                    supplier.supplier_name,
                                                    style: fontTextStyle(
                                                        16,
                                                        Color(0XFF2D2E30),
                                                        FontWeight.w600),
                                                  ),
                                                ),
                                                Row(
                                                  children: [
                                                    Image.asset(
                                                      'images/star.png',
                                                      fit: BoxFit.cover,
                                                      width: 16,
                                                      height: 16,
                                                    ),
                                                    Text(
                                                      '4.2 (20K+ Ratings)',
                                                      style: fontTextStyle(
                                                          9,
                                                          Color(0XFF515253),
                                                          FontWeight.w400),
                                                    ),
                                                  ],
                                                )
                                              ],
                                            ),
                                            Text(
                                              'Drinking | Bore Water',
                                              style: fontTextStyle(
                                                  12,
                                                  Color(0XFF4692FD),
                                                  FontWeight.w500),
                                            ),
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: [
                                                Text(
                                                    '${supplier.displayAddress}   ${supplier.distanceInMeters} Km',
                                                    style: fontTextStyle(
                                                        12,
                                                        Color(0XFF515253),
                                                        FontWeight.w400)),
                                                GestureDetector(
                                                  onTap: () async {
                                                    AppSettings.preLoaderDialog(
                                                        context);
                                                    try {
                                                      bool tankerResponse =
                                                          await AppSettings
                                                              .removeFavourites(
                                                                  supplier
                                                                      .supplier_id);
                                                      Navigator.of(context,
                                                              rootNavigator:
                                                                  true)
                                                          .pop();
                                                      if (tankerResponse) {
                                                        AppSettings
                                                            .longSuccessToast(
                                                                'Supplier removed from favourites');
                                                        await getAllSuppliersData();
                                                        await getConnectedSuppliersData();
                                                        await getAllFavouritesData();
                                                      } else {
                                                        AppSettings.longFailedToast(
                                                            'Failed to remove from favourites');
                                                      }
                                                    } catch (e) {
                                                      Navigator.of(context,
                                                              rootNavigator:
                                                                  true)
                                                          .pop();
                                                      AppSettings.longFailedToast(
                                                          'Failed to remove from favourites');
                                                    }
                                                  },
                                                  child: Image.asset(
                                                    'images/heart_active.png',
                                                    fit: BoxFit.cover,
                                                    width: 16,
                                                    height: 16,
                                                  ),
                                                )
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  Divider(color: Colors.grey.shade300),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        'Plan',
                                        style: fontTextStyle(10,
                                            Color(0XFF343637), FontWeight.w400),
                                      ),
                                      Text(
                                        '15,000 / week',
                                        style: fontTextStyle(10,
                                            Color(0XFF2D2E30), FontWeight.w500),
                                      )
                                    ],
                                  ),
                                  SizedBox(
                                    height: MediaQuery.of(context).size.height *
                                        .016,
                                  ),
                                  isConnected
                                      ? Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Expanded(
                                              child: GestureDetector(
                                                onTap: () {},
                                                child: Container(
                                                  decoration: BoxDecoration(
                                                    color: Colors.white,
                                                    border: Border.all(
                                                      width: 1,
                                                      color: Color(0XFF1D7AFC),
                                                    ),
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            12),
                                                  ),
                                                  alignment: Alignment.center,
                                                  padding: EdgeInsets.symmetric(
                                                      vertical: 12),
                                                  child: Text(
                                                    'Chat',
                                                    style: fontTextStyle(
                                                        12,
                                                        Color(0XFF1D7AFC),
                                                        FontWeight.w600),
                                                  ),
                                                ),
                                              ),
                                            ),
                                            SizedBox(
                                              width: MediaQuery.of(context)
                                                      .size
                                                      .width *
                                                  .010,
                                            ),
                                            Expanded(
                                              child: GestureDetector(
                                                onTap: () {
                                                  Navigator.push(
                                                    context,
                                                    MaterialPageRoute(
                                                      builder: (context) =>
                                                          SupplierScreen(
                                                        details: supplier,
                                                      ),
                                                    ),
                                                  );
                                                },
                                                child: Container(
                                                  decoration: BoxDecoration(
                                                    color: Color(0XFF1D7AFC),
                                                    border: Border.all(
                                                      width: 1,
                                                      color: Colors.white,
                                                    ),
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            12),
                                                  ),
                                                  alignment: Alignment.center,
                                                  padding: EdgeInsets.symmetric(
                                                      vertical: 12),
                                                  child: Text(
                                                    'Place Order',
                                                    style: fontTextStyle(
                                                        12,
                                                        Colors.white,
                                                        FontWeight.w600),
                                                  ),
                                                ),
                                              ),
                                            )
                                          ],
                                        )
                                      : Row(
                                          children: [
                                            Expanded(
                                              child: GestureDetector(
                                                onTap: () {},
                                                child: Container(
                                                  decoration: BoxDecoration(
                                                    color: Colors.white,
                                                    border: Border.all(
                                                      width: 1,
                                                      color: Color(0XFF098603),
                                                    ),
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            24),
                                                  ),
                                                  alignment: Alignment.center,
                                                  padding: EdgeInsets.symmetric(
                                                      vertical: 12),
                                                  child: Text(
                                                    'Connect',
                                                    style: fontTextStyle(
                                                        12,
                                                        Color(0XFF098603),
                                                        FontWeight.w600),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              )
            : Center(
                child: Text(
                  'No Data Available',
                  style: fontTextStyle(12, Color(0XFF000000), FontWeight.w500),
                ),
              );
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: _controller.length, // Two tabs
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar:AppBar(
          elevation: 0,
          backgroundColor: Colors.white,
          title: Text(
            'My Suppliers',
            style: fontTextStyle(14, Color(0XFF2A2A2A), FontWeight.w500),
          ),
          iconTheme: IconThemeData(color: Color(0XFF2A2A2A)),
          actions: [
            Row(
              children: [
                Padding(
                  padding: EdgeInsets.fromLTRB(10, 10, 0, 10),
                  child: IconButton(
                    icon: Image(
                        image: AssetImage(
                            'images/calender_supplier_landing.png')),
                    onPressed: () {},
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
                  child: IconButton(
                    icon: Image.asset(
                      'images/notification_appbar.png', // Example URL image
                    ),
                    onPressed: () {},
                  ),
                )
              ],
            )
          ],
          leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Padding(
              padding: const EdgeInsets.fromLTRB(
                  8, 8, 8, 8), // Add padding if needed
              child: Image.asset(
                'images/backbutton_appbar.png', // Replace with your image path
                fit: BoxFit.contain, // Adjust the fit
              ),
            ),
          ),
          bottom: PreferredSize(
            preferredSize: Size.fromHeight(70.0),
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              padding: EdgeInsets.all(4),
              decoration: BoxDecoration(
                color: Color(0xFFF5F6F6),
                borderRadius: BorderRadius.circular(23),
                // Remove all borders/shadows
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(19),
                child: TabBar(
                  controller: _controller,
                  indicator: BoxDecoration(), // No underline
                  indicatorColor: Colors.transparent, // Extra safety
                  labelPadding: EdgeInsets.zero,
                  dividerColor: Colors
                      .transparent, // <-- Removes line between TabBar and TabBarView (Flutter 3.10+)
                  tabs: List.generate(3, (index) {
                    final labels = [
                      'Suppliers',
                      'My Suppliers',
                      'Favourites'
                    ];
                    return Container(
                      decoration: BoxDecoration(
                        color: _controller.index == index
                            ? Color(0XFFF5CD47)
                            : Color(0xFFF5F6F6),
                        borderRadius: BorderRadius.circular(27),
                      ),
                      child: Tab(
                        child: Center(
                          child: Text(
                            labels[index],
                            style: fontTextStyle(
                              12,
                              Color(0XFF3B3B3B),
                              FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    );
                  }),
                ),
              ),
            ),
          ),
        ),
        body: Builder(
          builder: (BuildContext context) {
            return TabBarView(
              controller: _controller,
              children: [
                // Tab 1 content
                otherSuppliers(),

                // Tab 2 content
                mySuppliers(),
                // Tab 2 content
                favorites()
              ],
            );
          },
        ),
      ),
    );
  }
}
