import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.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 {
    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()));
        }
      } else {
        Navigator.pop(context);
        Constants('Login', responseMap['status'].toString())
            .showAlertDialog(context, false);
      }
    } catch (e) {
      Navigator.pop(context);
      Constants('Login', e.toString()).showAlertDialog(context, false);
    }
  }

  Future<void> initializeCamera() async {
    final cameras = await availableCameras();

    // Check if there is a front camera
    final frontCamera = cameras.firstWhere(
      (camera) => camera.lensDirection == CameraLensDirection.front,
    );

    if (frontCamera == null) {
      if (kDebugMode) {
        print('No front camera found');
      }
      return;
    }

    // Initialize the CameraController
    controller = CameraController(
      frontCamera,
      ResolutionPreset.high,
    );

    // Initialize the camera and wait for it to initialize
    await controller!.initialize();
  }

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

  Future<void> takePicture() async {
    if (controller == null || !controller!.value.isInitialized) {
      // Initialize the camera before taking a picture
      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: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/bg.png"),
            fit: BoxFit.cover, // Adjust as needed
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(
              height: 150,
            ),
            Image.asset(
              "assets/images/logo.png",
              width: 250,
              height: 125,
            ),
            const SizedBox(
              height: 20,
            ),
            const Padding(
              padding: EdgeInsets.only(
                  top: 40.0, left: 20.0, right: 20.0, bottom: 0),
              child: SizedBox(
                height: 60,
                child: Text(
                  'LOGIN',
                  style: Constants.buttonsfontStyle,
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(
                  top: 0, left: 20.0, right: 20.0, bottom: 0),
              child: SizedBox(
                height: 50,
                child: TextFormField(
                  cursorColor: const Color.fromARGB(255, 126, 69, 85),
                  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, 224, 226, 228),
                    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: 24,
                          height: 24,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            Padding(
              padding: const EdgeInsets.only(
                  top: 0, left: 20.0, right: 20.0, bottom: 0),
              child: SizedBox(
                height: 50,
                child: TextFormField(
                  cursorColor: const Color.fromARGB(255, 126, 69, 85),
                  obscureText: true,
                  controller: _pass,
                  decoration: InputDecoration(
                    contentPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                    hintText: 'PASSWORD',
                    filled: true,
                    fillColor: const Color.fromARGB(255, 224, 226, 228),
                    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: 24,
                          height: 24,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 80,
            ),
            Padding(
              padding: const EdgeInsets.only(
                  top: 0,
                  left: 20.0,
                  right: 20.0,
                  bottom: 0), // Adjust padding as needed
              child: ElevatedButton(
                onPressed: () async {
                  Constants.saveLoginCredentials(
                      '', _email.text, '', '', '', true);
                  Navigator.pushReplacement(context,
                      MaterialPageRoute(builder: (context) => const Home()));
                },
                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
                  ),
                ),
                child: Row(
                  children: [
                    SizedBox(
                      child: Image.asset(
                        "assets/images/signin.png",
                        width: 42, // Adjust the width as needed
                        height: 42, // Adjust the height as needed
                      ),
                    ),
                    const Expanded(
                      child: Center(
                        child: Text(
                          'SIGN IN',
                          style: Constants.buttonsfontStyle,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
