import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sms/flutter_sms.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart'
    show SharedPreferences;
import 'package:storemonitor/Screens/Chatboat.dart';
import 'package:storemonitor/Screens/Constants.dart';
import 'package:storemonitor/Screens/LoginPage.dart';
import 'package:storemonitor/Services/RemoteData.dart';
import 'package:url_launcher/url_launcher.dart';

class NavBar extends StatefulWidget {
  final String message;
  final String storeNames;
  NavBar({super.key, required this.message, required this.storeNames});

  @override
  _NavBarState createState() => _NavBarState();
}

class _NavBarState extends State<NavBar> {
  String? name;
  String? access;
  var isMeeters = '';
  List<String> names = [];
  Future<void> _getSharedPreferencesValues() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    setState(() {
      name = sharedPreferences.getString('userId');
      access = sharedPreferences.getString('access');
    });
  }

  @override
  void initState() {
    super.initState();
    _getSharedPreferencesValues();
    isMeeters = widget.message;
    names = widget.storeNames
        .substring(1, widget.storeNames.length - 1) // Remove square brackets
        .split(", ") // Split by comma and space
        .map((store) => store.replaceAll(
            RegExp(r'[^\w\s]+'), '')) // Remove non-alphanumeric characters
        .toList();
    if (kDebugMode) {
      print(isMeeters);
    }
    if (kDebugMode) {
      print(names);
    }
  }

  // void makePhoneCall(String phoneNumber) async {
  //   //FlutterPhoneDirectCaller.callNumber(phoneNumber);
  //   //launchUrl("tel:+99364921507");
  //   // final Uri phoneUri = Uri(scheme: "tel", path: phoneNumber);
  //   // try {
  //   //   if (await canLaunchUrl(phoneUri)) await canLaunchUrl(phoneUri);
  //   // } catch (error) {
  //   //   throw ("Cannot dial");
  //   // }
  //   final url = Uri.parse('tel:$phoneNumber');
  //   if (await canLaunchUrl(url)) {
  //     await launchUrl(url);
  //   } else {
  //     throw 'Could not launch $url';
  //   }
  // }

  void makePhoneCall(String phoneNumber) async {
    final Uri launchUri = Uri(
      scheme: 'tel',
      path: phoneNumber,
    );
    if (!mounted) return; // Check if the widget is still mounted
    await launchUrl(launchUri);
  }

  void requestPhoneCallPermission() async {
    if (!mounted) return; // Check if the widget is still mounted
    PermissionStatus status = await Permission.phone.request();
    if (kDebugMode) {
      print('Status $status');
    }
    if (!mounted) return;
    if (status.isGranted) {
      makePhoneCall('8121007327');
    } else {
      // Permission is denied or permanently denied, show an explanation to the user
      if (status.isPermanentlyDenied) {
        // Show a dialog explaining why the permission is required and how to enable it
        openAppSettings();
      } else {
        // Permission is denied but not permanently, show a rationale to the user
        if (!mounted) return; // Check if the widget is still mounted
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('Phone call permission is required to make calls.'),
            action: SnackBarAction(
              label: 'Grant',
              onPressed: () {
                requestPhoneCallPermission();
              },
            ),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    //_getSharedPreferencesValues();
    return Drawer(
      child: Column(
        children: [
          Container(
            width: 400,
            height: 120,
            margin: const EdgeInsets.only(top: 0.0),
            color: const Color.fromARGB(
                255, 123, 50, 254), // Set the background color
            child: const Text(
              '\n\n\t\t\t\tMENU', // Text content
              style: TextStyle(
                  color: Colors.white, // Set the text color
                  fontSize: 22.0,
                  fontWeight: FontWeight.w400),
              textAlign: TextAlign.left,
            ),
          ),
          Expanded(
            child: ListView(
              children: [
                ExpansionTile(
                  title: Row(
                    children: [
                      Image.asset(
                        'assets/images/my_profile.png',
                        width: 32,
                        height: 32,
                      ),
                      const SizedBox(
                        width: 30,
                        height: 1,
                      ),
                      const Text(
                        'My Profile',
                        style: Constants.headerlistitems,
                      ),
                    ],
                  ),
                  children: [
                    ListTile(
                      title: Text('Name   : $name',
                          style: Constants.headerlistitems),
                      //onTap: () => null,
                    ),
                    const Divider(
                      height: 1,
                    ),
                    ListTile(
                      //leading: const Icon(Icons.support_agent),
                      title: Text('Access Level : $access',
                          style: Constants.headerlistitems),
                      //onTap: () => null,
                    ),
                    const Divider(
                      height: 1,
                    ),
                  ],
                ),
                ListTile(
                    leading: Image.asset(
                      'assets/images/chat.png',
                      width: 32,
                      height: 32,
                    ),
                    title: const Text(
                      'Bob',
                      style: Constants.headerlistitems,
                    ),
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const SpeechSampleApp1(),
                        ),
                      );
                    }),
                const Divider(
                  height: 1,
                ),
                ListTile(
                  leading: Image.asset(
                    'assets/images/command_center.png',
                    width: 32,
                    height: 32,
                  ),
                  title: const Text(
                    'Command Center',
                    style: Constants.headerlistitems,
                  ),
                  onTap: () => requestPhoneCallPermission(),
                ),
                const Divider(
                  height: 1,
                ),
                ListTile(
                  leading: Image.asset(
                    'assets/images/support.png',
                    width: 32,
                    height: 32,
                  ),
                  title: const Text(
                    'Raise a ticket',
                    style: Constants.headerlistitems,
                  ),
                  onTap: () => showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return CustomDialog1(
                          message: isMeeters, names: names.toString());
                    },
                  ),
                ),
                const Divider(
                  height: 1,
                ),
                ListTile(
                  leading: Image.asset(
                    'assets/images/change_password.png',
                    width: 32,
                    height: 32,
                  ),
                  title: const Text(
                    'Change Password',
                    style: Constants.headerlistitems,
                  ),
                  onTap: () {
                    // Navigator.push(
                    //   context,
                    //   MaterialPageRoute(builder: (context) => const VideoApp()),
                    // );
                    showDialog(
                        context: context,
                        builder: (BuildContext context) {
                          return const CustomDialog();
                        });
                  },
                ),
                const Divider(
                  height: 1,
                ),
                ListTile(
                  leading: Image.asset(
                    'assets/images/logout.png',
                    width: 32,
                    height: 32,
                  ),
                  title: const Text(
                    'Logout',
                    style: Constants.headerlistitems,
                  ),
                  onTap: () async {
                    bool valid = await Constants.checkInternetConnectivity();
                    if (valid) {
                      Constants.saveLoginCredentials('', '', '', '', '', false);
                      Navigator.of(context).pushAndRemoveUntil(
                          MaterialPageRoute(
                              builder: (context) => const LoginPage()),
                          (Route<dynamic> route) => false);
                    } else {
                      Constants(
                              'Store Monitor', 'Check your internet connection')
                          .showAlertDialog(context, false);
                    }
                  },
                ),
                const Divider(
                  height: 1,
                ),
              ],
            ),
          ),
          const Divider(
            height: 1,
            thickness: 1,
            color: Color.fromARGB(255, 122, 96, 153),
          ),
          const Text(''),
          Text.rich(
            TextSpan(
              text: 'Designed & Developed by ',
              style:
                  TextStyle(fontSize: 15, color: Colors.black.withOpacity(0.6)),
              children: const [
                TextSpan(
                  text: 'SOPT\n\n',
                  style: TextStyle(
                    fontSize: 15,
                    color: Colors.amber,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}

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

  @override
  _CustomDialogState createState() => _CustomDialogState();
}

class _CustomDialogState extends State<CustomDialog> {
  final TextEditingController _textFieldController1 = TextEditingController();
  final TextEditingController _textFieldController2 = TextEditingController();
  final TextEditingController _textFieldController3 = TextEditingController();
  String? userId = '';
  GlobalKey<State<StatefulWidget>> alertDialogKey = GlobalKey();

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

  @override
  void dispose() {
    _textFieldController1.dispose();
    _textFieldController2.dispose();
    _textFieldController3.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10), // Adjust the radius as needed
      ),
      key: alertDialogKey,
      title: const Text(
        'Change Password',
        style: Constants.HeaderStyle,
        textAlign: TextAlign.center,
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            height: 50,
            child: TextFormField(
              cursorColor: const Color.fromARGB(255, 125, 50, 253),
              style: Constants.fontStyle,
              controller: _textFieldController1,
              obscureText: true,
              decoration: InputDecoration(
                labelText: 'Current Password',
                labelStyle: const TextStyle(
                  //fontWeight: FontWeight.bold,
                  fontSize: 14,
                  color: Colors.grey,
                  letterSpacing: 0.5,
                ),
                enabledBorder: const OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.grey, // Set the desired color here
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(
                    color: Color.fromARGB(
                        255, 125, 50, 253), // Set the desired color here
                  ),
                  borderRadius: BorderRadius.circular(5.0),
                ),
              ),
            ),
          ),
          const SizedBox(height: 10, width: 10),
          SizedBox(
            height: 50,
            child: TextFormField(
              cursorColor: const Color.fromARGB(255, 125, 50, 253),
              style: Constants.fontStyle,
              controller: _textFieldController2,
              obscureText: true,
              decoration: InputDecoration(
                labelText: 'New Password',
                labelStyle: const TextStyle(
                  //fontWeight: FontWeight.bold,
                  fontSize: 14,
                  color: Colors.grey,
                  letterSpacing: 0.5,
                ),
                enabledBorder: const OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.grey, // Set the desired color here
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(
                    color: Color.fromARGB(
                        255, 125, 50, 253), // Set the desired color here
                  ),
                  borderRadius: BorderRadius.circular(5.0),
                ),
              ),
            ),
          ),
          const SizedBox(height: 10, width: 10),
          SizedBox(
            height: 50,
            child: TextFormField(
              cursorColor: const Color.fromARGB(255, 125, 50, 253),
              style: Constants.fontStyle,
              controller: _textFieldController3,
              obscureText: true,
              decoration: InputDecoration(
                labelText: 'Confirm Password',
                labelStyle: const TextStyle(
                  //fontWeight: FontWeight.bold,
                  fontSize: 14,
                  color: Colors.grey,
                  letterSpacing: 0.5,
                ),
                enabledBorder: const OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.grey, // Set the desired color here
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(
                    color: Color.fromARGB(
                        255, 125, 50, 253), // Set the desired color here
                  ),
                  borderRadius: BorderRadius.circular(5.0),
                ),
              ),
            ),
          ),
          const SizedBox(height: 10, width: 10),
          SizedBox(
            width: double.infinity,
            height: 50,
            child: ElevatedButton(
              onPressed: () async {
                if (_textFieldController1.text.isEmpty &&
                    _textFieldController2.text.isEmpty &&
                    _textFieldController3.text.isEmpty) {
                  Constants('Change Password ', 'Enter All Details')
                      .showAlertDialog(context, false);
                } else if (_textFieldController2.text.isEmpty &&
                    _textFieldController3.text.isEmpty) {
                  Constants('Change Password', 'Enter Change Password Details')
                      .showAlertDialog(context, false);
                } else if (_textFieldController1.text.isEmpty) {
                  Constants('Change Password ', 'Enter Current Password')
                      .showAlertDialog(context, false);
                } else if (_textFieldController2.text.isEmpty) {
                  Constants('Change Password ', 'Enter New Password')
                      .showAlertDialog(context, false);
                } else if (_textFieldController3.text.isEmpty) {
                  Constants('Change Password ', 'Enter Confirm Password')
                      .showAlertDialog(context, false);
                } else {
                  if (_textFieldController2.text ==
                      _textFieldController3.text) {
                    bool isInternetConnected =
                        await Constants.checkInternetConnectivity();
                    if (isInternetConnected) {
                      showDialog(
                          context: context,
                          builder: (context) {
                            return const Center(
                                child: CircularProgressIndicator(
                              color: Color.fromARGB(255, 173, 57, 230),
                            ));
                          });
                      print(userId);
                      print(_textFieldController1.text);
                      print(_textFieldController2.text);
                      //tor.Navigapop(context);

                      String res = await RemoteData().getChangePassword(
                          _textFieldController1.text,
                          _textFieldController2.text,
                          userId!);
                      //print(res);

                      Map<String, dynamic> responseMap = jsonDecode(res);
                      String status = responseMap['status'];
                      Navigator.pop(context);
                      if (status == 'Enter valid password') {
                        Constants('Change Password', status)
                            .showAlertDialog(context, false);
                      } else {
                        Constants('Change Password', status)
                            .showAlertDialog(context, true);
                      }

                      //login(_email.text, _pass.text);
                      //Navigator.pop(context);
                      // Navigator.pop(context);
                    } else {
                      Constants.dialogMessage(context, 'Change Password',
                          'Check your internetconnection');
                    }
                  } else {
                    Constants.dialogMessage(context, 'Change Password',
                        'Must be Same New and Confirm Password');
                  }
                }
              },
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all<Color>(
                      const Color.fromARGB(255, 62, 43, 75)),
                  shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                      RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5.0),
                    //side: BorderSide(color: Colors.red)
                  ))),
              child: const Text(
                'UPDATE',
                style: Constants.fontStyle,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> getData() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    userId = sharedPreferences.getString('empId')!;
  }
}

class CustomDialog1 extends StatefulWidget {
  final String message;
  final String names;

  const CustomDialog1({Key? key, required this.message, required this.names})
      : super(key: key);

  @override
  _customdialog1state createState() => _customdialog1state();

  String get getMessage => message;
  //List<String> get getList => names;
}

class _customdialog1state extends State<CustomDialog1> {
  final TextEditingController _textFieldController1 = TextEditingController();
  final TextEditingController _textFieldController2 = TextEditingController();
  final TextEditingController _textFieldController3 = TextEditingController();
  String? selectedDropdownItem;
  late String message;

  List<String>? storesList;

  @override
  void dispose() {
    _textFieldController1.dispose();
    _textFieldController2.dispose();
    _textFieldController3.dispose();
    super.dispose();
  }

  Future<void> loadData() async {
    setState(() {
      selectedDropdownItem = storesList![0];
      //print(selectedDropdownItem);
      //getData(selectedDropdownItem!);
    });
  }

  @override
  void initState() {
    super.initState();
    message = widget.message;
    storesList = widget.names
        .substring(1, widget.names.length - 1) // Remove square brackets
        .split(", ") // Split by comma and space
        .map((store) => store.replaceAll(
            RegExp(r'[^\w\s]+'), '')) // Remove non-alphanumeric characters
        .toList();

    loadData(); // Call the loadData() function here
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10), // Adjust the radius as needed
      ),
      title: const Text(
        'Raise A Ticket',
        style: Constants.HeaderStyle,
        textAlign: TextAlign.center,
      ),
      //insetPadding: EdgeInsets.zero,
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey),
              borderRadius: BorderRadius.circular(5.0),
            ),
            child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
                menuMaxHeight: Constants.getDropdownItemHeight(context),
                value: selectedDropdownItem,
                onChanged: (newValue) {
                  setState(() {
                    selectedDropdownItem = newValue;
                  });
                },
                items: storesList?.map((item) {
                  return DropdownMenuItem<String>(
                    value: item,
                    child: Text(item),
                  );
                }).toList(),
                icon: const Icon(Icons.arrow_drop_down),
                isExpanded: true,
              ),
            ),
          ),
          const SizedBox(
            height: 10,
            width: 1,
          ),
          SizedBox(
            height: 50,
            child: TextFormField(
              keyboardType: TextInputType.name,
              cursorColor: const Color.fromARGB(255, 125, 50, 253),
              style: Constants.headerlistitems,
              controller: _textFieldController2,
              //obscureText: true,
              decoration: InputDecoration(
                labelText: 'Your Name',
                labelStyle: const TextStyle(
                  //fontWeight: FontWeight.bold,
                  fontSize: 14,
                  color: Colors.grey,
                  letterSpacing: 0.5,
                ),
                enabledBorder: const OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.grey, // Set the desired color here
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(
                    color: Color.fromARGB(
                        255, 125, 50, 253), // Set the desired color here
                  ),
                  borderRadius: BorderRadius.circular(5.0),
                ),
              ),
            ),
          ),
          const SizedBox(height: 10, width: 10),
          SizedBox(
            height: 120,
            child: TextFormField(
              keyboardType: TextInputType.multiline,
              maxLines: 4,
              cursorColor: const Color.fromARGB(255, 125, 50, 253),
              style: Constants.headerlistitems,
              controller: _textFieldController3,
              decoration: InputDecoration(
                labelText: 'Comments...',
                //filled: true,
                labelStyle: const TextStyle(
                  //fontWeight: FontWeight.bold,
                  fontSize: 14,
                  color: Colors.grey,
                  letterSpacing: 0.5,
                ),
                enabledBorder: const OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.grey, // Set the desired color here
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(
                    color: Color.fromARGB(
                        255, 125, 50, 253), // Set the desired color here
                  ),
                  borderRadius: BorderRadius.circular(5.0),
                ),
              ),
            ),
          ),
          const SizedBox(height: 10, width: 10),
          SizedBox(
            width: double.infinity,
            height: 50,
            child: ElevatedButton(
              onPressed: () async {
                //sendSMS('KLM AMEERPET', ' Issue with Unkown Photos');
                if (_textFieldController2.text.isEmpty &&
                    _textFieldController3.text.isEmpty) {
                  Constants('Support ', 'Enter All Details')
                      .showAlertDialog(context, false);
                } else if (_textFieldController2.text.isEmpty) {
                  Constants('Support ', 'Enter Phone Number')
                      .showAlertDialog(context, false);
                } else if (_textFieldController3.text.isEmpty) {
                  Constants('Support ', 'Enter Comments')
                      .showAlertDialog(context, false);
                } else {
                  String name = _textFieldController2.text;
                  String desc = _textFieldController3.text;
                  String message =
                      "StoreName:$selectedDropdownItem\nName:$name\nDescription:$desc ";
                  List<String> recipents = ["8121007326", "8121007327"];
                  //_sendSMS(message, recipents);
                  requestSmsPermission(message, recipents);
                  Navigator.pop(context);
                }
              },
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all<Color>(
                      const Color.fromARGB(255, 62, 43, 75)),
                  shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                      RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5.0),
                    //side: BorderSide(color: Colors.red)
                  ))),
              child: const Text(
                'Raise',
                style: Constants.fontStyle,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // void sendSMS(String storeName, String description) {
  //   SmsSender sender = SmsSender();

  //   String message = "Store Name: $storeName\nDescription: $description";
  //   String recipient =
  //       "9502344033"; // Replace with the recipient's phone number

  //   SmsMessage smsMessage = SmsMessage(recipient, message);

  //   sender.sendSms(smsMessage);
  // }

  void requestSmsPermission(String message, List<String> reciepts) async {
    if (await Permission.sms.request().isGranted) {
      _sendSMS(message, reciepts);
    } else {
      // Permission is denied or permanently denied, show an explanation to the user
      if (await Permission.sms.isPermanentlyDenied) {
        // Show a dialog explaining why the permission is required and how to enable it
        openAppSettings();
      } else {
        // Permission is denied b
        //ut not permanently, show a rationale to the user

        // var status = await Permission.sms.request();
        // if (status.isGranted) {
        //   requestSmsPermission(message, reciepts);
        // } else {
        //   // Permission denied
        //   print('SMS permission denied.');
        // }
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('SMS permission is required to send messages.'),
            action: SnackBarAction(
              label: 'Grant',
              onPressed: () {
                // Request permission again
                requestSmsPermission(message, reciepts);
              },
            ),
          ),
        );
      }
    }
  }

  void _sendSMS(String message, List<String> recipents) async {
    // sender.sendSms(message);
    String result = await sendSMS(message: message, recipients: recipents)
        .catchError((onError) {
      if (kDebugMode) {
        print(onError);
      }
      return '';
    });
    if (kDebugMode) {
      print(result);
    }
  }
}
