import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:gif_view/gif_view.dart';
import '../Models/UserResponse.dart';
import '../Services/RemoteData.dart';
import 'Constants.dart';
import 'Home.dart';

class LoginPage extends StatelessWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      //resizeToAvoidBottomPadding: false,
      body: SingleChildScrollView(
        child: Container(
          height: MediaQuery.of(context).size.height,
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Color.fromARGB(255, 125, 50, 253),
                Color.fromARGB(255, 125, 50, 253),
                // Color.fromARGB(255, 157, 55, 237)
              ],
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const SizedBox(height: 30),
              //  GifImage(
              //   image: AssetImage('assets/sample.gif'), // Replace with your actual GIF image path
              //  ),
              GifView.asset(
                'assets/images/login.gif',
                height: 350,
                width: 350,
                frameRate: 30, // default is 15 FPS
              ),
              // Image.asset(
              //   'assets/images/login_header_image.png',
              //   height: 350,
              //   width: 350,
              // ),
              const SizedBox(height: 30),
              const LoginForm(),
            ],
          ),
        ),
      ),
    );
  }
}

class LoginForm extends StatefulWidget {
  const LoginForm({Key? key}) : super(key: key);
  @override
  LoginFormState createState() => LoginFormState();
}

class LoginFormState extends State<LoginForm> {
  final TextEditingController _email = TextEditingController();
  final TextEditingController _pass = TextEditingController();
  late FirebaseMessaging messaging;
  String? deviceId = '';
  //late FlutterGifController controller1;

  @override
  void initState() {
    super.initState();
    //controller1 = FlutterGifController(vsync: context);
    if (Platform.isAndroid) {
      messaging = FirebaseMessaging.instance;
      messaging.getToken().then((value) {
        if (kDebugMode) {
          print('Token Value :$value');
        }
        deviceId = value;
      });
    }
  }

  Future<void> login(String email, String pass) async {
    //Constants.showAlertDialog1(context);
    //final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

    // String? deviceId;
    // if (Platform.isAndroid) {
    //   const androidId = AndroidId();
    //   deviceId = await androidId.getId();
    // } else if (Platform.isIOS) {
    //   final iosInfo = await deviceInfo.iosInfo;
    //   deviceId = iosInfo.identifierForVendor;
    // }
    final response = await RemoteData().getLoginRequest(
      email,
      pass,
      deviceId!,
    );
    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,
              };
            }).toList();
          }
          String jsonStr = json.encode(normalArray);
          Navigator.pop(context);
          //print(userResponse.level);
          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
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 20),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.5),
            spreadRadius: 5,
            blurRadius: 7,
            offset: const Offset(0, 3), // changes position of shadow
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            'USER LOGIN',
            style: Constants.fontStyle,
          ),
          const SizedBox(
            height: 20,
            width: 10,
          ),
          SizedBox(
            height: 50,
            child: TextFormField(
              cursorColor: const Color.fromARGB(255, 125, 50, 253),
              style: Constants.fontStyle,
              controller: _email,
              //obscureText: true,
              decoration: InputDecoration(
                labelText: ' User',
                labelStyle: const TextStyle(
                  //fontWeight: FontWeight.bold,
                  fontSize: 16,
                  color: Colors.grey,
                  letterSpacing: 1,
                ),
                // Align the label text to the left by specifying the padding
                //contentPadding: const EdgeInsets.all(15.0),
                // Align the suffix icon to the right by wrapping it in a Row

                suffix: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Opacity(
                      opacity: 0.5, // Set the desired opacity value (0.0 - 1.0)
                      child: IconButton(
                        icon: const Icon(Icons.person),
                        onPressed: () {},
                      ),
                    )
                  ],
                ),

                enabledBorder: const OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.grey, // Set the desired color here
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(
                    color: Color.fromARGB(
                        255, 125, 50, 253), // Set the desired color here
                  ),
                  borderRadius: BorderRadius.circular(5.0),
                ),
              ),
            ),
          ),
          const SizedBox(height: 15),
          SizedBox(
            height: 50,
            child: TextFormField(
              cursorColor: const Color.fromARGB(255, 125, 50, 253),
              style: Constants.fontStyle,
              controller: _pass,
              obscureText: true,
              decoration: InputDecoration(
                labelText: 'Password',
                labelStyle: const TextStyle(
                  //fontWeight: FontWeight.bold,
                  fontSize: 16,
                  color: Colors.grey,
                  letterSpacing: 0.5,
                ),
                // Align the label text to the left by specifying the padding
                //contentPadding: const EdgeInsets.fromLTRB(4, 10, 0, 10),
                // Align the suffix icon to the right by wrapping it in a Row
                suffix: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Opacity(
                      opacity: 0.5, // Set the desired opacity value (0.0 - 1.0)
                      child: IconButton(
                        icon: const Icon(Icons.lock),
                        onPressed: () {},
                      ),
                    )
                  ],
                ),
                enabledBorder: const OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.grey, // Set the desired color here
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(
                    color: Color.fromARGB(
                        255, 125, 50, 253), // Set the desired color here
                  ),
                  borderRadius: BorderRadius.circular(5.0),
                ),
                // border: OutlineInputBorder(
                //   borderRadius: BorderRadius.circular(5.0),
                // ),
              ),
            ),
          ),
          const SizedBox(height: 15),
          SizedBox(
            width: double.infinity,
            height: 50,
            child: ElevatedButton(
              onPressed: () async {
                if (_email.text.isEmpty && _pass.text.isEmpty) {
                  Constants('Login ', 'Enter userId and password')
                      .showAlertDialog(context, false);
                } else if (_email.text.isEmpty) {
                  Constants('Login ', 'Enter userId')
                      .showAlertDialog(context, false);
                } else if (_pass.text.isEmpty) {
                  Constants('Login ', 'Enter password')
                      .showAlertDialog(context, false);
                } else {
                  bool isInternetConnected =
                      await Constants.checkInternetConnectivity();
                  if (isInternetConnected) {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return const Center(
                              child: CircularProgressIndicator(
                            color: Color.fromARGB(255, 173, 57, 230),
                          ));
                        });
                    login(_email.text, _pass.text);
                  } else {
                    Constants.dialogMessage(context, 'Login', 'Check your internetconnection');
                  }
                }
              },
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all<Color>(
                      const Color.fromARGB(255, 62, 43, 75)),
                  shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                      RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5.0),
                    //side: BorderSide(color: Colors.red)
                  ))),
              child: const Text(
                'LOGIN',
                style: Constants.fontStyle,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
