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:vasthram/Constants.dart';
import 'package:vasthram/CustomAlertDialog.dart';
import 'package:vasthram/RemoteData.dart';
import 'CameraScreen.dart';

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

class _Identifyproduct extends State<Identifyproduct> {
  File? imagefile;
  final ImagePicker _picker = ImagePicker();
  late List<File> arraylist = [];
  XFile? image;
  bool isloading = false;
  bool isVisible = true;
  bool isData = false;
  String? graph;
  String? graph1;
  Uint8List? bytes;
  Uint8List? bytes1;
  var bodycolor = '';
  var bordercolor = '';
  double bordersize = 0.0;
  var stylecode = '';
  var status = '';
  late PageController _pageController;
  List<Widget> pages = [];
  Uint8List? imageBytes;
  List<dynamic>? embedding;
  String? _base64Image;

  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: () {
                    Navigator.of(context).pop();
                    _navigateToCameraScreen();
                  },
                ),
                const Padding(padding: EdgeInsets.all(8.0)),
                GestureDetector(
                  child: const Text(
                    'GALLERY',
                    style: Constants.dialogbuttonstyle,
                  ),
                  onTap: () {
                    _getImageFromGallery(context);
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> _navigateToCameraScreen() async {
    if (kDebugMode) {
      print('Hitting or not');
    }
    try {
      final imageFile1 = await Navigator.push<File>(
        context,
        MaterialPageRoute(builder: (context) => CameraScreen()),
      );
      if (imageFile1 != null) {
        if (kDebugMode) {
          print('Camera Capture ==========> $imageFile1');
        }
        imagefile = imageFile1;
        final bytes = await imageFile1.readAsBytes();
        final base64String1 = base64Encode(bytes);
        setState(() {
          _base64Image = base64String1;
        });
        getStatus(imagefile, 'camera');
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error navigating to CameraScreen: $e');
      }
    }
  }

  Future<void> getStatus(File? imagefile, String type) async {
    setState(() {
      isloading = true; // Set loading state to true
    });
    bool isInternetConnected = await Constants.checkInternetConnectivity();
    if (isInternetConnected) {
      Constants.Showindicator(context, 'Detecting Saree');
      var upload1 = await RemoteData().uploadimage(imagefile!, '');
      if (upload1 != null) {
        setState(() {
          isloading = false;
        });
        var jsonResponse = jsonDecode(upload1);
        await Future.delayed(const Duration(seconds: 1));
        updateUI(jsonResponse, type);
      }
    } else {
      setDialog('Check your internet connection');
    }
  }

  Future<void> _getImageFromGallery(BuildContext context) async {
    image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      if (kDebugMode) {
        print('Picked image from gallery: ${image!.path}');
      }
      setState(() {
        imagefile = File(image!.path);
        isVisible = true;
        isData = false;
      });
      getStatus(imagefile, 'gallery');
    }
  }

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

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

  Widget buildPage2(String title) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          const Padding(
              padding: EdgeInsets.only(left: 10, bottom: 10, top: 10)),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: const Color.fromARGB(255, 69, 66, 121),
                    borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(10),
                      bottomLeft: Radius.circular(10),
                    ),
                    border: Border.all(
                      color: Colors.white, // Set border color to white
                      width: 1, // Set border width
                    ),
                  ),
                  padding: const EdgeInsets.all(12),
                  child: const Column(
                    mainAxisAlignment:
                        MainAxisAlignment.end, // Align content at the bottom
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        'SIMILAR STOCK: ',
                        style: TextStyle(
                          fontSize: 15,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: const Color.fromARGB(255, 255, 255, 255),
                    borderRadius: const BorderRadius.only(
                      topRight: Radius.circular(10),
                      bottomRight: Radius.circular(10),
                    ),
                    border: Border.all(
                      color: Colors.white, // Set border color to white
                      width: 1, // Set border width
                    ),
                  ),
                  padding: const EdgeInsets.all(12),
                  child: const Column(
                    children: [
                      Text(
                        '',
                        style: TextStyle(
                          fontSize: 15,
                          color: Color.fromARGB(255, 69, 66, 121),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          const Padding(padding: EdgeInsets.only(left: 10, top: 10)),
        ],
      ),
    );
  }

  Widget buildPage3(String title) {
    return Center(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        const Padding(padding: EdgeInsets.only(left: 10, bottom: 10, top: 10)),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: const Color.fromARGB(255, 69, 66, 121),
                  borderRadius: const BorderRadius.only(
                    topLeft: Radius.circular(10),
                    bottomLeft: Radius.circular(10),
                  ),
                  border: Border.all(
                    color: Colors.white, // Set border color to white
                    width: 1, // Set border width
                  ),
                ),
                padding: const EdgeInsets.all(12),
                child: const Column(
                  mainAxisAlignment:
                      MainAxisAlignment.end, // Align content at the bottom
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      'SIMILAR SALE: ',
                      style: TextStyle(
                        fontSize: 15,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: const Color.fromARGB(255, 255, 255, 255),
                  borderRadius: const BorderRadius.only(
                    topRight: Radius.circular(10),
                    bottomRight: Radius.circular(10),
                  ),
                  border: Border.all(
                    color: Colors.white, // Set border color to white
                    width: 1, // Set border width
                  ),
                ),
                padding: const EdgeInsets.all(12),
                child: const Column(
                  children: [
                    Text(
                      '',
                      style: TextStyle(
                        fontSize: 15,
                        color: Color.fromARGB(255, 69, 66, 121),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        const Padding(padding: EdgeInsets.only(left: 10, top: 10)),
        Container(
          color: const Color.fromARGB(255, 240, 200, 159),
          child: Image.memory(
            bytes1!,
            fit: BoxFit.cover, // Adjust as needed
          ),
        ),
      ],
    ));
  }

  Widget buildPage1(String title) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          if (bodycolor.isNotEmpty || bordercolor.isNotEmpty)
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                const Padding(
                    padding: EdgeInsets.only(left: 10, bottom: 10, top: 10)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Flexible(
                      flex: 6, // 60% of the width
                      fit: FlexFit.tight,
                      child: Container(
                        decoration: BoxDecoration(
                          color: const Color.fromARGB(255, 69, 66, 121),
                          borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(10),
                            bottomLeft: Radius.circular(10),
                          ),
                          border: Border.all(
                            color: Colors.white, // Set border color to white
                            width: 1, // Set border width
                          ),
                        ),
                        padding: const EdgeInsets.all(12),
                        child: const Column(
                          mainAxisAlignment: MainAxisAlignment
                              .end, // Align content at the bottom
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Text(
                              '\tBODY COLOR: \t',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.white,
                              ),
                              textAlign: TextAlign.right,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Flexible(
                      flex: 4, // 40% of the width
                      fit: FlexFit.tight,
                      child: Container(
                        decoration: BoxDecoration(
                          color: const Color.fromARGB(255, 255, 255, 255),
                          borderRadius: const BorderRadius.only(
                            topRight: Radius.circular(10),
                            bottomRight: Radius.circular(10),
                          ),
                          border: Border.all(
                            color: Colors.white, // Set border color to white
                            width: 1, // Set border width
                          ),
                        ),
                        padding: const EdgeInsets.all(12),
                        child: Column(
                          children: [
                            Text(
                              bodycolor,
                              style: const TextStyle(
                                fontSize: 15,
                                color: Color.fromARGB(255, 69, 66, 121),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),

                const Padding(padding: EdgeInsets.only(left: 10, bottom: 8)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Flexible(
                      flex: 6,
                      fit: FlexFit.tight,
                      child: Container(
                        decoration: BoxDecoration(
                          color: const Color.fromARGB(255, 69, 66, 121),
                          borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(10),
                            bottomLeft: Radius.circular(10),
                          ),
                          border: Border.all(
                            color: Colors.white, // Set border color to white
                            width: 1, // Set border width
                          ),
                        ),
                        padding: const EdgeInsets.all(12),
                        child: const Column(
                          mainAxisAlignment: MainAxisAlignment
                              .end, // Align content at the bottom
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Text(
                              '\t BORDER COLOR:  \t',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.white,
                              ),
                              textAlign: TextAlign.right,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Flexible(
                      flex: 4, // 40% of the width
                      fit: FlexFit.tight,
                      child: Container(
                        decoration: BoxDecoration(
                          color: const Color.fromARGB(255, 255, 255, 255),
                          borderRadius: const BorderRadius.only(
                            topRight: Radius.circular(10),
                            bottomRight: Radius.circular(10),
                          ),
                          border: Border.all(
                            color: Colors.white, // Set border color to white
                            width: 1, // Set border width
                          ),
                        ),
                        padding: const EdgeInsets.all(12),
                        child: Column(
                          children: [
                            Text(
                              bordercolor,
                              style: const TextStyle(
                                fontSize: 15,
                                color: Color.fromARGB(255, 69, 66, 121),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),

                const Padding(padding: EdgeInsets.only(left: 10, bottom: 8)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Flexible(
                      flex: 6, // 60% of the width
                      fit: FlexFit.tight,
                      child: Container(
                        decoration: BoxDecoration(
                          color: const Color.fromARGB(255, 69, 66, 121),
                          borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(10),
                            bottomLeft: Radius.circular(10),
                          ),
                          border: Border.all(
                            color: Colors.white, // Set border color to white
                            width: 1, // Set border width
                          ),
                        ),
                        padding: const EdgeInsets.all(12),
                        child: const Column(
                          mainAxisAlignment: MainAxisAlignment
                              .end, // Align content at the bottom
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Text(
                              '\t BORDER SIZE:  \t',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.white,
                              ),
                              textAlign: TextAlign.right,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Flexible(
                      flex: 4, // 40% of the width
                      fit: FlexFit.tight,
                      child: Container(
                        decoration: BoxDecoration(
                          color: const Color.fromARGB(255, 255, 255, 255),
                          borderRadius: const BorderRadius.only(
                            topRight: Radius.circular(10),
                            bottomRight: Radius.circular(10),
                          ),
                          border: Border.all(
                            color: Colors.white, // Set border color to white
                            width: 1, // Set border width
                          ),
                        ),
                        padding: const EdgeInsets.all(12),
                        child: Column(
                          children: [
                            Text(
                              bordersize.toString(),
                              style: const TextStyle(
                                fontSize: 15,
                                color: Color.fromARGB(255, 69, 66, 121),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            )
          else
            const SizedBox(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(padding: EdgeInsets.only(bottom: 20)),
                  Text('\n'),
                  Text('\n'),
                  Text('\n'),
                  Text('\n'),
                  Text('\n'),
                ],
              ),
            ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          'IDENTIFY PRODUCT',
          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: [
                      Column(
                        children: [
                          const Padding(padding: EdgeInsets.only(top: 5)),
                          GestureDetector(
                            onTap: () {
                              _showPicker(context);
                            },
                            child: SizedBox(
                              width: MediaQuery.of(context).size.width * 0.90,
                              height: MediaQuery.of(context).size.height * 0.50,
                              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
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  if (isData)
                    SizedBox(
                      height: MediaQuery.of(context).size.height * 0.60,
                      child: PageView(
                        controller: _pageController,
                        children: pages = [
                          buildPage1('Page 1'),
                          //buildPage2('Page 2'),
                          //buildPage3('Page 3'),
                        ],
                      ),
                    ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.28,
                  ),
                  const Text('\n\n')
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> updateUI(Map<String, dynamic> jsonResponse1, String type) async {
    Navigator.of(context).pop();
    print('Response Data : $jsonResponse1');
    var saree = jsonResponse1['saree_detected'];
    if (kDebugMode) {
      print(saree);
    }
    if (saree == 'Yes') {
      var bodyimage = jsonResponse1['body_metrics'][3];
      var annotated_image = jsonResponse1['annotated_image'];
      setState(() {
        _base64Image = annotated_image;
      });
      print(bodyimage);
      try {
        Constants.Showindicator(context, 'Identify Product');
        var upload = await RemoteData().detectAttributes(imagefile!, bodyimage);
        var json = jsonDecode(upload!);
        await Future.delayed(const Duration(seconds: 1));
        getupdate(json);
      } catch (e) {
        print('verified$e');
        return;
      }
      return;
    } else {
      if (type == 'camera') {
        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();
                Future.delayed(const Duration(milliseconds: 200), () {
                  _navigateToCameraScreen();
                });
              },
              icon: const Icon(Icons.info),
            );
          },
        );
      } else {
        _getImageFromGallery(context);
      }
    }
  }

  void getupdate(Map<String, dynamic> jsonResponse) {
    print('Hitting ot npt $jsonResponse');
    Navigator.of(context).pop();
    setState(() {
      isloading = false;
    });
    isData = true;
    //isVisible = false;
    setState(() {
      isData = true;
      isVisible = false;
      status = jsonResponse['status']!;
      print(status);
      if (status == 'Success') {
        bodycolor = jsonResponse['body_color']!;
        bordercolor = jsonResponse['border_color']!;
        bordersize = jsonResponse['border_size'];
        _base64Image = jsonResponse['image'];
        //stylecode = jsonResponse['stylecode']!;
      } else {
        setDialog('Could not found IdentifyProduct');
        bodycolor = '';
        bordercolor = '';
        bordersize = 0.0;
        stylecode = '';
      }
    });

    print('Hitting ot npt $jsonResponse');
  }

  void setDialog(String text) {
    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,
          ),
        );
      },
    );
  }
}
