import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:vasthram/Constants.dart';
import 'package:vasthram/RemoteData.dart';
import 'package:vasthram/SignUp.dart';

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

class _Home extends State<Home> {
  File? imagefile;
  final ImagePicker _picker = ImagePicker();
  late List<File> arraylist = [];
  XFile? image;
  bool isloading = false;
  bool isVisible = true;
  bool isData = false;
  var bodycolor = '';
  var bodydesigncolor = '';
  var bordercolor = '';
  var bordersize = '';
  var borderworkcolor = '';
  var status = '';
  final PageController _pageController = PageController(initialPage: 0);
  List<Widget> pages = [];

  Future<void> _getImage(int index) async {
    image = await _picker.pickImage(source: ImageSource.camera);
    if (image != null) {
      setState(() {
        imagefile = File(image!.path);
        isVisible = true;
        isData = false;
      });
    } else {
      image = await _picker.pickImage(source: ImageSource.camera);
    }
  }

  @override
  void initState() {
    super.initState();
  }

  Widget buildPage2(String title) {
    return Center(
      child: Container(
        color: const Color.fromRGBO(222, 221, 220, 1),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            if (bodycolor.isNotEmpty ||
                bodydesigncolor.isNotEmpty ||
                bordercolor.isNotEmpty ||
                bordersize.isNotEmpty ||
                borderworkcolor.isNotEmpty)
              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Padding(padding: EdgeInsets.only(left: 10, bottom: 30)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text('Body Design Color: $bodydesigncolor\n'),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text('Border Color: $bordercolor\n'),
                    ],
                  ),
                ],
              )
            else
              const SizedBox(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(padding: EdgeInsets.only(bottom: 30)),
                    Text('\n'),
                    Text('\n'),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget buildPage3(String title) {
    return Container(
      color: const Color.fromARGB(255, 240, 200, 159),
    );
  }

  Widget buildPage1(String title) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          if (bodycolor.isNotEmpty ||
              bodydesigncolor.isNotEmpty ||
              bordercolor.isNotEmpty ||
              bordersize.isNotEmpty ||
              borderworkcolor.isNotEmpty)
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                const Padding(padding: EdgeInsets.only(left: 10, bottom: 10)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 140, 71, 86),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            bottomLeft: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: const Column(
                          children: [
                            Text(
                              'Body Color: ',
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 255, 255, 255),
                          borderRadius: BorderRadius.only(
                            topRight: Radius.circular(20),
                            bottomRight: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: Column(
                          children: [
                            Text(
                              bodycolor,
                              style: const TextStyle(
                                fontSize: 16,
                                color: Color.fromARGB(
                                  255,
                                  140,
                                  71,
                                  86,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),

                const Padding(padding: EdgeInsets.only(left: 10, bottom: 10)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 140, 71, 86),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            bottomLeft: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: const Column(
                          children: [
                            Text(
                              'Body Design Color: ',
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 255, 255, 255),
                          borderRadius: BorderRadius.only(
                            topRight: Radius.circular(20),
                            bottomRight: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: Column(
                          children: [
                            Text(
                              bodydesigncolor,
                              style: const TextStyle(
                                fontSize: 16,
                                color: Color.fromARGB(
                                  255,
                                  140,
                                  71,
                                  86,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),

                const Padding(padding: EdgeInsets.only(left: 10, bottom: 10)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 140, 71, 86),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            bottomLeft: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: const Column(
                          children: [
                            Text(
                              'Border Color: ',
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 255, 255, 255),
                          borderRadius: BorderRadius.only(
                            topRight: Radius.circular(20),
                            bottomRight: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: Column(
                          children: [
                            Text(
                              bordercolor,
                              style: const TextStyle(
                                fontSize: 16,
                                color: Color.fromARGB(
                                  255,
                                  140,
                                  71,
                                  86,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                // Row(
                //   mainAxisAlignment: MainAxisAlignment.start,
                //   children: [
                //     Text('Body Design Color: $bodydesigncolor\n'),
                //   ],
                // ),
                const Padding(padding: EdgeInsets.only(left: 10, bottom: 10)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 140, 71, 86),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            bottomLeft: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: const Column(
                          children: [
                            Text(
                              'Body Size: ',
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 255, 255, 255),
                          borderRadius: BorderRadius.only(
                            topRight: Radius.circular(20),
                            bottomRight: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: Column(
                          children: [
                            Text(
                              bordersize,
                              style: const TextStyle(
                                fontSize: 16,
                                color: Color.fromARGB(
                                  255,
                                  140,
                                  71,
                                  86,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),

                const Padding(padding: EdgeInsets.only(left: 10, bottom: 10)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 140, 71, 86),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            bottomLeft: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: const Column(
                          children: [
                            Text(
                              'Body Work Color: ',
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: const BoxDecoration(
                          color: Color.fromARGB(255, 255, 255, 255),
                          borderRadius: BorderRadius.only(
                            topRight: Radius.circular(20),
                            bottomRight: Radius.circular(20),
                          ),
                        ),
                        padding: const EdgeInsets.all(10),
                        child: Column(
                          children: [
                            Text(
                              borderworkcolor,
                              style: const TextStyle(
                                fontSize: 16,
                                color: Color.fromARGB(
                                  255,
                                  140,
                                  71,
                                  86,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                // Row(
                //   mainAxisAlignment: MainAxisAlignment.start,
                //   children: [
                //     Text('Border Color: $bordercolor\n'),
                //   ],
                // ),
                // Row(
                //   mainAxisAlignment: MainAxisAlignment.start,
                //   children: [
                //     Text('Border Size: $bordersize\n'),
                //   ],
                // ),
                // Row(
                //   mainAxisAlignment: MainAxisAlignment.start,
                //   children: [
                //     Text('Border Work Color: $borderworkcolor\n'),
                //   ],
                // ),
              ],
            )
          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: const Text(
          'CAPTURE IMAGE',
          style: Constants.fontStyle,
        ),
        actions: [
          IconButton(
            icon: Image.asset(
              "assets/images/signout.png",
              width: 24, // Adjust the width as needed
              height: 24, // Adjust the height as needed
            ),
            onPressed: () async {
              bool valid = await Constants.checkInternetConnectivity();
              if (valid) {
                Constants.saveLoginCredentials('', '', '', '', '', false);
                Navigator.pushReplacement(context,
                    MaterialPageRoute(builder: (context) => const SignUp()));
              } else {
                Constants('Vasthram', 'Check your internet connection')
                    .showAlertDialog(context, true);
              }
            },
          ),
        ],
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/bg.png"),
            fit: BoxFit.cover, // Adjust as needed
          ),
        ),
        child: SingleChildScrollView(
          child: Container(
            margin: const EdgeInsets.all(10.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Column(
                      children: [
                        const Padding(padding: EdgeInsets.only(top: 5)),
                        GestureDetector(
                          onTap: () {
                            _getImage(0);
                          },
                          child: SizedBox(
                            width: MediaQuery.of(context).size.width * 0.94,
                            height: MediaQuery.of(context).size.height * 0.50,
                            child: imagefile != null
                                ? Image.file(
                                    imagefile!,
                                    fit: BoxFit.cover,
                                  )
                                : Image.asset(
                                    'assets/images/captureimage.png',
                                    width: MediaQuery.of(context).size.width *
                                        0.80,
                                    height: MediaQuery.of(context).size.height *
                                        0.60,
                                  ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                if (isData)
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.30,
                    child: PageView(
                      controller: _pageController,
                      children: pages = [
                        buildPage1('Page 1'),
                        buildPage2('Page 2'),
                        buildPage3('Page 3'),
                      ],
                    ),
                  ),
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.30,
                ),
                Visibility(
                  visible: isVisible,
                  child: ElevatedButton(
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(
                              50.0), // Adjust the radius as needed
                        ),
                      ),
                      minimumSize: MaterialStateProperty.all<Size>(
                        const Size(double.infinity, 50),
                      ),
                      backgroundColor: MaterialStateProperty.all<Color>(
                        const Color.fromARGB(255, 126, 69,
                            85), // Adjust the background color as needed
                      ),
                    ),
                    onPressed: () async {
                      if (imagefile == null) {
                        Constants('Vasthram', 'Please Capture Image')
                            .showAlertDialog(context, true);
                      } else {
                        isloading = true;
                        bool isInternetConnected =
                            await Constants.checkInternetConnectivity();
                        if (isInternetConnected) {
                          showDialog(
                            context: context,
                            builder: (context) {
                              return const Center(
                                child: CircularProgressIndicator(),
                              );
                            },
                          );
                          var upload =
                              await RemoteData().uploadimage(imagefile!);
                          if (upload != null) {
                            setState(() {
                              isloading = false;
                              Navigator.of(context).pop();
                            });
                            var jsonResponse = jsonDecode(upload);
                            await Future.delayed(const Duration(seconds: 2));
                            updateUI(jsonResponse);
                          }
                        } else {
                          Constants(
                                  'Vasthram', 'Check your internet connection')
                              .showAlertDialog(context, true);
                        }
                      }
                    },
                    child: const Text(
                      'UPLOAD IMAGE',
                      style: Constants.buttonsfontStyle,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void updateUI(Map<String, dynamic> jsonResponse) {
    setState(() {
      isData = true;
      isloading = false;
      isVisible = false;
      status = jsonResponse['status'];
      if (status == 'Success') {
        bodycolor = jsonResponse['body_color'];
        bodydesigncolor = jsonResponse['body_design_color'];
        bordercolor = jsonResponse['border_color'];
        bordersize = jsonResponse['border_size'];
        borderworkcolor = jsonResponse['border_work_color'];
      } else {
        Constants.dialogMessage(context, 'Vasthram', 'Could not found image');
        bodycolor = '';
        bodydesigncolor = '';
        bordercolor = '';
        bordersize = '';
        borderworkcolor = '';
      }
    });
    _pageController.jumpToPage(0);
  }
}
