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

@immutable
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;
  var body_color = '';
  var body_design_color = '';
  var border_color = '';
  var border_size = '';
  var border_work_color = '';
  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);
      });
    } 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 (body_color.isNotEmpty ||
                body_design_color.isNotEmpty ||
                border_color.isNotEmpty ||
                border_size.isNotEmpty ||
                border_work_color.isNotEmpty)
              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Padding(padding: EdgeInsets.only(bottom: 20)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text('Body Design Color: $body_design_color\n'),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text('Border Color: $border_color\n'),
                    ],
                  ),
                ],
              )
            else
              const SizedBox(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(padding: EdgeInsets.only(bottom: 20)),
                    Text('\n'),
                    Text('\n'),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

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

  Widget buildPage1(String title) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          if (body_color.isNotEmpty ||
              body_design_color.isNotEmpty ||
              border_color.isNotEmpty ||
              border_size.isNotEmpty ||
              border_work_color.isNotEmpty)
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                const Padding(padding: EdgeInsets.only(bottom: 20)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text('Body Color: $body_color\n'),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text('Body Design Color: $body_design_color\n'),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text('Border Color: $border_color\n'),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text('Border Size: $border_size\n'),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text('Border Work Color: $border_work_color\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('VASTHRAM'),
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            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: 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)),
                      const Text(
                        'Capture Image',
                        style: TextStyle(
                          fontSize: 18,
                          color: Colors.black,
                          fontStyle: FontStyle.normal,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const Padding(padding: EdgeInsets.only(top: 15)),
                      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/camera.png',
                                  width:
                                      MediaQuery.of(context).size.width * 0.80,
                                  height:
                                      MediaQuery.of(context).size.height * 0.60,
                                ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.25,
                child: PageView(
                  controller: _pageController,
                  children: pages = [
                    buildPage1(
                        'Page 1'), // Replace with your content for the first object
                    buildPage2('Page 2'),
                    buildPage3(
                        'Page 3'), // Replace with your content for the second object
                    // Add more pages for other objects
                  ],
                ),
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.fromLTRB(20, 10, 20, 10),
                  backgroundColor: const Color.fromARGB(255, 170, 57, 230),
                  minimumSize: const Size.fromHeight(50),
                ),
                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 = true;
                        });
                        var jsonResponse = jsonDecode(upload);
                        await Future.delayed(const Duration(seconds: 2));

                        updateUI(jsonResponse);
                        setState(() {
                          isloading = false;
                        });
                      }

                      Navigator.of(context).pop();
                    } else {
                      Constants('Vasthram', 'Check your internet connection')
                          .showAlertDialog(context, true);
                    }
                  }
                },
                child: const Text('Upload Image'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void updateUI(Map<String, dynamic> jsonResponse) {
    setState(() {
      // Update variables based on jsonResponse
      status = jsonResponse['status'];
      print(status);
      if (status == 'Success') {
        print('One :$status');
        body_color = jsonResponse['body_color'];
        print('One :$body_color');
        body_design_color = jsonResponse['body_design_color'];
        print('One :$body_design_color');
        border_color = jsonResponse['border_color'];
        print('One :$border_color');

        border_size = jsonResponse['border_size'];
        print('One :$border_size');

        border_work_color = jsonResponse['border_work_color'];
        print('One :$border_work_color');
      } else {
        print('Two :$status');
        Constants.dialogMessage(context, 'Vasthram', 'Could not found image');
        body_color = '';
        body_design_color = '';
        border_color = '';
        border_size = '';
        border_work_color = '';
      }
    });
    _pageController.jumpToPage(0);
  }
}
