import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tflite_flutter/tflite_flutter.dart';
import 'package:vasthram/CameraScreen.dart';
import 'package:vasthram/Constants.dart';
import 'package:vasthram/CustomAlertDialog.dart';
import 'package:vasthram/RemoteData.dart';

class Uploadstylecode extends StatefulWidget {
  const Uploadstylecode({super.key});
  @override
  State<StatefulWidget> createState() => _Uploadstylecode();
}

class _Uploadstylecode extends State<Uploadstylecode> {
  File? imagefile;
  final ImagePicker _picker = ImagePicker();
  late List<File> arraylist = [];
  final TextEditingController _stylecode = TextEditingController();
  XFile? image;
  bool isloading = false;
  bool isVisible = true;
  bool isData = false;
  String? graph;
  String? graph1;
  Uint8List? bytes;
  Uint8List? bytes1;
  var bodycolor = '';
  var bodydesigncolor = '';
  var bordercolor = '';
  var bordersize = '';
  var borderworkcolor = '';
  var stylecode = '';
  var status = '';
  int similarsale = 0;
  int similarstock = 0;
  late PageController _pageController;
  List<Widget> pages = [];
  Uint8List? imageBytes;
  List<dynamic>? embedding;
  bool _isPickingImage = false;
  String? _base64Image;

  // void getImage(File? imagefile) {
  //   // Reading image bytes from file
  //   final imageData = File(imagefile!.path).readAsBytesSync();
  //   // Decoding image
  //   final image = img.decodeImage(imageData);
  //   // Resizing image fpr model, [300, 300]
  //   final imageInput = img.copyResize(
  //     image!,
  //     width: 300,
  //     height: 300,
  //   );
  //   if (kDebugMode) {
  //     print(imageInput);
  //   }
  // // Creating matrix representation, [300, 300, 3]
  // final imageMatrix = List.generate(
  //     imageInput.height,
  //     (y) => List.generate(
  //       imageInput.width,
  //       (x) {
  //         final pixel = imageInput.getPixel(x, y);
  //         final r = img.getRed(pixel);
  //         final g = img.getGreen(pixel);
  //         final b = img.getBlue(pixel);
  //         return [r, g, b];
  //       },
  //     ),
  //   );
  //   embedding = imageMatrix;
  //   if (kDebugMode) {
  //     print(imageMatrix);
  //   }
  // }
  // Future<void> _getImage(int index) async {
  //   image = await _picker.pickImage(source: ImageSource.camera);
  //   print('Testing Image ==========> $image');
  //   if (image != null) {
  //     setState(() {
  //       imagefile = File(image!.path);
  //       isVisible = true;
  //       isData = false;
  //       //getImage(imagefile);
  //     });
  //   } else {
  //     image = await _picker.pickImage(source: ImageSource.camera);
  //   }
  // }

  Future<void> _navigateToCameraScreen() async {
    print('Hitting or not');
    try {
      final imageFile1 = await Navigator.push<File>(
        context,
        MaterialPageRoute(builder: (context) => CameraScreen()),
      );
      imagefile = imageFile1;
      final bytes = await imageFile1?.readAsBytes();
      final base64String1 = base64Encode(bytes!);
      setState(() {
        _base64Image = base64String1;
      });
      if (imageFile1 != null) {
        print('Camera Capture ==========> $imageFile1');
        setState(() {
          isloading = true; // Set loading state to true
        });
        bool isInternetConnected = await Constants.checkInternetConnectivity();
        if (isInternetConnected) {
          Constants.Showindicator(context, 'Detecting Saree');
          var upload = await RemoteData().uploadimage(imagefile!, '');
          print(_stylecode.text);
          if (upload != null) {
            setState(() {
              isloading = false;
            });
            var jsonResponse = jsonDecode(upload);
            await Future.delayed(const Duration(seconds: 1));
            updateUI(jsonResponse);
          }
          if (Navigator.of(context).canPop()) {
            if (kDebugMode) {
              print('Testing =========>');
            }
            //Navigator.of(context).pop();
          }
        } else {
          setDialog('Check your internet connection');
        }
      }
      // Handle imageFile
    } catch (e) {
      print('Error navigating to CameraScreen: $e');
    }
  }

  Future<void> _getImage() async {
    if (_isPickingImage) return;
    _isPickingImage = true;

    try {
      final pickedFile = await _picker.pickImage(source: ImageSource.camera);
      if (pickedFile != null) {
        setState(() {
          imagefile = File(pickedFile.path);
          isVisible = true;
          isData = false;
        });
        print('Image picked successfully: ${pickedFile.path}');
      } else {
        print("No image picked");
      }
    } catch (e) {
      print("Error while picking image from camera: $e");
    } finally {
      _isPickingImage = false;
    }
  }

  void _showPicker(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text(
            'SELECT OPTION',
            style: Constants.dialogbuttonstyle,
          ),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                GestureDetector(
                  child: const Text(
                    'CAMERA',
                    style: Constants.dialogbuttonstyle,
                  ),
                  onTap: () {
                    _navigateToCameraScreen();
                    Navigator.of(context).pop();
                  },
                ),
                const Padding(padding: EdgeInsets.all(8.0)),
                GestureDetector(
                  child: const Text(
                    'GALLERY',
                    style: Constants.dialogbuttonstyle,
                  ),
                  onTap: () {
                    _getImageFromGallery(context);
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> _getImageFromCamera() async {
    try {
      final pickedFile = await _picker.pickImage(source: ImageSource.camera);
      if (pickedFile != null) {
        setState(() {
          imagefile = File(pickedFile.path);
          isVisible = true;
          isData = false;
        });
      }
    } catch (e) {
      if (kDebugMode) {
        print("Error while picking image from camera: $e");
      }
    }
  }

  // 54639
  Future<void> _getImageFromGallery(BuildContext context) async {
    image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        imagefile = File(image!.path);
        isVisible = true;
        isData = false;
        //getImage(imagefile);
      });
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _pageController = PageController(initialPage: 0);
    });
    //loadModel();
  }

  Future<void> loadModel() async {
    String? modelPath = 'assets/images/model.tflite';
    if (kDebugMode) {
      print('Loading interpreter options...');
    }
    final interpreterOptions = InterpreterOptions();
    if (Platform.isAndroid) {
      interpreterOptions.addDelegate(XNNPackDelegate());
    }
    if (Platform.isIOS) {
      interpreterOptions.addDelegate(GpuDelegate());
    }
    if (kDebugMode) {
      print('Loading interpreter...');
    }
  }

  @override
  void dispose() {
    _pageController.dispose();
    _stylecode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          'REGISTER STYLE CODE',
          style: Constants.colorfontStyle,
        ),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Color.fromARGB(255, 69, 66, 121),
            size: 24,
          ),
          onPressed: () => Navigator.pop(context),
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      body: Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage(
                    'assets/images/bg.png'), // Path to your background image
                fit: BoxFit.cover,
              ),
            ),
          ),
          SingleChildScrollView(
            child: Container(
              margin: const EdgeInsets.all(20.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  SizedBox(
                    height: 60,
                    child: TextFormField(
                      cursorColor: const Color.fromARGB(255, 69, 66, 121),
                      keyboardType: TextInputType.streetAddress,
                      controller: _stylecode,
                      scrollPadding: const EdgeInsets.all(100.0),
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                        hintText: 'Stylecode',
                        filled: true,
                        fillColor: const Color.fromARGB(255, 244, 244, 254),
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(
                      height:
                          20), // Add spacing between the TextFormField and the image
                  GestureDetector(
                    onTap: () {
                      //_getImage(0);
                      if (_stylecode.text.isEmpty) {
                        setDialog('Enter StyleCode');
                      } else {
                        _navigateToCameraScreen();
                      }
                    },
                    // child: Container(
                    //   height: MediaQuery.of(context).size.height *
                    //       0.65, // Adjusted height for the image container
                    //   // decoration: BoxDecoration(
                    //   //   border: Border.all(color: Colors.grey),
                    //   // ),
                    //   child: imagefile != null
                    //       ? Image.file(
                    //           imagefile!,
                    //           fit: BoxFit.cover,
                    //         )
                    //       : Center(
                    //           child: Image.asset(
                    //             'assets/images/camera.png',
                    //             width: MediaQuery.of(context).size.width *
                    //                 0.50, // Adjusted width
                    //             height: MediaQuery.of(context).size.height *
                    //                 0.35, // Adjusted height
                    //           ),
                    //         ),
                    // ),
                    child: Container(
                      //width: MediaQuery.of(context).size.width * 0.88,
                      height: MediaQuery.of(context).size.height * 0.65,
                      child: _base64Image != null
                          ? Image.memory(
                              base64Decode(_base64Image!),
                              fit: BoxFit.cover,
                            )
                          : Center(
                              child: Image.asset(
                                'assets/images/camera.png',
                                width: MediaQuery.of(context).size.width *
                                    0.50, // Adjusted width
                                height: MediaQuery.of(context).size.height *
                                    0.35, // Adjusted height
                              ),
                            ),
                    ),
                  ),
                  const SizedBox(
                      height:
                          20), // Add spacing between the image and the button
                  // Visibility(
                  //   visible: isVisible,
                  //   child: SizedBox(
                  //     width: MediaQuery.of(context).size.width * 0.90,
                  //     child: GestureDetector(
                  //       onTap: () async {
                  //         if (imagefile == null) {
                  //           setDialog('Please Capture Image');
                  //         } else {
                  //           setState(() {
                  //             isloading = true; // Set loading state to true
                  //           });
                  //           bool isInternetConnected =
                  //               await Constants.checkInternetConnectivity();
                  //           if (isInternetConnected) {
                  //             showDialog(
                  //                 context: context,
                  //                 barrierDismissible: false,
                  //                 builder: (context) {
                  //                   return const Center(
                  //                     child: CircularProgressIndicator(
                  //                       color: Color.fromARGB(255, 69, 66, 121),
                  //                     ),
                  //                   );
                  //                 });
                  //             var upload = await RemoteData()
                  //                 .uploadimage(imagefile!, '');
                  //             print(_stylecode.text);
                  //             if (upload != null) {
                  //               setState(() {
                  //                 isloading = false;
                  //               });
                  //               var jsonResponse = jsonDecode(upload);
                  //               await Future.delayed(
                  //                   const Duration(seconds: 1));
                  //               updateUI(jsonResponse);
                  //             }
                  //             if (Navigator.of(context).canPop()) {
                  //               if (kDebugMode) {
                  //                 print('Testing =========>');
                  //               }
                  //               //Navigator.of(context).pop();
                  //             }
                  //           } else {
                  //             setDialog('Check your internet connection');
                  //           }
                  //         }
                  //       },
                  //       child: Container(
                  //         margin: const EdgeInsets.only(
                  //             left: 10, top: 0, right: 2, bottom: 0),
                  //         width: MediaQuery.of(context).size.width * 0.50,
                  //         height: MediaQuery.of(context).size.width * 0.13,
                  //         padding: const EdgeInsets.all(5),
                  //         decoration: BoxDecoration(
                  //           gradient: const LinearGradient(
                  //             begin: Alignment.bottomLeft,
                  //             end: Alignment.bottomRight,
                  //             colors: [
                  //               Color.fromARGB(255, 227, 144, 214),
                  //               Color.fromARGB(255, 125, 174, 251),
                  //             ],
                  //           ),
                  //           borderRadius: BorderRadius.circular(50),
                  //         ),
                  //         child: const Center(
                  //           child: Text(
                  //             'REGISTER STYLE CODE',
                  //             style: Constants.buttonsfontStyle,
                  //             textAlign: TextAlign.center,
                  //           ),
                  //         ),
                  //       ),
                  //     ),
                  //   ),
                  // ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // @override
  // Widget build(BuildContext context) {
  //   return Scaffold(
  //     resizeToAvoidBottomInset: false,
  //     appBar: AppBar(
  //       title: Text(
  //         'REGISTER STYLE CODE',
  //         style: Constants.colorfontStyle,
  //       ),
  //       automaticallyImplyLeading: false,
  //       leading: IconButton(
  //         icon: const Icon(
  //           Icons.arrow_back_ios,
  //           color: Color.fromARGB(255, 69, 66, 121),
  //           size: 24,
  //         ),
  //         onPressed: () => Navigator.pop(context),
  //       ),
  //       flexibleSpace: Container(
  //         decoration: BoxDecoration(
  //           gradient: Constants.getReturn(),
  //         ),
  //       ),
  //     ),
  //     body: Stack(
  //       children: [
  //         Container(
  //           decoration: const BoxDecoration(
  //             image: DecorationImage(
  //               image: AssetImage(
  //                   'assets/images/bg.png'), // Path to your background image
  //               fit: BoxFit.cover,
  //             ),
  //           ),
  //         ),
  //         SingleChildScrollView(
  //           child: Container(
  //             margin: const EdgeInsets.all(20.0),
  //             child: Column(
  //               mainAxisAlignment: MainAxisAlignment.start,
  //               children: <Widget>[
  //                 Row(
  //                   mainAxisAlignment: MainAxisAlignment.spaceAround,
  //                   children: [
  //                     SizedBox(
  //                       height: 60,
  //                       child: TextFormField(
  //                         cursorColor: const Color.fromARGB(255, 69, 66, 121),
  //                         keyboardType: TextInputType.number,
  //                         controller: _stylecode,
  //                         scrollPadding: const EdgeInsets.all(100.0),
  //                         decoration: InputDecoration(
  //                           contentPadding:
  //                               const EdgeInsets.fromLTRB(20, 0, 20, 0),
  //                           hintText: 'Stylecode',
  //                           filled: true,
  //                           fillColor: const Color.fromARGB(255, 244, 244, 254),
  //                           border: OutlineInputBorder(
  //                             borderSide: BorderSide.none,
  //                             borderRadius: BorderRadius.circular(10),
  //                           ),
  //                         ),
  //                       ),
  //                     ),
  //                     Flexible(
  //                       child: Column(
  //                         children: [
  //                           const Padding(padding: EdgeInsets.only(top: 5)),
  //                           GestureDetector(
  //                             onTap: () {
  //                               _getImage(0);
  //                             },
  //                             child: SizedBox(
  //                               width: MediaQuery.of(context).size.width * 0.88,
  //                               height:
  //                                   MediaQuery.of(context).size.height * 0.68,
  //                               child: imagefile != null
  //                                   ? Image.file(
  //                                       imagefile!,
  //                                       fit: BoxFit.cover,
  //                                     )
  //                                   : Center(
  //                                       child: Image.asset(
  //                                         'assets/images/camera.png',
  //                                         width: MediaQuery.of(context)
  //                                                 .size
  //                                                 .width *
  //                                             0.50, // Adjusted width
  //                                         height: MediaQuery.of(context)
  //                                                 .size
  //                                                 .height *
  //                                             0.35, // Adjusted height
  //                                       ),
  //                                     ),
  //                             ),
  //                           ),
  //                         ],
  //                       ),
  //                     ),
  //                   ],
  //                 ),
  //                 SizedBox(
  //                   height: MediaQuery.of(context).size.height * 0.10,
  //                 ),
  //                 Visibility(
  //                   visible: isVisible,
  //                   child: SizedBox(
  //                     width: MediaQuery.of(context).size.width * 0.90,
  //                     child: GestureDetector(
  //                       onTap: () async {
  //                         if (imagefile == null) {
  //                           setDialog('Please Capture Image');
  //                         } else {
  //                           setState(() {
  //                             isloading = true; // Set loading state to true
  //                           });
  //                           bool isInternetConnected =
  //                               await Constants.checkInternetConnectivity();
  //                           if (isInternetConnected) {
  //                             showDialog(
  //                                 context: context,
  //                                 barrierDismissible: false,
  //                                 builder: (context) {
  //                                   return const Center(
  //                                     child: CircularProgressIndicator(
  //                                       color: Color.fromARGB(255, 69, 66, 121),
  //                                     ),
  //                                   );
  //                                 });
  //                             var upload = await RemoteData().uploadimage(
  //                                 imagefile!, embedding!.toString());
  //                             if (upload != null) {
  //                               setState(() {
  //                                 isloading = false;
  //                               });
  //                               var jsonResponse = jsonDecode(upload);
  //                               await Future.delayed(
  //                                   const Duration(seconds: 1));
  //                               updateUI(jsonResponse);
  //                             }
  //                             if (Navigator.of(context).canPop()) {
  //                               if (kDebugMode) {
  //                                 print('Testing =========>');
  //                               }
  //                               Navigator.of(context).pop();
  //                             }
  //                           } else {
  //                             setDialog('Check your internet connection');
  //                           }
  //                         }
  //                       },
  //                       child: Container(
  //                         margin: const EdgeInsets.only(
  //                             left: 10, top: 0, right: 2, bottom: 0),
  //                         width: MediaQuery.of(context).size.width * 0.100,
  //                         height: MediaQuery.of(context).size.width * 0.13,
  //                         padding: const EdgeInsets.all(5),
  //                         decoration: BoxDecoration(
  //                           gradient: const LinearGradient(
  //                             begin: Alignment.bottomLeft,
  //                             end: Alignment.bottomRight,
  //                             colors: [
  //                               Color.fromARGB(255, 227, 144, 214),
  //                               //Color(0xFFC2185B),
  //                               Color.fromARGB(255, 125, 174, 251),
  //                             ],
  //                           ),
  //                           borderRadius: BorderRadius.circular(50),
  //                         ),
  //                         child: const Row(
  //                           children: [
  //                             Text('\t\t'),
  //                             // replace with your image

  //                             Expanded(
  //                               child: Center(
  //                                 child: Text(
  //                                   'REGISTER STYLE CODE',
  //                                   style: Constants.buttonsfontStyle,
  //                                   textAlign: TextAlign.center,
  //                                 ),
  //                               ),
  //                             ),
  //                           ],
  //                         ),
  //                       ),
  //                     ),
  //                   ),
  //                 ),
  //               ],
  //             ),
  //           ),
  //         ),
  //       ],
  //     ),
  //   );
  // }

  Future<void> updateUI(Map<String, dynamic> jsonResponse) async {
    Navigator.of(context).pop();
    print('Response Data : $jsonResponse');
    var saree = jsonResponse['saree_detected'];
    if (saree == 'Yes') {
      var bodyimage = jsonResponse['body_metrics'][3];
      var annotated_image = jsonResponse['annotated_image'];
      setState(() {
        _base64Image = annotated_image;
      });
      Constants.Showindicator(context, 'Register Stylecode');
      var upload = await RemoteData()
          .registerStyleCode(imagefile!, bodyimage, _stylecode.text);
      if (upload != null) {
        var json = jsonDecode(upload);
        await Future.delayed(const Duration(seconds: 1));
        getupdate(json);
        print(upload);
      }

      return;
    } else {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return CustomAlertDialog(
            titleText: 'WARNING ! \t',
            contentText: 'Saree Not Detected',
            buttonText: 'No',
            onButtonPressed: () {
              Navigator.of(context).pop();
            },
            secondButtonText: 'Yes',
            onSecondButtonPressed: () {
              Navigator.of(context).pop(); // Close the dialog first
              // Navigate to CameraScreen after the dialog is closed
              Future.delayed(const Duration(milliseconds: 200), () {
                _navigateToCameraScreen();
              });
            },
            icon: const Icon(Icons.info),
          );
        },
      );
    }
  }

  void getupdate(Map<String, dynamic> jsonResponse) {
    setState(() {
      Navigator.of(context).pop();
      setState(() {
        isloading = false;
      });
      isVisible = false;
      //{"error_message":"","reg_status":"Success"}
      status = jsonResponse['reg_status'];
      if (status == 'Success') {
        print('Printing ===============>');
        isData = true;
        isloading = false;
        isVisible = false;
        setDialog('Uploaded Sucessfully');
        //Navigator.of(context).pop();
        //graph  = jsonResponse[''];
        //graph1 = jsonResponse[''];
      } else {
        print('Else Printing ===============>');

        setDialog(jsonResponse['reg_status']);
        //bytes!.clear();
        //bytes1!.clear();
        //embedding!.clear();
        //Navigator.of(context).pop();
      }
    });
  }

  void setDialog(String text) {
    print('Printing ===============>');
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CustomAlertDialog(
          titleText: 'WARNING ! \t',
          contentText: text,
          buttonText: '\t\t\tCANCEL\t\t\t',
          onButtonPressed: () {
            Navigator.of(context).pop();
          },
          icon: Image.asset(
            'assets/images/error.png',
            width: 58,
            height: 58,
          ),
        );
      },
    );
  }
}
