
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:healthcare_pharmacy/dashboard.dart';
import 'package:healthcare_pharmacy/maps/app_colors.dart';
import 'package:healthcare_pharmacy/models/offersview_model.dart';
import 'package:healthcare_pharmacy/createoffers.dart';
import 'package:healthcare_pharmacy/settings.dart';
import 'package:healthcare_pharmacy/viewpager.dart';
import 'package:intl/intl.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';


class OffersData extends StatefulWidget {
  const OffersData({Key? key}) : super(key: key);

  @override
  State<OffersData> createState() => _OffersDataState();
}

class _OffersDataState extends State<OffersData> with TickerProviderStateMixin, WidgetsBindingObserver {
  bool isOfferDataLoading=false;
  bool isSereverIssue = false;
  bool isSereverIssueConnected = false;
  bool isSereverIssuePending = false;
  var startdate;
  var enddate;
  TextEditingController updateOfferNameController = TextEditingController();
  TextEditingController updateOfferCodeController = TextEditingController();
  TextEditingController updateOfferDescriptionController = TextEditingController();
  TextEditingController updateOfferCategoryController = TextEditingController();
  TextEditingController updateDiscountController = TextEditingController();
  TextEditingController updateOfferStartDateController = TextEditingController();
  TextEditingController updateOfferEndDateController = TextEditingController();
  List<GetOffersDetailsModel> activeOffersList = [];
  List<GetOffersDetailsModel> inactiveOffersList = [];
  final ImagePicker _picker = ImagePicker();
  String updateofferUrl='';
  String dropdownTypeOfCategory = 'A {1 - 500}';
  var typeOfCategoryItems = [
    'A {1 - 500}',
    'B {501 - 1000}',
    'C {1001 - 2000}',
    'D {Above 2000}',
    'S {Special offer}',
  ];

  List updateCategoryTypes = [];

  late TabController _controller;
  bool isActiveDataLoading=false;
  bool isinactiveDataLoading=false;



  final List<Tab> topTabs = <Tab>[
    Tab(
      child: Column(
        children: [Text('Active Offers')],
      ),
    ),
    Tab(
      child: Column(
        children: [Text('InActive Offers')],
      ),
    ),
  ];
  Future<void> getActiveOffersViewData() async {
    isActiveDataLoading = true;


    try {
      var data = await AppSettings.getOffers();
      setState(() {
        List<dynamic> responseData = jsonDecode(data)['data'];
        activeOffersList  = responseData
            .map((jsonObject) => GetOffersDetailsModel.fromJson(jsonObject))
            .toList();
        isActiveDataLoading = false;
      });

    } catch (error) {
      setState(() {
        isActiveDataLoading = false;
        isSereverIssueConnected = true;
      });
    }
  }
  Future<void> getInactiveOffersViewData() async {
    isinactiveDataLoading = true;
    try {
      var response = await AppSettings.getinactiveOffers();
      setState(() {
        inactiveOffersList =
            ((jsonDecode(response)['data']) as List).map((dynamic model) {
              return GetOffersDetailsModel.fromJson(model);
            }).toList();
        isinactiveDataLoading = false;
      });


    } catch (e) {
      setState(() {
        isinactiveDataLoading = false;
        isSereverIssueConnected = true;
      });
    }
  }


  Future pickImageFromGallery(var offerCode) async {

    try {
      final image = await _picker.pickImage(source: ImageSource.gallery);
      if (image == null) return '';

      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.offerupdateuploadImageHTTPNew(image, offerCode);
      print(jsonDecode(res));

      setState(() {
        updateofferUrl = jsonDecode(res)['picture'][0]['url'];
        print("update url: $updateofferUrl");
      });

      Navigator.of(context, rootNavigator: true).pop();
      if(res.contains("error")){
        return 'some thing went wrong please try again';
      }
      else{
        return jsonDecode(res)['picture'][0]['url'];
      }

    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
      return 'some thing went wrong please try again';
    }
  }

  Future<String> takeImageFromCamera(String offerCode) async {
    try {
      final image = await _picker.pickImage(source: ImageSource.camera);
      if (image == null) return '';

      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.offerupdateuploadImageHTTPNew(image, offerCode);
      print(jsonDecode(res));

      setState(() {
        updateofferUrl = jsonDecode(res)['picture'][0]['url'];
        print("update url: $updateofferUrl");
      });

      Navigator.of(context, rootNavigator: true).pop();
      if(res.contains("error")){
        return 'some thing went wrong please try again';
      }
      else{
        return jsonDecode(res)['picture'][0]['url'];
      }

    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
      return 'some thing went wrong please try again';
    }

  }




  showUpdateOfferDialog(GetOffersDetailsModel object, int index) async {
    updateOfferNameController.text = object.offer_name!;
    updateOfferCodeController.text = object.offer_code!;
    updateOfferDescriptionController.text = object.description!;
    updateOfferStartDateController.text=object.starting_date!;
    updateOfferEndDateController.text=object.ending_date!;
    setState(() {
      dropdownTypeOfCategory=object.category.toString().toString()??'';
    });
    updateofferUrl=object.picture[0].url;
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, StateSetter setState) {
            var data=activeOffersList[index];
            print("result$updateofferUrl");
            return AlertDialog(
              title: const Text('Update Offer'),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    // ImageView
                    InkWell(
                      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(object.offer_code!).then((value) {
                                             print("datatatttta$value");
                                             setState(() {
                                               updateofferUrl = value;
                                               // print(updateofferUrl);
                                             });
                                           });
                                          Navigator.pop(context);
                                        },
                                      ),
                                      SizedBox(
                                        width:
                                        MediaQuery.of(context).size.width * .20,
                                      ),
                                      GestureDetector(
                                        child: Icon(
                                          Icons.photo,
                                          size: 100,
                                          color: primaryColor,
                                        ),
                                        onTap: () async {
                                           await pickImageFromGallery(object.offer_code).then((value) {
                                             print("datatatttta$value");
                                             setState(() {
                                               updateofferUrl = value;
                                               // print(updateofferUrl);
                                             });
                                           });;
                                          Navigator.pop(context);
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            });
                      },
                      child: Container(
                        width: MediaQuery.of(context).size.width,
                        height: 150,
                        child: updateofferUrl.isEmpty
                            ? Image.network(
                          "https://assets.aboutamazon.com/dims4/default/1db03c8/2147483647/strip/false/crop/2000x1125+0+0/resize/1200x675!/quality/90/?url=https%3A%2F%2Famazon-blogs-brightspot.s3.amazonaws.com%2Fa3%2Fc2%2F5c0b93db41d789be1bec015003bd%2Fpharmacy-hero-2000x1125.jpg",
                          fit: BoxFit.cover,
                        )
                            : Image.network(
                          updateofferUrl,
                          fit: BoxFit.cover,
                        ),
                      ),


                    ),
                    const SizedBox(
                      height: 20,
                    ),

                    // Offer Name
                    Container(
                      padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                      child: TextFormField(
                        cursorColor: greyColor,
                        controller: updateOfferNameController,
                        textCapitalization: TextCapitalization.words,
                        decoration: const InputDecoration(
                          prefixIcon: Icon(
                            Icons.person,
                            color: primaryColor,
                          ),
                          border: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor)),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: greyColor),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: greyColor),
                          ),
                          labelText: 'Offer name',
                          labelStyle: TextStyle(
                            color: greyColor, //<-- SEE HERE
                          ),
                        ),
                      ), //tanker name
                    ),
                    const SizedBox(
                      height: 20,
                    ),

                    Container(
                      //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                      child: TextFormField(
                        cursorColor: greyColor,
                        controller: updateOfferCodeController,
                        textCapitalization: TextCapitalization.words,
                        decoration: const InputDecoration(
                          prefixIcon: Icon(
                            Icons.numbers,
                            color: primaryColor,
                          ),
                          border: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor)),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: greyColor),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: greyColor),
                          ),
                          labelText: 'Offer Code',
                          labelStyle: TextStyle(
                            color: greyColor, //<-- SEE HERE
                          ),
                        ),
                      ), //tanker name
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    Container(
                      //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                      child: TextFormField(
                        cursorColor: greyColor,
                        controller: updateOfferDescriptionController,
                        textCapitalization: TextCapitalization.words,
                        decoration: const InputDecoration(
                          prefixIcon: Icon(
                            Icons.description,
                            color: primaryColor,
                          ),
                          border: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor)),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: greyColor),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: greyColor),
                          ),
                          labelText: 'Offer Description',
                          labelStyle: TextStyle(
                            color: greyColor, //<-- SEE HERE
                          ),
                        ),
                      ), //tanker name
                    ),

                    const SizedBox(
                      height: 30,
                    ),


                    Container(
                      child: DropdownButtonFormField(
                        // Initial Value
                        value: dropdownTypeOfCategory,
                        isExpanded: true,
                        decoration: const InputDecoration(
                          prefixIcon: Icon(
                            Icons.type_specimen,
                            color: primaryColor,
                          ),
                          border: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor)),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: greyColor),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: greyColor),
                          ),
                          labelText: 'Type of category',
                          labelStyle: TextStyle(
                            color: greyColor, //<-- SEE HERE
                          ),
                        ),

                        hint: Text('Select Type of category'),
                        // Down Arrow Icon
                        icon: const Icon(Icons.keyboard_arrow_down),

                        // Array list of items
                        items: typeOfCategoryItems.map((String items) {
                          return DropdownMenuItem(
                            value: items,
                            child: Text(items),
                          );
                        }).toList(),
                        // After selecting the desired option,it will
                        // change button value to selected value
                        onChanged: (String? newValue) {
                          setState(() {
                            dropdownTypeOfCategory = newValue!;
                          });
                        },
                      ),
                    ),








                    const SizedBox(
                      height: 20,
                    ),
                    Container(
                      child: TextFormField(
                        readOnly: true,
                        cursorColor: greyColor,
                        controller: updateOfferStartDateController,
                        decoration: InputDecoration(
                          labelText: 'Select Start Date',
                          prefixIcon: IconButton(
                            icon:  Icon(
                              Icons.date_range,
                              color: primaryColor,
                            ),
                            onPressed: () async {
                              DatePicker.showDatePicker(
                                context,
                                dateFormat: 'dd MMMM yyyy',
                                initialDateTime: DateTime.now(),
                                minDateTime:DateTime.now(),
                                maxDateTime: DateTime.now().add(Duration(days: 365)),
                                onMonthChangeStartWithFirstDate: true,
                                pickerMode: DateTimePickerMode.datetime,
                                pickerTheme: DateTimePickerTheme(
                                  // backgroundColor: Colors.white,
                                  cancelTextStyle: labelTextStyle(),
                                  confirmTextStyle: labelTextStyle(),
                                  // showTitle: true,
                                  //title: Text('Pick date and time'),
                                  itemTextStyle: valuesTextStyle(),
                                ),
                                onConfirm: (dateTime, List<int> index)async {
                                  DateTime selectdate = dateTime;
                                  setState(() {
                                    startdate = DateFormat('dd-MMM-yyyy').format(selectdate);
                                  });

                                  if(startdate!=''){
                                    setState(() {
                                      updateOfferStartDateController.text=startdate.toString();
                                    });
                                  }
                                  else {
                                    AppSettings.longFailedToast('Select start date');
                                  }
                                },
                              );
                            },
                          ),

                          labelStyle: const TextStyle(
                            color: greyColor, //<-- SEE HERE
                          ),
                          border: const OutlineInputBorder(
                              borderSide: BorderSide(color: primaryColor)),
                          focusedBorder: const OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                          ),
                          enabledBorder: const OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                          ),

                        ),

                      ),
                    ),

                    const SizedBox(
                      height: 20,
                    ),
                    Container(
                      child: TextFormField(
                        readOnly: true,
                        cursorColor: greyColor,
                        controller: updateOfferEndDateController,
                        decoration: InputDecoration(
                          labelText: 'Select end Date',
                          prefixIcon: IconButton(
                            icon:  Icon(
                              Icons.date_range,
                              color: primaryColor,
                            ),
                            onPressed: () async {
                              DatePicker.showDatePicker(
                                context,
                                dateFormat: 'dd MMMM yyyy',
                                initialDateTime: DateTime.now(),
                                minDateTime:DateTime.now(),
                                maxDateTime: DateTime.now().add(Duration(days: 365)),
                                onMonthChangeStartWithFirstDate: true,
                                pickerMode: DateTimePickerMode.datetime,
                                pickerTheme: DateTimePickerTheme(
                                  // backgroundColor: Colors.white,
                                  cancelTextStyle: labelTextStyle(),
                                  confirmTextStyle: labelTextStyle(),
                                  // showTitle: true,
                                  //title: Text('Pick date and time'),
                                  itemTextStyle: valuesTextStyle(),
                                ),
                                onConfirm: (dateTime, List<int> index)async {
                                  DateTime selectdate = dateTime;
                                  setState(() {
                                    enddate = DateFormat('dd-MMM-yyyy').format(selectdate);
                                  });

                                  if(enddate!=''){
                                    setState(() {
                                      updateOfferEndDateController.text=enddate.toString();
                                    });
                                  }
                                  else {
                                    AppSettings.longFailedToast('Select end date');
                                  }
                                },
                              );
                            },
                          ),

                          labelStyle: const TextStyle(
                            color: greyColor, //<-- SEE HERE
                          ),
                          border: const OutlineInputBorder(
                              borderSide: BorderSide(color: primaryColor)),
                          focusedBorder: const OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                          ),
                          enabledBorder: const OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor),
                          ),
                        ),

                      ),
                    ),//address description

                    const SizedBox(
                      height: 30,
                    ),

                  ],
                ),
              ),
              actions: <Widget>[
                TextButton(
                  child: Text('cancel', style: textButtonStyle()),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                TextButton(
                  child: Text('Update', style: textButtonStyle()),
                  onPressed: () async {
                    if (updateOfferNameController.text != '' ) {
                      AppSettings.preLoaderDialog(context);

                      Map<String, dynamic> payload = {
                        "offer_name": updateOfferNameController.text.toString(),
                        "offer_code": updateOfferCodeController.text.toString(),
                        "description":updateOfferDescriptionController.text.toString(),
                        "category":dropdownTypeOfCategory.toString(),
                        "starting_date":updateOfferStartDateController.text.toString(),
                        "ending_date": updateOfferEndDateController.text.toString(),
                        "picture": [
                          {
                            "url":updateofferUrl
                          }
                        ],
                        "offer_status": "active",
                      };

                      bool offerStatus = await AppSettings.updateOffers(object.offer_code, payload);
                      try {
                        if (offerStatus) {
                          Navigator.of(context, rootNavigator: true).pop();
                          AppSettings.longSuccessToast(
                              "Offer Updated Successfully");
                          updateOfferNameController.text = '';
                          updateOfferCodeController.text = '';
                          updateOfferDescriptionController.text = '';
                          updateOfferStartDateController.text = '';
                          updateOfferEndDateController.text = '';
                          await getActiveOffersViewData();
                          await Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const OffersData()),
                          );
                        } else {
                          Navigator.of(context, rootNavigator: true).pop();
                          AppSettings.longFailedStyledToast(
                              "Offer upadtion failed", context);
                          Navigator.of(context).pop();
                        }
                      } catch (exception) {
                        Navigator.of(context).pop();
                        print(exception);
                      }
                    } else {
                      AppSettings.longFailedStyledToast("enter details", context);
                    }
                  },
                ),
              ],
            );
          },
        );
      },
    );
  }


  @override
  void initState() {
    // TODO: implement initState
    _controller = TabController(vsync: this, length: 2);
    getActiveOffersViewData();
    getInactiveOffersViewData();
    WidgetsBinding.instance!.addObserver(this);
    super.initState();
  }
  @override
  void dispose() {
    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // The app has been resumed from the background
      // Add your code here to handle the resume event
     // AppSettings.longSuccessToast("Successfully");
    }
  }

  Widget renderzActiveUi(){
    if(activeOffersList.length!=0){

      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(child:ListView.builder(
                padding:  EdgeInsets.all(0),
                  itemCount: activeOffersList .length,
                itemBuilder: (context,index){
                  var data=activeOffersList[index];
                  return GestureDetector(
                    onTap: () {
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (__) => new Viewpager(activeOffersList,index)));
                    },
                    child: Card(
                      child: ListTile(
                        leading: Container(
                          width: 100,
                          height: 300,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            image: DecorationImage(
                              fit: BoxFit.cover,
                              alignment: Alignment.center, // Align the image within the container
                              image: data.picture.isEmpty
                                  ? AssetImage('images/logo.png') as ImageProvider
                                  : NetworkImage(activeOffersList[index].picture[0].url),
                            ),
                          ),
                        ),


                        title: RichText(
                          text: TextSpan(
                            style: DefaultTextStyle.of(context).style,
                            children: <TextSpan>[
                              TextSpan(
                                text: 'Name: ',
                                style: TextStyle(
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              TextSpan(
                                text: activeOffersList[index].offer_name,
                                style: TextStyle(
                                  color: primaryColor,
                                ),
                              ),
                            ],
                          ),
                        ),
                        subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // ... (other RichText widgets for Code, Description, Start Date, End Date)
                            RichText(
                              text: TextSpan(
                                style: DefaultTextStyle.of(context).style,
                                children: <TextSpan>[
                                  TextSpan(
                                    text: 'Code: ',
                                    style: TextStyle(
                                      color: Colors.black, // Change the color for "Description" text
                                      fontWeight: FontWeight.bold, // You can apply other styles too
                                    ),
                                  ),
                                  TextSpan(
                                    text: activeOffersList[index].offer_code,
                                    style: TextStyle(
                                      color: primaryColor, // Change the color for description content
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            RichText(
                              text: TextSpan(
                                style: DefaultTextStyle.of(context).style,
                                children: <TextSpan>[
                                  TextSpan(
                                    text: 'Description: ',
                                    style: TextStyle(
                                      color: Colors.black, // Change the color for "Description" text
                                      fontWeight: FontWeight.bold, // You can apply other styles too
                                    ),
                                  ),
                                  TextSpan(
                                    text: activeOffersList[index].description,
                                    style: TextStyle(
                                      color:primaryColor, // Change the color for description content
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            RichText(
                              text: TextSpan(
                                style: DefaultTextStyle.of(context).style,
                                children: <TextSpan>[
                                  TextSpan(
                                    text: 'Category: ',
                                    style: TextStyle(
                                      color: Colors.black, // Change the color for "Description" text
                                      fontWeight: FontWeight.bold, // You can apply other styles too
                                    ),
                                  ),
                                  TextSpan(
                                    text: activeOffersList[index].category,
                                    style: TextStyle(
                                      color:primaryColor, // Change the color for description content
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            RichText(
                              text: TextSpan(
                                style: DefaultTextStyle.of(context).style,
                                children: <TextSpan>[
                                  TextSpan(
                                    text: 'Start Date: ',
                                    style: TextStyle(
                                      color: Colors.black, // Change the color for "Description" text
                                      fontWeight: FontWeight.bold, // You can apply other styles too
                                    ),
                                  ),
                                  TextSpan(
                                    text: activeOffersList[index].starting_date,

                                    style: TextStyle(
                                      color:primaryColor, // Change the color for description content
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            RichText(
                              text: TextSpan(
                                style: DefaultTextStyle.of(context).style,
                                children: <TextSpan>[
                                  TextSpan(
                                    text: 'End Date  :',
                                    style: TextStyle(
                                      color: Colors.black, // Change the color for "Description" text
                                      fontWeight: FontWeight.bold, // You can apply other styles too
                                    ),
                                  ),
                                  TextSpan(
                                    text: activeOffersList[index].ending_date,
                                    style: TextStyle(
                                      color:primaryColor, // Change the color for description content
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                IconButton(
                                  icon: Icon(Icons.edit),
                                  onPressed: () {

                                    showUpdateOfferDialog(activeOffersList[index], index);
                                  },
                                ),
                                Switch(
                                  value: false, // Replace with your actual property
                                  onChanged: (newValue) {
                                    if (newValue) {
                                      // Show your AlertDialog for confirmation
                                      showDialog(
                                        context: context,
                                        builder: (BuildContext context) => AlertDialog(
                                          title: Text(
                                            'Do you want to In_Activate the offer?',
                                            style: TextStyle(
                                              color: primaryColor,
                                              fontSize: 16,
                                            ),
                                          ),
                                          actionsAlignment: MainAxisAlignment.spaceBetween,
                                          actions: [
                                            TextButton(
                                              onPressed: () async {
                                                bool deleteOfferStatus =
                                                await AppSettings.deleteOffers(
                                                    activeOffersList[index].offer_code);
                                                if (deleteOfferStatus) {
                                                  getActiveOffersViewData();
                                                  AppSettings.longSuccessToast(
                                                      'Offer In_Active Successfully!!');
                                                  getInactiveOffersViewData();
                                                  // Update the isActive property

                                                } else {
                                                  AppSettings.longFailedToast('Offer In_Active failed');
                                                }
                                                Navigator.of(context).pop(true);
                                              },
                                              child: const Text(
                                                'Yes',
                                                style: TextStyle(
                                                  color: primaryColor,
                                                  fontSize: 18,
                                                ),
                                              ),
                                            ),
                                            TextButton(
                                              onPressed: () {
                                                Navigator.of(context).pop(true);
                                              },
                                              child: const Text(
                                                'No',
                                                style: TextStyle(
                                                  color: primaryColor,
                                                  fontSize: 18,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      );
                                    } else {
                                      // Handle the case where the user wants to undo the In_Activation
                                      // Update the isActive property
                                      //m;./ activeOffersList[index].isActive = false;
                                      // You might want to add code to revert the In_Activation in your data model here
                                    }

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






                }) ),
            Padding(
              padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
              child: CircleAvatar(
                backgroundColor: primaryColor,
                radius: 40,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    IconButton(
                      iconSize: 40,
                      icon: const Icon(
                        Icons.add,
                        color: Colors.white,
                      ),
                      onPressed: () async{
                        Navigator.pop(context);
                        await Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => offers()),
                        );
                        //showBoreAddingDialog();
                      },
                    ),
                    /* Padding(
                      padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
                      child: Text(
                        'Add Tanks ',
                        style: TextStyle(color: Colors.white),
                      ),
                    )*/
                  ],
                ),
              ),
            ),
          ]);
    }
    else{
      return  Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: MediaQuery.of(context).size.height * .25,),
                Text('Click below icon to add new Offer'),
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: primaryColor,
                  radius: 40,
                  child: IconButton(
                    iconSize: 40,
                    icon: const Icon(
                      Icons.add,
                      color: Colors.white,
                    ),
                    onPressed: () async {
                      Navigator.pop(context);
                      await Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => offers()),
                      );
                    },
                  ),
                )
              ],
            ),
          )
      );
    }
  }

  Widget renderzInactiveUi(){
    if(inactiveOffersList.length!=0){

      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(child:ListView.builder(
                padding:  EdgeInsets.all(0),
                itemCount: inactiveOffersList.length,
                itemBuilder: (BuildContext context, int index) {
                  var data=inactiveOffersList[index];
                  return Card(
                    margin: EdgeInsets.all(8.0),
                    child: ListTile(
                      contentPadding: EdgeInsets.all(8.0),
                      leading: Container(
                        width: 100,
                        height: 300,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          image: DecorationImage(
                            fit: BoxFit.cover,
                            alignment: Alignment.center, // Align the image within the container
                            image: data.picture.isEmpty
                                ? AssetImage('images/logo.png') as ImageProvider
                                : NetworkImage(inactiveOffersList[index].picture[0].url),
                          ),
                        ),
                      ),
                      title: RichText(
                        text: TextSpan(
                          style: DefaultTextStyle.of(context).style,
                          children: <TextSpan>[
                            TextSpan(
                              text: 'Name: ',
                              style: TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            TextSpan(
                              text: inactiveOffersList[index].offer_name,
                              style: TextStyle(
                                color: primaryColor,
                              ),
                            ),
                          ],
                        ),
                      ),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          RichText(
                            text: TextSpan(
                              style: DefaultTextStyle.of(context).style,
                              children: <TextSpan>[
                                TextSpan(
                                  text: 'Code: ',
                                  style: TextStyle(
                                    color: Colors.black, // Change the color for "Description" text
                                    fontWeight: FontWeight.bold, // You can apply other styles too
                                  ),
                                ),
                                TextSpan(
                                  text: inactiveOffersList[index].offer_code,
                                  style: TextStyle(
                                    color: primaryColor, // Change the color for description content
                                  ),
                                ),
                              ],
                            ),
                          ),
                          RichText(
                            text: TextSpan(
                              style: DefaultTextStyle.of(context).style,
                              children: <TextSpan>[
                                TextSpan(
                                  text: 'Description: ',
                                  style: TextStyle(
                                    color: Colors.black, // Change the color for "Description" text
                                    fontWeight: FontWeight.bold, // You can apply other styles too
                                  ),
                                ),
                                TextSpan(
                                  text: inactiveOffersList[index].description,
                                  style: TextStyle(
                                    color:primaryColor, // Change the color for description content
                                  ),
                                ),
                              ],
                            ),
                          ),
                          RichText(
                            text: TextSpan(
                              style: DefaultTextStyle.of(context).style,
                              children: <TextSpan>[
                                TextSpan(
                                  text: 'Category: ',
                                  style: TextStyle(
                                    color: Colors.black, // Change the color for "Description" text
                                    fontWeight: FontWeight.bold, // You can apply other styles too
                                  ),
                                ),
                                TextSpan(
                                  text: inactiveOffersList[index].category,
                                  style: TextStyle(
                                    color:primaryColor, // Change the color for description content
                                  ),
                                ),
                              ],
                            ),
                          ),
                          RichText(
                            text: TextSpan(
                              style: DefaultTextStyle.of(context).style,
                              children: <TextSpan>[
                                TextSpan(
                                  text: 'Start Date: ',
                                  style: TextStyle(
                                    color: Colors.black, // Change the color for "Description" text
                                    fontWeight: FontWeight.bold, // You can apply other styles too
                                  ),
                                ),
                                TextSpan(
                                  text: inactiveOffersList[index].starting_date,

                                  style: TextStyle(
                                    color:primaryColor, // Change the color for description content
                                  ),
                                ),
                              ],
                            ),
                          ),

                          RichText(
                            text: TextSpan(
                              style: DefaultTextStyle.of(context).style,
                              children: <TextSpan>[
                                TextSpan(
                                  text: 'End Date  :',
                                  style: TextStyle(
                                    color: Colors.black, // Change the color for "Description" text
                                    fontWeight: FontWeight.bold, // You can apply other styles too
                                  ),
                                ),
                                TextSpan(
                                  text: inactiveOffersList[index].ending_date,
                                  style: TextStyle(
                                    color:primaryColor, // Change the color for description content
                                  ),
                                ),
                              ],
                            ),
                          ),

                          SizedBox(height: 8),




                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              TextButton(
                                onPressed: () {
                                  showDialog(
                                    //if set to true allow to close popup by tapping out of the popup
                                    //barrierDismissible: false,
                                    context: context,
                                    builder: (BuildContext context) => AlertDialog(
                                      title: const Text(
                                        'Do you want to Re-Active offer ??',
                                        style: TextStyle(
                                          color: primaryColor,
                                          fontSize: 16,
                                        ),
                                      ),
                                      actionsAlignment: MainAxisAlignment.spaceBetween,
                                      actions: [
                                        TextButton(
                                          onPressed: () async {
                                            bool deleteTankStatus = await AppSettings.reactiveOffers(inactiveOffersList[index].offer_code);

                                            if (deleteTankStatus) {
                                              AppSettings.longSuccessToast('offer Re-Active successfully');
                                              getActiveOffersViewData();
                                              getInactiveOffersViewData();
                                              Navigator.of(context).pop(true);
                                            } else {
                                              AppSettings.longFailedToast('offer Re-Active failed');
                                            }
                                          },
                                          child: const Text(
                                            'Yes',
                                            style: TextStyle(
                                              color: primaryColor,
                                              fontSize: 18,
                                            ),
                                          ),
                                        ),
                                        TextButton(
                                          onPressed: () {
                                            Navigator.of(context).pop(true);
                                          },
                                          child: const Text(
                                            'No',
                                            style: TextStyle(
                                              color: primaryColor,
                                              fontSize: 18,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                                child: Text(
                                  'Re-activate',
                                  style: TextStyle(
                                    color: primaryColor, // You can set the text color to your preference.
                                    fontSize: 16, // You can adjust the font size as needed.
                                  ),
                                ),
                              ),
                              IconButton(
                                icon: Icon(
                                  Icons.delete,
                                  color: primaryColor, // Customize the delete icon color
                                ),
                                onPressed: () async{
                                  showDialog(
                                    //if set to true allow to close popup by tapping out of the popup
                                    //barrierDismissible: false,
                                    context: context,
                                    builder: (BuildContext context) => AlertDialog(
                                      title: const Text('Do you want to delete Offer?',
                                          style: TextStyle(
                                            color: primaryColor,
                                            fontSize: 20,
                                          )),
                                      actionsAlignment: MainAxisAlignment.spaceBetween,
                                      actions: [
                                        TextButton(
                                          onPressed: ()async {
                                            bool deleteOfferStatus = await AppSettings.deleteInActiveOffer(inactiveOffersList[index].offer_code);
                                            if(deleteOfferStatus){
                                              getInactiveOffersViewData();
                                              AppSettings.longSuccessToast('Offer deleted successfully');
                                              Navigator.of(context).pop(true);

                                            }
                                            else{
                                              AppSettings.longFailedToast('Offer deletion failed');
                                            }
                                          },
                                          child: const Text('Yes',
                                              style: TextStyle(
                                                color: primaryColor,
                                                fontSize: 20,
                                              )),
                                        ),
                                        TextButton(
                                          onPressed: () {
                                            Navigator.of(context).pop(true);
                                          },
                                          child: const Text('No',
                                              style: TextStyle(
                                                color: primaryColor,
                                                fontSize: 20,
                                              )),
                                        ),
                                      ],
                                    ),
                                  );

                                },
                              ),
                            ],
                          ),

                        ],
                      ),
                    ),
                  );
                }) ),
            Padding(
              padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
              child: CircleAvatar(
                backgroundColor: primaryColor,
                radius: 40,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    IconButton(
                      iconSize: 40,
                      icon: const Icon(
                        Icons.add,
                        color: Colors.white,
                      ),
                      onPressed: () async{
                        Navigator.pop(context);
                        await Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => offers()),
                        );
                        //showBoreAddingDialog();
                      },
                    ),
                    /* Padding(
                      padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
                      child: Text(
                        'Add Tanks ',
                        style: TextStyle(color: Colors.white),
                      ),
                    )*/
                  ],
                ),
              ),
            ),
          ]);
    }
    else{
      return  Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: MediaQuery.of(context).size.height * .25,),
                Text('Click below icon to add new Offer'),
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: primaryColor,
                  radius: 40,
                  child: IconButton(
                    iconSize: 40,
                    icon: const Icon(
                      Icons.add,
                      color: Colors.white,
                    ),
                    onPressed: () async {
                      Navigator.pop(context);
                      await Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => offers()),
                      );
                    },
                  ),
                )
              ],
            ),
          )
      );
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Offers'),
        backgroundColor: primaryColor,
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () async {
            await Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => const Dashboard()),
            );
          },
        ),
        bottom: TabBar(
          controller: _controller,
          tabs: topTabs,
          indicatorColor: Colors.blue,
          unselectedLabelColor: Colors.white60,
          indicatorWeight: 2,
        ),),
      /* body: */
      body: TabBarView(controller: _controller, children: [
        /*Container(
          // color: Colors.lightGreenAccent,
          child: isTankerDataLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):_tanker(),
        ),*/
        Container(
          //color: Colors.lightBlueAccent,
          child: isActiveDataLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):renderzActiveUi(),
        ),
        Container(
          //color: Colors.lightBlueAccent,
          child: isinactiveDataLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):renderzInactiveUi(),
        ),


      ]),
    );
  }

}