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

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:healthcare_pharmacy/adddeliveryboy.dart';
import 'package:healthcare_pharmacy/companyoffrers.dart';
import 'package:healthcare_pharmacy/getallpharmacies.dart';
import 'package:healthcare_pharmacy/getdeliveryboydata.dart';
import 'package:healthcare_pharmacy/getmedicines.dart';
import 'package:healthcare_pharmacy/inactiveoffersview.dart';
import 'package:healthcare_pharmacy/invitations.dart';
import 'package:healthcare_pharmacy/medicinecart.dart';
import 'package:healthcare_pharmacy/createoffers.dart';
import 'package:healthcare_pharmacy/offerstabdata.dart';
import 'package:healthcare_pharmacy/offersview.dart';
import 'package:healthcare_pharmacy/biddingrequests.dart';
import 'package:healthcare_pharmacy/pharmacyaccounts.dart';
import 'package:healthcare_pharmacy/qrcode_display.dart';
import 'package:healthcare_pharmacy/updateprofile.dart';
import 'package:image_picker/image_picker.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'dart:ui' as ui;
import 'approvedoffers.dart';
import 'login.dart';
import 'seekopinion.dart';
import 'settings.dart';

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

  @override
  State<Dashboard> createState() => _DashboardState();
}

class _DashboardState extends State<Dashboard> {
  int _selectedIndex = 0;
  final List<String> imgList = [
    'images/mobilebg.png',
    'images/mobilebg2.png',
    'images/mobilebg3.png'
  ];

  final ImagePicker _picker = ImagePicker();
  bool isTablet = false;
  bool isPhone = true;

  final double devicePixelRatio = ui.window.devicePixelRatio;
  static final ui.Size size1 = ui.window.physicalSize;
  final double width = size1.width;
  final double height = size1.height;

  devicedetection() {
    if (devicePixelRatio < 2 && (width >= 1000 || height >= 1000)) {
      isTablet = true;
      isPhone = false;
    } else if (devicePixelRatio == 2 && (width >= 1920 || height >= 1920)) {
      isTablet = true;
      isPhone = false;
    } else {
      isTablet = false;
      isPhone = true;
    }
  }

  List<String> images = [
    "images/createoffer.png",
    "images/activeoffer.png",
   // "images/inactiveoffer.png",

    /*  "images/reports.png",
    "images/prescriptions.png",
    "images/medicines.png",
    "images/invitations.png",
    "images/emergency.png"*/
  ];

  gridOntap(int ind){

    if(ind==0){
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => const offers()),
      );
    }
    else if(ind==1){
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => const OffersData()),
      );
    }
   /* else if(ind==2){
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => const InActiveOffersView()),
      );
    }*/
/*
    else if(ind==3){
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => const Medicines()),
      );
    }
    else if(ind==4){
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => const Invitations()),
      );
    }
    else if(ind==5){
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => const Emergency()),
      );
    }*/

  }

  Widget _dashBoard() {
    return Container(
        color: Color(0xffA78966),
      child: Column(
        children: <Widget>[

          Container(
              height: MediaQuery.of(context).size.height * .250,
              width: double.infinity,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(0),
              ),
              //color: Colors.red,
              child: FittedBox(
                child:Image(
                  image: const AssetImage('images/mobilebg2.png'),

                ),
                fit: BoxFit.fill,
              )
          ),
          /*CarouselSlider(
            options: CarouselOptions(
              height: MediaQuery.of(context).size.height * .250,
              aspectRatio: 16 / 9,
              viewportFraction: 0.8,
              initialPage: 0,
              enableInfiniteScroll: true,
              reverse: false,
              autoPlay: true,
              autoPlayInterval: Duration(seconds: 3),
              autoPlayAnimationDuration: Duration(milliseconds: 800),
              autoPlayCurve: Curves.ease,
              enlargeCenterPage: true,
              enlargeFactor: 0.2,
              scrollDirection: Axis.horizontal,
            ),
            items: imgList.map((i) {
              return Builder(
                builder: (BuildContext context) {
                  return Container(
                      height: MediaQuery.of(context).size.height * .250,
                      width: double.infinity,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(0),
                      ),
                      //color: Colors.red,
                      child: FittedBox(
                        child: Image(
                          image: AssetImage(i),
                        ),
                        fit: BoxFit.fill,
                      ));
                },
              );
            }).toList(),
          ),*/
          SizedBox(height: 5),
          Expanded(child: Container(
              padding: EdgeInsets.all(12.0),
              child: GridView.builder(
                itemCount: images.length,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 4.0,
                  mainAxisSpacing: 4.0,),
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: (){
                      gridOntap(index);
                    },
                    child:  Image.asset(images[index]),
                  );
                },
              )),)
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    devicedetection();
  }

  Future<void> uploadProfileApi(image) async {
    var payload = new Map<String, dynamic>();
    payload["formData"] = image.toString();
    var response1 = await AppSettings.updateProfilePicture(payload);

    print(response1);
  }

  Future pickImageFromGallery() 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.uploadImageHTTPNew(image);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        AppSettings.profilePictureUrl = jsonDecode(res)['picture'];
      });
      AppSettings.saveData('profile', jsonDecode(res)['picture'], 'STRING');
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  Future takeImageFromCamera() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.camera);
      if (image == null) return;
      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.uploadImageHTTPNew(image);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        AppSettings.profilePictureUrl = jsonDecode(res)['picture'];
      });
      AppSettings.saveData('profile', jsonDecode(res)['picture'], 'STRING');
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  showLogoutAlertDialog(context) {
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
                return AlertDialog(
                    title: const Text('Do you really want to logout?'),
                    actions: <Widget>[
                      TextButton(
                        child: Text('No', style: textButtonStyle()),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                      ),
                      TextButton(
                        child: Text('Yes', style: textButtonStyle()),
                        onPressed: () async {
                          await AppSettings.clearSharedPreferences();
                          await Navigator.pushAndRemoveUntil(
                            context,
                            MaterialPageRoute(builder: (context) => Login()),
                                (Route<dynamic> route) => false,
                          );
                        },
                      ),
                    ]);
              });
        });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        final shouldPop = await showDialog<bool>(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: const Text('Do you want to exit app?',
                  style: TextStyle(
                    color: primaryColor,
                    fontSize: 20,
                  )),
              actionsAlignment: MainAxisAlignment.spaceBetween,
              actions: [
                TextButton(
                  onPressed: () {
                    SystemNavigator.pop();
                  },
                  child: const Text('Yes',
                      style: TextStyle(
                        color: primaryColor,
                        fontSize: 20,
                      )),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop(false);
                  },
                  child: const Text('No',
                      style: TextStyle(
                        color: primaryColor,
                        fontSize: 20,
                      )),
                ),
              ],
            );
          },
        );
        return shouldPop!;
      },
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppSettings.appBar('Health Care'),
        drawer: Drawer(
          backgroundColor: secondaryColor,

          child: ListView(
            padding: EdgeInsets.zero,
            children: [
              DrawerHeader(
                decoration: const BoxDecoration(
                  color: primaryColor,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        GestureDetector(
                          child: Container(
                            width: MediaQuery.of(context).size.width * .23,
                            height:
                            MediaQuery.of(context).size.height * .15,
                            decoration: BoxDecoration(

                              shape: BoxShape.rectangle,
                              image: DecorationImage(
                                  image: (AppSettings.profilePictureUrl !=
                                      '' &&
                                      AppSettings.profilePictureUrl !=
                                          'null')
                                      ? NetworkImage(AppSettings
                                      .profilePictureUrl)
                                  as ImageProvider
                                      : AssetImage(
                                      "images/profile_pic.png"),

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

                        Container(

                          child: AppSettings.qrCode==''?TextButton(
                            child:  Text(
                              'GetQR',
                              style: TextStyle(
                                fontSize: 15,
                                color: Colors.white,
                                decoration: TextDecoration.underline,
                              ),
                            ),
                            onPressed: () async{
                              AppSettings.preLoaderDialog(context);

                              try{
                                var value = await AppSettings.generateQRCode();
                                var valueResponse = jsonDecode(value);
                                String dataUri = jsonDecode(value)['qrCodeData'];

                                List<String> parts = dataUri.split(",");
                                String? base64String = parts.length == 2 ? parts[1] : null;

                                if (base64String != null) {

                                  print(base64String);
                                  AppSettings.qrCode=base64String;
                                } else {
                                  print("Invalid data URI");
                                }
                                Navigator.of(context, rootNavigator: true).pop();
                              }
                              catch(e){
                                Navigator.of(context, rootNavigator: true).pop();
                              }



                            },
                          ):GestureDetector(
                            onTap: (){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => const DisplayQrCode()),
                              );
                            },
                            child: Container(
                              height:MediaQuery.of(context).size.height * .20,
                              width:MediaQuery.of(context).size.width * .1,
                              child: Image.memory(Uint8List.fromList(base64.decode(AppSettings.qrCode))),
                            ),
                          ),
                        )
                      ],
                    ),),
                    SizedBox(
                      height: 5,
                    ),
                    Text(
                      AppSettings.pharmacyName,
                      style: TextStyle(color: Colors.white, fontSize: 15),

                    ),
                    Text(
                      AppSettings.phoneNumber,
                      style: TextStyle(color: Colors.white, fontSize: 15),

                    ),
                    Visibility(
                      visible: AppSettings.email != '',
                      child: Text(
                        AppSettings.email,
                        style: TextStyle(color: Colors.white, fontSize: 15),

                      ),
                    ),
                  ],
                ),),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/editprofile.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Edit Profile', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const UpdateProfile()),
                  );
                },
              ),
              Divider(
                color: Colors.grey,
              ),
           /*   ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/myhealth.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('My Health', style: TextStyle(color: primaryColor)),
                  ],
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const MyHealth()),
                  );
                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/reportmyself.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Report Myself', style: TextStyle(color: primaryColor)),
                  ],
                ),
                onTap: () {},
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/myconnections.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('My Connections', style: TextStyle(color: primaryColor)),
                  ],
                ),
                onTap: () {},
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/mymedicinetimings.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('My Medicine Timings', style: TextStyle(color: primaryColor)),
                  ],
                ),
                onTap: () {},
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/updatepin.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Update Pin', style: TextStyle(color: primaryColor)),
                  ],
                ),
                onTap: () {},
              ),
              Divider(
                color: Colors.grey,
              ),*/
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/createofferic.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Create Offers', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const offers()),
                  );
                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/active.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('OffersData', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const OffersData()),
                  );
                },
              ),

              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/inactive.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Approved Offers', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () {

                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => ApprovedOffersData()),
                  );
                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/inactive.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Add Delivery Boys', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () {

                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => Deliverboy()),
                  );
                },
              ),

              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/inactive.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Deliveryboys View', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () {

                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => GetDeliveryboyData()),
                  );
                },
              ),
              /*Divider(
                color: Colors.grey,
              ),

              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/inactive.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Accounts', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () {

                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => PharmacyAccounts()),
                  );
                },
              ),*/
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/inactive.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('BiddingRequests', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () {

                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => BiddingRequests()),
                  );
                },
              ),

              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/inactive.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('SendInvite', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => Invitations()),
                  );
                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: const [
                    Image(
                        image: const AssetImage('images/logout.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Logout', style: TextStyle(color: Colors.black)),
                  ],
                ),
                onTap: () async {
                  showLogoutAlertDialog(context);
                },
              ),

            ],
          ),
        ),
        body: _dashBoard(),
      ),
    );
  }
}
