import 'dart:convert';
import 'package:doctor/common/qrcode_display.dart';
import 'package:doctor/common/updateprofile.dart';
import 'package:doctor/connected_patients/connected_patients.dart';
import 'package:doctor/patient_dashboard/patient_dashboard.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'dart:ui' as ui;
import 'login.dart';
import 'dart:io';
import 'package:dots_indicator/dots_indicator.dart';
import 'package:doctor/common/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;
  int currentIndex = 0;
  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/seekopinion.png",
    "images/reports.png",
    "images/prescriptions.png",
    "images/medicines.png",
    "images/invitations.png",
    "images/emergency.png"
  ];



  Widget _newDashboard() {
    return Container(
        color: primaryColor,
        child: Column(children: <Widget>[
          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,
              onPageChanged: (index, reason) {
                setState(() {
                  currentIndex = index;
                });
              },
              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(),
          ),
          DotsIndicator(
              dotsCount: imgList.length,
              position: currentIndex,
              axis: Axis.horizontal,
              decorator: DotsDecorator(
                  color: Colors.white,
                  activeColor: buttonColors
              )
              //decorator: decorator,
              ),
          Padding(
            padding: EdgeInsets.all(10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Column(
                  children: [
                    GestureDetector(
                      child: Container(
                        width: MediaQuery.of(context).size.width * .20,
                        height: MediaQuery.of(context).size.height * .15,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                            image: DecorationImage(
                                image: AssetImage(
                                    "images/myconnections.png"), // picked file
                                fit: BoxFit.fitWidth)),
                      ),
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => const ConnectedPatients()),
                        );
                      },
                    ),
                    Text(
                      'My Connections',
                      style: dashboardTextStyle(),
                    ),
                  ],
                ),
                Column(
                  children: [
                    GestureDetector(
                      child: Container(
                        width: MediaQuery.of(context).size.width * .20,
                        height: MediaQuery.of(context).size.height * .15,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                            image: DecorationImage(
                                image: AssetImage(
                                    "images/myconnections.png"), // picked file
                                fit: BoxFit.fitWidth)),
                      ),
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => const PatientDashboard()),
                        );
                      },
                    ),
                    Text(
                      'Patient Dashboard',
                      style: dashboardTextStyle(),
                    ),
                  ],
                ),
              ],
            ),
          ),
          /*Padding(
            padding: EdgeInsets.all(10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Column(
                  children: [
                    GestureDetector(
                      child: Container(
                        width: MediaQuery.of(context).size.width * .20,
                        height: MediaQuery.of(context).size.height * .15,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                            image: DecorationImage(
                                image: AssetImage(
                                    "images/prescriptions.png"), // picked file
                                fit: BoxFit.fitWidth)),
                      ),
                      onTap: () {
                      },
                    ),
                    Text(
                      'Prescriptions',
                      style: dashboardTextStyle(),
                    ),
                  ],
                ),
                Column(
                  children: [
                    GestureDetector(
                      child: Container(
                        width: MediaQuery.of(context).size.width * .20,
                        height: MediaQuery.of(context).size.height * .15,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                            image: DecorationImage(
                                image: AssetImage(
                                    "images/medicines.png"), // picked file
                                fit: BoxFit.fitWidth)),
                      ),
                      onTap: () {

                      },
                    ),
                    Text(
                      'Medicines',
                      style: dashboardTextStyle(),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.all(10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Column(
                  children: [
                    GestureDetector(
                      child: Container(
                        width: MediaQuery.of(context).size.width * .20,
                        height: MediaQuery.of(context).size.height * .15,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                            image: DecorationImage(
                                image: AssetImage(
                                    "images/myconnections.png"), // picked file
                                fit: BoxFit.fitWidth)),
                      ),
                      onTap: () {

                      },
                    ),
                    Text(
                      'My Connections',
                      style: dashboardTextStyle(),
                    ),
                  ],
                ),
                Column(
                  children: [
                    GestureDetector(
                      child: Container(
                        width: MediaQuery.of(context).size.width * .20,
                        height: MediaQuery.of(context).size.height * .15,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                            image: DecorationImage(
                                image: AssetImage(
                                    "images/emergency.png"), // picked file
                                fit: BoxFit.fitWidth)),
                      ),
                      onTap: () {
                      },
                    ),
                    Text(
                      'Emergency',
                      style: dashboardTextStyle(),
                    ),
                  ],
                ),
              ],
            ),
          )*/
        ]));
  }

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


  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.clearSharedPrefeences();
                      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(
        backgroundColor: primaryColor,
        resizeToAvoidBottomInset: false,
        appBar: AppSettings.appBar('Health Care'),
        drawer: Drawer(
          backgroundColor: primaryColor,
          child: ListView(
            padding: EdgeInsets.zero,
            children: [
              DrawerHeader(
                  decoration: const BoxDecoration(
                    color: secondaryColor,
                  ),
                  child: Row(

                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                GestureDetector(
                                  child: Container(
                                    width: MediaQuery.of(context).size.width * .20,
                                    height:
                                    MediaQuery.of(context).size.height * .15,
                                    decoration: BoxDecoration(
                                        shape: BoxShape.circle,
                                        image: DecorationImage(
                                            image: (AppSettings.profilePictureUrl !=
                                                '' &&
                                                AppSettings.profilePictureUrl !=
                                                    'null')
                                                ? NetworkImage(AppSettings
                                                .profilePictureUrl)
                                            as ImageProvider
                                                : AssetImage(
                                                "images/profile_pic.png"), // picked file
                                            fit: BoxFit.fitWidth)),
                                  ),
                                  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);
                                                    },
                                                  ),
                                                ],
                                              ),
                                            ),
                                          );
                                        });
                                  },
                                ),
                                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))),
                                    ),
                                  ),

                                )
                              ],
                            ),
                          ),
                          Text(
                            AppSettings.doctorName,
                            style: drawerHeaderTextStyleNew(),
                          ),
                          Text(
                            AppSettings.phoneNumber,
                            style: drawerHeaderTextStyleNew(),
                          ),
                          Visibility(
                            visible: AppSettings.email != '',
                            child: Text(
                              AppSettings.email,
                              style: drawerHeaderTextStyleNew(),
                            ),
                          ),
                          Row(
                            children: [
                              Visibility(
                                visible: AppSettings.age != '',
                                child: Text(
                                  AppSettings.age + '  Yrs, ',
                                  style: drawerHeaderTextStyleNew(),
                                ),
                              ),
                              Visibility(
                                visible: AppSettings.gender != '',
                                child: Text(
                                  AppSettings.gender,
                                  style: drawerHeaderTextStyleNew(),
                                ),
                              ),
                            ],
                          )
                        ],
                      ),


                    ],
                  )),
              ListTile(
                title: Row(
                  children: [
                    Image(
                        image: const AssetImage('images/editprofile.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Edit Profile', style: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const UpdateProfile()),
                  );
                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    Image(
                        image: const AssetImage('images/editprofile.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Video Call', style: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => const UpdateProfile()),
                  );
                },
              ),
              /*Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    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: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {

                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    Image(
                        image: const AssetImage('images/reportmyself.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('How are you feeling today?',
                        style: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {

                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    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: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {

                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    Image(
                        image: const AssetImage('images/invitations.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Invitations', style: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {

                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    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: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {

                },
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    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: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {},
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    Image(
                        image:
                            const AssetImage('images/updatemobilenumber.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Update Mobile Number',
                        style: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {},
              ),
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    Image(
                        image: const AssetImage('images/updatemylocation.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Update My Location',
                        style: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {

                },
              ),
             */
              Divider(
                color: Colors.grey,
              ),
              ListTile(
                title: Row(
                  children: [
                    Image(
                        image: const AssetImage('images/logout.png'),
                        height: 25,
                        width: 25,
                        fit: BoxFit.fill),
                    const SizedBox(
                      width: 10,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text('Logout', style: drawerListItemsTextStyle()),
                  ],
                ),
                onTap: () {
                  showLogoutAlertDialog(context);
                },
              ),
            ],
          ),
        ),
        body: _newDashboard(),
      ),
    );
  }
}
