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

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

class _Identifystylecode extends State<Identifystylecode> {
  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 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;
  List<Stylecode>? closestStylecodes;
  File? imagefile0;
  CameraController? controller;
  String? _base64Image;

  Future<void> initializeCamera() async {
    final cameras = await availableCameras();
    final frontCamera = cameras.firstWhere(
        (camera) => camera.lensDirection == CameraLensDirection.back);
    if (frontCamera == null) {
      if (kDebugMode) {
        print('No front camera found');
      }
      return;
    }
    controller = CameraController(frontCamera, ResolutionPreset.veryHigh);
    await controller!.initialize();
  }

  Future<void> _navigateToCameraScreen() async {
    try {
      final imageFile1 = await Navigator.push<File>(context, MaterialPageRoute(builder: (context) => CameraScreen()));
      if (imageFile1 != null) {
        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');
      }
    }
  }

  //
  void _showPicker(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext dialogContext) {
        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(dialogContext).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> _getImageFromGallery(BuildContext context) async {
    image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        imagefile = File(image!.path);
        isVisible = true;
        isData = false;
      });
      getStatus(imagefile, 'gallery');
    }
  }

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



  @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: Column(
                    children: [
                      Text(
                        similarstock.toString(),
                        style: const TextStyle(
                          fontSize: 15,
                          color: Color.fromARGB(255, 69, 66, 121),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          const Padding(padding: EdgeInsets.only(left: 10, top: 10)),
          Container(
            color: const Color.fromRGBO(222, 221, 220, 1),
            child: Image.memory(
              bytes!,
              fit: BoxFit.contain, // Adjust as needed
            ),
          ),
        ],
      ),
    );
  }

  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: Column(
                  children: [
                    Text(
                      similarsale.toString(),
                      style: const 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 SizedBox(
      height: MediaQuery.of(context).size.height * 0.60,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          if (closestStylecodes!.isNotEmpty)
            Expanded(
              // Use Expanded to ensure ListView gets the remaining space
              child: ListView.builder(
                itemCount: closestStylecodes!.length,
                itemBuilder: (context, index) {
                  return Card(
                    child: Column(
                      children: [
                        ListTile(
                          title: Text(
                            'Style Code \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: ${closestStylecodes![index].styleCode!.toUpperCase()}',
                            style: Constants.headerfontStyle,
                          ),
                          subtitle: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const SizedBox(
                                height: 8,
                              ),
                              Text(
                                'Similarity Percentage\t: ${closestStylecodes![index].similarityPercentage ?? 'None'}${closestStylecodes![index].similarityPercentage != 'None' ? '%' : ''}',
                                style: Constants.headerfontStyle,
                              ),
                            ],
                          ),
                          onTap: () {},
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            ElevatedButton(
                              onPressed: () {
                                Constants.Showindicator(
                                    context, 'Loading Data ...');
                                getStock(closestStylecodes![index].styleCode);
                              },
                              style: ElevatedButton.styleFrom(
                                backgroundColor:
                                    const Color.fromARGB(255, 69, 66, 121),
                              ),
                              child: const Text(
                                'Stock',
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                            const SizedBox(width: 16),
                            ElevatedButton(
                              onPressed: () {
                                Constants.Showindicator(
                                    context, 'Loading Data ...');
                                getSale(closestStylecodes![index].styleCode);
                              },
                              style: ElevatedButton.styleFrom(
                                  backgroundColor:
                                      const Color.fromARGB(255, 69, 66, 121)),
                              child: const Text('\tSale\t',
                                  style: TextStyle(color: Colors.white)),
                            ),
                            const SizedBox(width: 16),
                            ElevatedButton(
                              onPressed: () {
                                if (closestStylecodes![index]
                                        .similarImagePath !=
                                    'No Saree') {
                                  showDialog(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return AlertDialog(
                                        title: const Text('Style Code Details'),
                                        content: Column(
                                          mainAxisSize: MainAxisSize.min,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              'Style Code: ${closestStylecodes![index].styleCode}',
                                              style: Constants.headerfontStyle,
                                            ),
                                            Text(
                                              'Similarity Percentage: ${closestStylecodes![index].similarityPercentage ?? 'None'}${closestStylecodes![index].similarityPercentage != 'None' ? '%' : ''}',
                                              style: Constants.headerfontStyle,
                                            ),
                                            Image.network(
                                              closestStylecodes![index]
                                                  .similarImagePath!,
                                              width: 200,
                                              height: 200,
                                            ),
                                          ],
                                        ),
                                        actions: [
                                          TextButton(
                                            child: const Text('Close'),
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                          ),
                                        ],
                                      );
                                    },
                                  );
                                }
                              },
                              style: ElevatedButton.styleFrom(
                                backgroundColor: const Color.fromARGB(
                                    255, 69, 66, 121), // Background color
                              ),
                              child: const Text(
                                '\tView\t',
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 5),
                      ],
                    ),
                  );
                },
              ),
            )
          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'),
                  Text('\n'),
                  Text('\n'),
                ],
              ),
            ),
        ],
      ),
    );
  }

  getStock(String? text) {
    var response = RemoteData().stockData(text!);
    response.then((value) {
      Navigator.of(context).pop();
      final Map<String, dynamic> data = jsonDecode(value);
      _showListDialog(context, data, 'Stock Data');
    });
  }

  getSale(String? text) {
    var response = RemoteData().saleData(text!);
    response.then((value) {
      Navigator.of(context).pop();
      final Map<String, dynamic> data = jsonDecode(value);
      _showListDialog(context, data, 'Sale Data');
    });
  }

  void _showListDialog(
      BuildContext context, Map<String, dynamic> data, String header) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(header),
          content: SizedBox(
            // Set the height and width of the container
            width: double.maxFinite,
            child: ListView.builder(
              shrinkWrap: true,
              itemCount: data.keys.length,
              itemBuilder: (BuildContext context, int index) {
                String key = data.keys.elementAt(index);
                String value = data[key].toString();
                if (key == 'Average GST Margin 90 days') {
                  value = '₹ $value';
                }
                if (key == 'STORES') {
                  value = value.substring(1, value.length - 1);
                }
                return ListTile(
                  title: Text(key),
                  subtitle: Text(
                    value,
                    style: const TextStyle(
                        color: Color.fromARGB(255, 69, 66, 121)),
                  ),
                );
              },
            ),
          ),
          actions: [
            TextButton(
              child: const Text('Close'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          'IDENTIFY 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: [
                      Column(
                        children: [
                          const Padding(padding: EdgeInsets.only(top: 5)),
                          GestureDetector(
                            onTap: () {
                              _showPicker(context);
                            },
                            child: SizedBox(
                              width: MediaQuery.of(context).size.width * 0.88,
                              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
                                      ),
                                    ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  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')
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  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,
          ),
        );
      },
    );
  }

  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 annotatedimage = jsonResponse1['annotated_image'];
      setState(() {
        _base64Image = annotatedimage;
      });
      //print(bodyimage);
      try {
        Constants.Showindicator(context, 'Identify stylecode');
        var upload =
            await RemoteData().IdentifyStyleCode(imagefile!, bodyimage);
        //var json = jsonDecode(upload!);
        await Future.delayed(const Duration(seconds: 1));
        getupdate(upload!);
      } catch (e) {
        //print(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(var jsonResponse) {
    //print('Hitting ot npt $jsonResponse');
    Navigator.of(context).pop();
    setState(() {
      isloading = false;
    });
    isData = true;
    //isVisible = false;
    setState(() {
      //var jsonArray = jsonDecode(jsonString);
      var jsonArray = jsonDecode(jsonResponse);
      closestStylecodes = jsonArray.map<Stylecode>((json) {
        return Stylecode.fromJson(json);
      }).toList();
      //closestStylecodes = [Stylecode.fromJson(json)];
    });
    print('Hitting ot npt $jsonResponse');
  }

  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');
    }
  }
}

class Stylecode {
  final int? similarityPercentage;
  final String? similarImagePath;
  final String? styleCode;

  Stylecode({
    this.similarityPercentage,
    this.similarImagePath,
    this.styleCode,
  });

  factory Stylecode.fromJson(Map<String, dynamic> json) {
    return Stylecode(
      similarityPercentage: json['Similarity Percentage'] ?? '',
      similarImagePath: json['imageURL'] ?? '',
      styleCode: json['Stylecode'] ?? '',
    );
  }
}
