import 'dart:convert';
import 'package:flutter/material.dart';
import '../Models/UserResponse.dart';
import '../Services/RemoteData.dart';
import 'Constants.dart';
import 'Home.dart';

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

class _SignUpState extends State<SignUp> {
  final TextEditingController _email = TextEditingController();
  /* try {
      LoginResponse res = await RemoteData()
          .getLoginRequest(email, Constants.hashPassword(pass));
      print(res.data.userAccessToken);
      print(res.data.empId);
      print(res.data.storeName);
      if (res.success == 1) {
        Navigator.pop(context);
        Constants.saveLoginCredentials(
            res.data.empId.toString(),
            res.data.userAccessToken,
            res.data.storeId.toString(),
            res.data.storeName,
            true);
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (context) => const Home()));
        //print(response.token);
        // ignore: use_build_context_synchronously
        //Navigator.push(context, MaterialPageRoute(builder: (context) => UsersList()));
      } else {
        Navigator.pop(context);
        Constants('Login', 'Invalid Credentials').showAlertDialog(context);
      }
    } catch (e) {
      print(e.toString());
    } */
  final TextEditingController _pass = TextEditingController();
  String dropdownValue = 'Option 1';
  bool item = true;
  Future<void> login(String email, String pass) async {
    Constants.showAlertDialog1(context);
    final response = await RemoteData().getLoginRequest(email, pass, '');
    try {
      Map<String, dynamic> responseMap = jsonDecode(response);
      if (responseMap['status'] == 'Success') {
        // Handle success status
        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,
                //'value': item.value,
              };
            }).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(
                        message: 'success',
                      )));
        }
      } else {
        Navigator.pop(context);
        Constants('Login', responseMap['status'].toString())
            .showAlertDialog(context, false);
      }
    } catch (e) {
      Navigator.pop(context);
      Constants('Login', e.toString()).showAlertDialog(context, false);
    }
  }

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Login '),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      resizeToAvoidBottomInset: false,
      body: Container(
        margin: const EdgeInsets.all(15.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // Image.asset(
            //   'assets/images/login_header_image.png',
            //   width: 300,
            //   height: 400,
            // ),
            TextFormField(
              keyboardType: TextInputType.number,
              controller: _email,
              //scrollPadding: const EdgeInsets.all(100.0),
              decoration: const InputDecoration(
                hintText: 'UserId',
                border: OutlineInputBorder(),
              ),
              style: const TextStyle(color: Colors.black),
            ),
            const SizedBox(
              height: 20,
            ),
            TextFormField(
              //focusNode: _focusNode,
              showCursor: false,
              obscureText: true,
              controller: _pass,
              decoration: const InputDecoration(
                hintText: 'Password',
                border: OutlineInputBorder(),
              ),
              style: const TextStyle(color: Colors.black),
            ),
            const SizedBox(
              height: 30,
            ),
            ElevatedButton(
              onPressed: () async {
                if (_email.text.isEmpty && _pass.text.isEmpty) {
                  Constants('Login ', 'Enter email and password')
                      .showAlertDialog(context, false);
                } else if (_email.text.isEmpty) {
                  Constants('Login ', 'Enter email')
                      .showAlertDialog(context, false);
                } else if (_pass.text.isEmpty) {
                  Constants('Login ', 'Enter password')
                      .showAlertDialog(context, false);
                } else {
                  bool isInternetConnected =
                      await Constants.checkInternetConnectivity();
                  if (isInternetConnected) {
                    login(_email.text, _pass.text);
                  } else {
                    Constants('Login', 'Check internet connection')
                        .showAlertDialog(context, false);
                  }
                }
              },
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all<Color>(
                    const Color.fromARGB(255, 170, 57, 230)),
              ),
              child: const SizedBox(
                height: 55,
                child: Center(
                  child: Text('Sign In'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
