import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../Models/CheckReg.dart';
import '../Services/RemoteData.dart';
import 'Constants.dart';

class CheckRegistration extends StatefulWidget {
  String message;
  CheckRegistration({super.key, required this.message});
  @override
  State<CheckRegistration> createState() => _CheckRegistration();
}

class _CheckRegistration extends State<CheckRegistration> {
  final TextEditingController _empId = TextEditingController();
  late final ImagePicker _picker = ImagePicker();
  XFile? image;
  File? newVideoFile;
  var store = '';

  @override
  void initState() {
    super.initState();
    store = widget.message;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'CHECK REGISTRATION',
          style: Constants.fontStyle,
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      resizeToAvoidBottomInset: false,
      body: Container(
        margin: const EdgeInsets.all(15.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            TextField(
              keyboardType: TextInputType.number,
              controller: _empId,
              scrollPadding: const EdgeInsets.all(100.0),
              decoration: const InputDecoration(
                contentPadding:
                    EdgeInsets.symmetric(vertical: 15, horizontal: 10),
                hintText: 'Enter Employee ID',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            Container(
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [Color(0xFF119887), Color(0xFF2bca83)],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(5),
              ),
              child: ElevatedButton(
                onPressed: () {
                  if (_empId.text.isNotEmpty) {
                    //getVideo(_empId.text);
                    getValidReg(_empId.text);
                  } else {
                    Constants('Check Registration', 'Enter emp id')
                        .showAlertDialog(context, false);
                  }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor:
                      Colors.transparent, // make the button transparent
                  elevation: 0, // remove the button's shadow
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                child: const SizedBox(
                  height: 50,
                  child: Center(
                    child: Text(
                      'EMPLOYEE CHECK',
                      style: Constants.buttonsfontStyle,
                    ),
                  ),
                ),
              ),
            ),
            // ElevatedButton(
            //   onPressed: () {
            //     if (_empId.text.isNotEmpty) {
            //       getValidReg(_empId.text);
            //     }
            //   },
            //   style: ButtonStyle(
            //     backgroundColor: MaterialStateProperty.all<Color>(
            //         const Color.fromARGB(255, 170, 57, 230)),
            //   ),
            //   child: const SizedBox(
            //     height: 50,
            //     child: Center(
            //       child: Text('Employee Check'),
            //     ),
            //   ),
            // ),
          ],
        ),
      ),
    );
  }

  void getVideo(String empid) async {
    showDialog(
        context: context,
        builder: (context) {
          return const Center(
              child: CircularProgressIndicator(
            color: Color.fromARGB(255, 173, 57, 230),
          ));
        });
    if (Platform.isAndroid) {
      image = await _picker.pickVideo(
          source: ImageSource.camera, preferredCameraDevice: CameraDevice.rear);
    } else {
      image = await _picker.pickVideo(
          source: ImageSource.camera,
          preferredCameraDevice: CameraDevice.front);
    }

    if (image != null) {
      File file = File(image!.path);
      String filecontents = await fileToString(file);
      String fileName = file.path.split(Platform.pathSeparator).last;

      final response =
          await RemoteData().UploadEmpVideo(file, fileName, empid, store);
      Map<String, dynamic> responseMap = jsonDecode(response);
      //String res = response;
      //bool isEqual = jsonEncode(jsonDecode(response)) == jsonEncode(jsonDecode('{message: VideoUploaded, status: Success}'));

      String message = "$responseMap";

// Extract the status value from the message
      String status = message.split('status:').last.split('}').first.trim();

      print(status);

      if (status == 'Success') {
        Navigator.pop(context);
        file.delete();
        _empId.text == '';
        _empId.clear();
        Constants('Check Registration', 'Registered Sucessfully')
            .showAlertDialog(context, false);
      } else {
        Navigator.pop(context);
        Constants('Check Registration', 'Registation Failed')
            .showAlertDialog(context, false);
        file.delete();
        //Navigator.of(context).pop();
      }

      if (kDebugMode) {
        print(responseMap);
      }
    }
  }

  void getValidReg(String text) async {
    var data = await RemoteData().getValidEmp(text);
    if (data.statusCode != 200) {
      Constants('Review', data.statusCode.toString())
          .showAlertDialog(context, false);
      return;
    }
    Map<String, dynamic> responseMap = jsonDecode(data.body);
    CheckReg checkReg = CheckReg.fromJson(responseMap);
    print('response:$responseMap');
    if (checkReg.status == 'Success') {
      getVideo(text);
    } else {
      Constants('Check Registration', checkReg.status)
          .showAlertDialog(context, false);
    }
  }

  Future<String> fileToString(File file) async {
    try {
      if (await file.exists()) {
        return await file.readAsString();
      }
    } catch (e) {
      print("Error reading file: $e");
    }
    return '';
  }
}
