import 'dart:convert';
import 'package:chewie/chewie.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:storemonitor/Screens/Constants.dart';
import 'package:storemonitor/Services/RemoteData.dart';
import 'package:video_player/video_player.dart';

class SurvellianceView extends StatefulWidget {
  final String message;
  final String id;
  final String comment;
  final String desc;
  final String store;
  final String location;
  final String time;

  const SurvellianceView(
      {Key? key,
      required this.message,
      required this.id,
      required this.comment,
      required this.desc,
      required this.store,
      required this.location,
      required this.time})
      : super(key: key);
      
  @override
  _SurvellianceViewState createState() => _SurvellianceViewState();
}

class _SurvellianceViewState extends State<SurvellianceView> {
  bool isLoading = true;
  late String videoUrl;
  var id = '';
  var comment = '';
  var store = '';
  var location = '';
  var des = '';
  var time = '';
  //late VlcPlayerController? controller;

  final TextEditingController _textFieldController3 = TextEditingController();
  final _focusNode = FocusNode();
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;

  void startLoading(bool val) {
    setState(() {
      isLoading = val;
    });
  }

  void initilize(String url) {
    _videoPlayerController = VideoPlayerController.networkUrl(
      Uri.parse(url),
    );
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      aspectRatio: 16 / 9, // Set your desired aspect ratio
      autoPlay: true,
      looping: false, // Set to true if you want the video to loop
      // Other customization options can be set here
      showControls: true, // Show video controls
      // Other customization options can be set here
      materialProgressColors: ChewieProgressColors(
        playedColor:
            const Color.fromARGB(255, 205, 96, 196), // Change played color
        handleColor:
            const Color.fromARGB(255, 244, 54, 222), // Change handle color
        bufferedColor: Colors.grey, // Change buffered color
        backgroundColor: Colors.grey[300]!, // Change background color
      ),
      cupertinoProgressColors: ChewieProgressColors(
        playedColor: const Color.fromARGB(
            255, 244, 54, 238), // Change played color on iOS
        handleColor: const Color.fromARGB(
            255, 244, 54, 216), // Change handle color on iOS
        bufferedColor: Colors.grey, // Change buffered color on iOS
        backgroundColor: Colors.grey[300]!, // Change background color on iOS
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    final data = widget.message;
    id = widget.id;
    comment = widget.comment;
    des = widget.desc;
    store = widget.store;
    location = widget.location;
    time = widget.time;
    _textFieldController3.text = comment;
    final urlParts = data.split('/');
    final indexOfD = urlParts.indexOf('d');
    final fileId = urlParts.elementAt(indexOfD + 1);
    videoUrl = 'https://drive.google.com/uc?export=download&id=$fileId';
    initilize(videoUrl);
  }

  void getUpdate1(String Id, String comment) async {
    final respon = await RemoteData().getUpdateIssueVideos1(Id, comment);
    Map<String, dynamic> responseMap = jsonDecode(respon);
    Navigator.of(context).pop();

    if (responseMap['status'] == 'Updated') {
      Constants.dialogMessage(context, 'Video Playing', responseMap['status']);
      //Navigator.of(context).pop();
    } else {
      Constants.dialogMessage(context, 'Video Playing', responseMap['status']);
    }
    if (kDebugMode) {
      print(responseMap);
    }
  }

  void hideKeyboard(BuildContext context) {
    // Use FocusScope to find the current FocusNode
    final currentFocus = FocusScope.of(context);

    // Unfocus the current FocusNode to hide the keyboard
    if (!currentFocus.hasPrimaryFocus) {
      currentFocus.unfocus();
      _focusNode.unfocus();
    }
  }

  @override
  void dispose() async {
    super.dispose();
    _textFieldController3.clear();
    _videoPlayerController.dispose();
    _chewieController.dispose();
    if (kDebugMode) {
      print('Hitting Here dispose ----------------->');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Video Playing',
          style: Constants.fontStyle,
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: const EdgeInsets.all(10.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(
                height: MediaQuery.of(context).size.height / 2.5,
                child: Chewie(
                  controller: _chewieController,
                ),
              ),
              const SizedBox(
                width: 1,
                height: 15,
              ),
              // SizedBox(
              //   width: 90,
              //   height: 40,
              //   child: ElevatedButton(
              //     onPressed: () {
              //       setState(() {
              //         _isPlaying = !_isPlaying;
              //         if (_isPlaying) {
              //           controller!.play();
              //         } else {
              //           controller!.pause();
              //         }
              //       });
              //     },
              //     style: ButtonStyle(
              //       backgroundColor: MaterialStateProperty.all<Color>(
              //           const Color.fromARGB(255, 35, 22, 66)),
              //     ),
              //     child: Text(_isPlaying ? 'Pause' : 'Play'),
              //   ),
              // ),
              // Center(
              //   child: isLoading
              //       ? const CircularProgressIndicator(
              //           color: Color.fromARGB(255, 173, 57, 230),
              //         )
              //       : const Text(''),
              // ),

              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Text('Vidnotid        :',
                      style: Constants.listHeaderfontStyle,
                      overflow: TextOverflow.ellipsis),
                  const SizedBox(
                    width: 10,
                    height: 1,
                  ),

                  Text(id,
                      style: Constants.listHeaderoppfontStyle,
                      overflow: TextOverflow.ellipsis),

                  //isvisible =false;
                ],
              ),
              const SizedBox(height: 10.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Text('Store                :',
                      style: Constants.listHeaderfontStyle,
                      overflow: TextOverflow.ellipsis),
                  const SizedBox(
                    width: 10,
                    height: 1,
                  ),

                  Text(store,
                      style: Constants.listHeaderoppfontStyle,
                      overflow: TextOverflow.ellipsis),

                  //isvisible =false;
                ],
              ),
              const SizedBox(height: 10.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Text('Location        :',
                      style: Constants.listHeaderfontStyle,
                      overflow: TextOverflow.ellipsis),
                  const SizedBox(
                    width: 10,
                    height: 1,
                  ),
                  Expanded(
                    child: Text(
                      location,
                      softWrap: true,
                      textAlign: TextAlign.left,
                      style: Constants.listHeaderoppfontStyle,
                    ),
                  ),
                  // Text(location,
                  //     textAlign: TextAlign.right,
                  //     style: Constants.listHeaderoppfontStyle,
                  //     overflow: TextOverflow.ellipsis),
                ],
              ),
              const SizedBox(height: 10.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Text('Time                 :',
                      style: Constants.listHeaderfontStyle,
                      overflow: TextOverflow.ellipsis),
                  const SizedBox(
                    width: 10,
                    height: 1,
                  ),

                  Text(time,
                      style: Constants.listHeaderoppfontStyle,
                      overflow: TextOverflow.ellipsis),

                  //isvisible =false;
                ],
              ),
              const SizedBox(height: 10.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Text('Description :',
                      style: Constants.listHeaderfontStyle,
                      overflow: TextOverflow.ellipsis),
                  const SizedBox(
                    width: 10,
                    height: 1,
                  ),
                  Expanded(
                    child: Text(
                      des,
                      softWrap: true,
                      textAlign: TextAlign.left,
                      style: Constants.listHeaderoppfontStyle,
                    ),
                  ),
                  // Text(des,
                  //     style: Constants.listHeaderoppfontStyle,
                  //     overflow: TextOverflow.ellipsis),

                  //isvisible =false;
                ],
              ),
              const SizedBox(height: 20.0),
              SizedBox(
                height: 120,
                child: TextFormField(
                  showCursor: false,
                  keyboardType: TextInputType.multiline,
                  focusNode: _focusNode,
                  maxLines: 8,
                  cursorColor: const Color.fromARGB(255, 125, 50, 253),
                  style: Constants.headerlistitems,
                  controller: _textFieldController3,
                  decoration: InputDecoration(
                    labelText: 'Comments...',
                    labelStyle: const TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                      letterSpacing: 0.5,
                    ),
                    enabledBorder: const OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.grey,
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: const BorderSide(
                        color: Color.fromARGB(255, 125, 50, 253),
                      ),
                      borderRadius: BorderRadius.circular(5.0),
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 10, width: 10),
              SizedBox(
                width: double.infinity,
                height: 50,
                child: ElevatedButton(
                  onPressed: () async {
                    if (_textFieldController3.text.isEmpty) {
                      Constants('Video Alert ', 'Enter Comments')
                          .showAlertDialog(context, false);
                    } else {
                      bool isInternetConnected =
                          await Constants.checkInternetConnectivity();
                      if (isInternetConnected) {
                        showDialog(
                            context: context,
                            builder: (context) {
                              return const Center(
                                  child: CircularProgressIndicator(
                                      color:
                                          Color.fromARGB(255, 173, 57, 230)));
                            });

                        //getUpdate(id, _textFieldController3.text);
                        getUpdate1(id, _textFieldController3.text);
                      } else {
                        Constants('Video Alert ',
                                'Please check internet connection')
                            .showAlertDialog(context, false);
                      }
                    }
                  },
                  style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all<Color>(
                          const Color.fromARGB(255, 62, 43, 75)),
                      shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                          RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      ))),
                  child: const Text(
                    'OK',
                    style: Constants.fontStyle,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
