import 'dart:convert';
import 'dart:io';
import 'package:chewie/chewie.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:share_plus/share_plus.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 = '';

  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
      showControls: true, // Show video controls
      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();
    hideKeyboard(context);
    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 ----------------->');
    }
  }

  Future<void> shareImageWithText(String textToShare, String desc) async {
    // List<String> paths = [
    //  textToShare
    // ]; // If you're sharing text, you might not need this list
    final box = context.findRenderObject() as RenderBox?;
    if (Platform.isAndroid) {
      if (kDebugMode) {
        print('Android Share      +++++++++++++++++++$desc');
      }
      //await Share.shareFiles(
      //   paths,
      //   text: '$textToShare\n\n$desc', // Combine text and description
      //   subject: 'Your Subject Here',
      //   sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
      //);
      await Share.share(
        '$textToShare \n\n$desc',
        subject: desc,
        sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
      );
    } else if (Platform.isIOS) {
      if (kDebugMode) {
        print('iOS Share      +++++++++++++++++++$textToShare');
      }
      await Share.share(
        '$textToShare \n\n$desc',
        // subject: 'Reason',
        sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Image.asset(
            "assets/images/back_arrow.png",
            width: 24,
            height: 24,
            color: Colors.white,
          ),
          //color: Colors.white,
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          'Video Playing',
          style: Constants.fontStyle,
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
        actions: [
          IconButton(
            icon: const Icon(
              Icons.share,
              color: Colors.white,
            ),
            onPressed: () async {
              bool valid = await Constants.checkInternetConnectivity();
              if (valid) {
                shareImageWithText(
                  videoUrl,
                  ' Vidnotid: ${id}\nStore:${store}\nLocation:${location}\nDescription:${des}',
                );
              } else {
                Constants('Upload Images', 'Check your internet connection');
              }
            },
          ),
        ],
      ),
      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,
              ),
              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),
                ],
              ),
              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),
                ],
              ),
              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,
                    ),
                  ),
                ],
              ),
              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,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
