import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
//import 'package:need_resume/need_resume.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:storemonitor/Screens/Issue.dart';
import 'package:storemonitor/Screens/SurvellianceView.dart';
import '../Services/RemoteData.dart';
import 'Constants.dart';

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

  @override
  State<IssueVideos> createState() => _IssueVideos();
}

class _IssueVideos extends State<IssueVideos> {
  String? selectedDropdownItem;
  var isMeeters = '';
  List<String>? storesList;
  Issue? issue;
  List<Data>? notificationslist = [];
  //PermissionStatus _storagePermissionStatus = PermissionStatus.denied;

  @override
  void initState() {
    super.initState();
    isMeeters = widget.message;
    requestStoragePermission();
    loadData();
  }

  Future<void> requestStoragePermission() async {
    final status = await Permission.storage.request();
    if (status.isGranted) {
      print('Granted');
      // You have the permission, you can now access storage.
    } else if (status.isDenied) {
      print('Not Granted');
      // The user denied the permission. You can explain why you need it and request again.
    } else if (status.isPermanentlyDenied) {
      // The user permanently denied the permission. You can open the app settings to let the user manually enable it.
      openAppSettings();
    }
  }

  Future<void> loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString("stores_list");
    //print(userId);
    storesList = (json.decode(userId!) as List<dynamic>)
        .map((map) => map['name'] as String)
        .toList();
    //print(storesList);
    int index = storesList!.indexWhere((item) => item.contains(isMeeters));

    setState(() {
      selectedDropdownItem = storesList![index];
      //print(selectedDropdownItem);
      getData(selectedDropdownItem!);
    });
  }

  void getData(String name) async {
    bool isInternetConnected = await Constants.checkInternetConnectivity();
    if (isInternetConnected) {
       showDialog(
          context: context,
          builder: (context) {
            return const Center(
                child: CircularProgressIndicator(
                    color: Color.fromARGB(255, 29, 20, 34)));
          });
      //Response data;
      final respon = await RemoteData().getIssueVideos(name);
      Map<String, dynamic> responseMap = jsonDecode(respon);
      if (kDebugMode) {
        print(responseMap['data']);
      }
      if (responseMap['data'] == null ||
          !(responseMap['data'] as List).isNotEmpty) {
        notificationslist = [];
        setState(() {
          notificationslist;
        });
        //Navigator.of(context).pop();
      } else {
        //print('response $responseMap');
        issue = Issue.fromJson(responseMap);
        notificationslist = issue!.data;
        if (notificationslist!.isNotEmpty) {
          //Navigator.of(context).pop();
          setState(() {
            notificationslist;
          });
        }
      }
      Navigator.of(context).pop();
    } else {}
    // } catch (e) {
    //   Constants('Review', e.).showAlertDialog(context);
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Issue Videos List',
          style: Constants.fontStyle,
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      body: Container(
        margin: const EdgeInsets.all(15.0),
        child: Column(
          //crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            // SizedBox(
            //   width: double.infinity,
            //   //height: double.infinity,
            //   child: DropdownButton(
            //     isExpanded: true,
            //     value: selectedDropdownItem,
            //     onChanged: (value) {
            //       setState(() {
            //         selectedDropdownItem = value;
            //         //getupdateData(selectedDropdownItem);
            //       });
            //     },
            //     items: storesList?.map((value) {
            //       return DropdownMenuItem(
            //         value: value,
            //         child: Text(value),
            //       );
            //     }).toList(),
            //   ),
            // ),
            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;
                      getData(selectedDropdownItem!);
                    });
                  },
                  items: storesList?.map((item) {
                    return DropdownMenuItem<String>(
                      value: item,
                      child: Text(item),
                    );
                  }).toList(),
                  icon: const Icon(Icons.arrow_drop_down),
                  isExpanded: true,
                ),
              ),
            ),

            const SizedBox(
              width: 0,
              height: 15,
            ),

            const Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text('Details',
                    textAlign: TextAlign.left,
                    style: Constants.headerfontStyle),
              ],
            ),

            Container(
              decoration: BoxDecoration(
                // border: Border.all(
                //   color: const Color.fromARGB(255, 123, 50, 254),
                //   style: BorderStyle.solid,
                //   width: 1.0,
                // ),
                color: const Color.fromARGB(255, 35, 22, 66),
                borderRadius: BorderRadius.circular(5.0),
              ),
              //color: Color.fromARGB(255, 123, 50, 254),
              height: 40,
              child: const Row(
                children: [
                  Expanded(
                    child: Text(
                      'VIDNOTID',
                      textAlign: TextAlign.center,
                      style: Constants.whitefontStyle,
                    ),
                  ),
                  SizedBox(width: 10),
                  VerticalDivider(
                    width: 1.0,
                    color: Colors.white,
                  ),
                  Expanded(
                    child: Text(
                      'Time',
                      textAlign: TextAlign.center,
                      style: Constants.whitefontStyle,
                    ),
                  ),
                  VerticalDivider(
                    width: 1.0,
                    color: Colors.white,
                  ),
                  Expanded(
                    child: Text(
                      'STATUS',
                      textAlign: TextAlign.center,
                      style: Constants.whitefontStyle,
                    ),
                  ),
                  // VerticalDivider(
                  //   width: 1.0,
                  //   color: Colors.white,
                  // ),
                  // Expanded(
                  //   child: Text(
                  //     'LINK',
                  //     textAlign: TextAlign.center,
                  //     style: Constants.whitefontStyle,
                  //   ),
                  // ),
                ],
              ),
            ),
            SizedBox(
              height: MediaQuery.of(context).size.height * 0.65,
              child: ListView.builder(
                itemCount: notificationslist?.length,
                itemBuilder: (context, index) {
                  return Padding(
                    padding: const EdgeInsets.all(2.0),
                    child: Container(
                      height: 60,
                      color: index % 2 == 0
                          ? const Color.fromARGB(255, 245, 242, 251)
                          : Colors.white,
                      child: GestureDetector(
                        onTap: () {
                          requestStoragePermission();
                          Navigator.of(context)
                              .push(
                                MaterialPageRoute(
                                    builder: (_) => SurvellianceView(
                                          message: notificationslist![index]
                                              .VIDEOURL,
                                          id: notificationslist![index]
                                              .VIDNOTID
                                              .toString(),
                                          comment: notificationslist![index]
                                              .COMMENTS,
                                          desc: notificationslist![index]
                                              .DESCRIPTION,
                                          store:
                                              notificationslist![index].STORE,
                                          location: notificationslist![index]
                                              .LOCATION,
                                          time: notificationslist![index]
                                              .TIMESTAMP,
                                        )),
                              )
                              .then((val) => (val != null)
                                  ? (val
                                      ? getData(selectedDropdownItem!)
                                      : true)
                                  : false);

                          // Navigator.of(context).push(MaterialPageRoute(
                          //     builder: (_) => MyHomePage()));
                        },
                        child: Row(
                          children: [
                            Expanded(
                              child: Text(
                                notificationslist![index]
                                    .VIDNOTID
                                    .toString()
                                    .toLowerCase(),
                                style: Constants.headerlistitems,
                                textAlign: TextAlign.center,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            const SizedBox(width: 10),
                            const VerticalDivider(
                              width: 1.0,
                              color: Colors.white,
                            ),
                            Expanded(
                              child: Text(
                                notificationslist![index].TIMESTAMP.toString(),
                                textAlign: TextAlign.center,
                                style: Constants.headerlistitems1,
                              ),
                            ),
                            const VerticalDivider(
                              width: 1.0,
                              color: Colors.white,
                            ),
                            Expanded(
                              child:
                                  notificationslist![index].STATUS.toString() ==
                                          'CLOSED'
                                      ? const Text(
                                          'VIEWED',
                                          style: Constants.close,
                                          overflow: TextOverflow.ellipsis,
                                          textAlign: TextAlign.center,
                                        )
                                      : Text(
                                          notificationslist![index]
                                              .STATUS
                                              .toString(),
                                          style: Constants.open,
                                          overflow: TextOverflow.ellipsis,
                                          textAlign: TextAlign.center,
                                        ),
                            ),
                            // VerticalDivider(
                            //   width: 1.0,
                            //   color: Colors.white,
                            // ),
                            // Expanded(
                            //   child: Text(
                            //     'LINK',
                            //     textAlign: TextAlign.center,
                            //     style: Constants.whitefontStyle,
                            //   ),

                            // ),
                          ],
                        ),
                      ),
                      // child: Row(
                      //   children: [
                      //     const SizedBox(
                      //       width: 5,
                      //       height: 2,
                      //     ),
                      //     SizedBox(
                      //       width: MediaQuery.of(context).size.width / 3.3,
                      //       // height: 40,
                      //       child: Text(
                      //         notificationslist![index]
                      //             .DESCRIPTION
                      //             .toString()
                      //             .toLowerCase(),
                      //         style: Constants.headerlistitems,
                      //         maxLines: 5,
                      //         overflow: TextOverflow.ellipsis,
                      //         textAlign: TextAlign.left,
                      //       ),
                      //     ),
                      //     const VerticalDivider(
                      //       width: 1.0,
                      //       color: Colors.white,
                      //     ),
                      //     // SizedBox(
                      //     //   width: MediaQuery.of(context).size.width / 4.6,
                      //     //   child: Text(
                      //     //     notificationslist![index].STATUS.toString(),
                      //     //     style: Constants.headerlistitems1,
                      //     //     overflow: TextOverflow.ellipsis,
                      //     //     textAlign: TextAlign.center,
                      //     //   ),
                      //     // ),
                      //     // const VerticalDivider(
                      //     //   width: 1.0,
                      //     //   color: Colors.white,
                      //     // ),
                      //     SizedBox(
                      //       width: MediaQuery.of(context).size.width / 3.4,
                      //       child:
                      //           notificationslist![index].STATUS.toString() ==
                      //                   'CLOSED'
                      //               ? const Text(
                      //                   'VIEWED',
                      //                   style: Constants.headerlistitems1,
                      //                   overflow: TextOverflow.ellipsis,
                      //                   textAlign: TextAlign.center,
                      //                 )
                      //               : Text(
                      //                   notificationslist![index]
                      //                       .STATUS
                      //                       .toString(),
                      //                   style: Constants.headerlistitems1,
                      //                   overflow: TextOverflow.ellipsis,
                      //                   textAlign: TextAlign.center,
                      //                 ),
                      //     ),
                      //     const VerticalDivider(
                      //       width: 1.0,
                      //       color: Colors.white,
                      //     ),
                      //     SizedBox(
                      //       width: MediaQuery.of(context).size.width / 3.6,
                      //       child: Align(
                      //         alignment: Alignment.center,
                      //         child: IconButton(
                      //           icon: const Icon(Icons.play_arrow,
                      //               size: 32.0), // Play arrow icon
                      //           onPressed: () {
                      //             // Add your play button action here
                      //             // For example, start playing a video or audio
                      //             // Navigator.push(
                      //             //   context,
                      //             //   MaterialPageRoute(
                      //             //     builder: (context) => SurvellianceView(
                      //             //       message: notificationslist![index]
                      //             //           .VIDEOURL,
                      //             //       id: notificationslist![index]
                      //             //           .VIDNOTID
                      //             //           .toString(),
                      //             //     ),
                      //             //   ),
                      //             // );

                      //             Navigator.of(context)
                      //                 .push(
                      //                   MaterialPageRoute(
                      //                       builder: (_) => SurvellianceView(
                      //                             message: notificationslist![
                      //                                     index]
                      //                                 .VIDEOURL,
                      //                             id: notificationslist![
                      //                                     index]
                      //                                 .VIDNOTID
                      //                                 .toString(),
                      //                           )),
                      //                 )
                      //                 .then((val) => val
                      //                     ? getData(selectedDropdownItem!)
                      //                     : null);

                      //             //.then((value) => setState(() {}));
                      //           },
                      //         ),
                      //       ),
                      //     ),
                      //   ],
                      // ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
