import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:vasthram/CustomAlertDialog.dart';
import 'package:vasthram/RemoteData.dart';
import 'package:vasthram/UserResponse.dart';
import 'Constants.dart';
import 'Home.dart';
import 'package:camera/camera.dart';

class SignUp extends StatefulWidget {
  const SignUp({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  final TextEditingController _email = TextEditingController();
  final TextEditingController _pass = TextEditingController();
  String dropdownValue = 'Option 1';
  bool item = true;
  File? imagefile;
  CameraController? controller;

  Future<void> login(String email, String pass) async {
    final response = await RemoteData().getLoginRequest(email, pass, '');
    try {
      Map<String, dynamic> responseMap = jsonDecode(response);
      if (responseMap['status'] == 'Success') {
        final userResponse = userResponseFromJson(response);
        if (userResponse.status.contains('Success')) {
          List<Map<String, dynamic>>? normalArray;
          if (userResponse.stores.isNotEmpty) {
            normalArray = userResponse.stores.map((item) {
              return {
                'name': item.storename,
              };
            }).toList();
          }
          String jsonStr = json.encode(normalArray);
          Navigator.pop(context);
          Constants.saveLoginCredentials(userResponse.empName, _email.text,
              jsonStr, '', userResponse.level, true);
          Navigator.pushReplacement(
              context, MaterialPageRoute(builder: (context) => const Home()));
        }
      } else {
        Navigator.pop(context);
        Constants('Login', responseMap['status'].toString())
            .showAlertDialog(context, false);
      }
    } catch (e) {
      Constants('Login', e.toString()).showAlertDialog(context, true);
    }
  }

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

  @override
  void dispose() {
    _email.dispose();
    _pass.dispose();
    controller?.dispose();
    super.dispose();
  }

  Future<void> takePicture() async {
    if (controller == null || !controller!.value.isInitialized) {
      await initializeCamera();
    }
    // Take a picture
    final XFile? picture = await controller!.takePicture();
    if (picture != null) {
      setState(() {
        imagefile = File(picture.path);
      });
    }
    print('Picture taken at: ${picture!.path}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //resizeToAvoidBottomInset: false,

      body: Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage(
                    "assets/images/bg.png"), // Path to your background image
                fit: BoxFit.cover,
              ),
            ),
          ),
          SingleChildScrollView(
            reverse: true,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                const SizedBox(
                  height: 150,
                ),
                Image.asset(
                  "assets/images/logo.png",
                  width: 320,
                  height: 220,
                ),
                const SizedBox(
                  height: 20,
                ),
                const Padding(
                  padding: EdgeInsets.only(
                      top: 40.0, left: 20.0, right: 20.0, bottom: 0),
                  child: SizedBox(
                    height: 45,
                    child: Text(
                      'LOGIN',
                      style: Constants.loginfontStyle,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      top: 0, left: 20.0, right: 20.0, bottom: 0),
                  child: SizedBox(
                    height: 60,
                    child: TextFormField(
                      cursorColor: const Color.fromARGB(255, 69, 66, 121),
                      keyboardType: TextInputType.number,
                      controller: _email,
                      scrollPadding: const EdgeInsets.all(100.0),
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                        hintText: 'USER ID',
                        filled: true,
                        fillColor: const Color.fromARGB(255, 244, 244, 254),
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                          borderRadius: BorderRadius.circular(50),
                        ),
                        suffixIcon: Padding(
                          padding: const EdgeInsets.only(right: 8.0),
                          child: IconButton(
                            onPressed: () {},
                            icon: Image.asset(
                              "assets/images/user.png",
                              width: 18,
                              height: 18,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      top: 0, left: 20.0, right: 20.0, bottom: 0),
                  child: SizedBox(
                    height: 60,
                    child: TextFormField(
                      cursorColor: const Color.fromARGB(255, 69, 66, 121),
                      obscureText: true,
                      controller: _pass,
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                        hintText: 'PASSWORD',
                        filled: true,
                        fillColor: const Color.fromARGB(255, 244, 244, 254),
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                          borderRadius: BorderRadius.circular(50),
                        ),
                        suffixIcon: Padding(
                          padding: const EdgeInsets.only(right: 8.0),
                          child: IconButton(
                            onPressed: () {},
                            icon: Image.asset(
                              "assets/images/password.png",
                              width: 18,
                              height: 18,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 80,
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width * 0.90,
                  child: GestureDetector(
                    onTap: () async {
                      if (_email.text.isEmpty && _pass.text.isEmpty) {
                        setDialog(
                          'Enter User Id & Password',
                        );
                      } else if (_email.text.isEmpty) {
                        setDialog('Enter UserId');
                      } else if (_pass.text.isEmpty) {
                        setDialog('Enter Password');
                      } else {
                        bool isInternetConnected =
                            await Constants.checkInternetConnectivity();
                        if (isInternetConnected) {
                          showDialog(
                              context: context,
                              builder: (context) {
                                return const Center(
                                    child: CircularProgressIndicator(
                                  color: Color.fromARGB(255, 164, 149, 120),
                                ));
                              });
                          login(_email.text, _pass.text);
                        } else {
                          setDialog('Check your internetconnection');
                        }
                      }
                    },
                    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: Row(
                        children: [
                          const Text('\t\t'),
                          Image.asset(
                            'assets/images/signin.png',
                            width: 60,
                            height: 60,
                          ), // replace with your image
                          const Expanded(
                            child: Text(
                              '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSIGN IN',
                              style: Constants.buttonsfontStyle,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                const Text('\n\n\n\n\n\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,
          ),
        );
      },
    );
  }
}
