import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:storemonitor/Services/NetworkApiServices.dart';
import '../Models/EmpReport.dart';
import '../Services/RemoteData.dart';
import 'Constants.dart';

class EmployeeReport extends StatefulWidget {
  final String message;
  const EmployeeReport({super.key, required this.message});

  @override
  State<EmployeeReport> createState() => _EmployeeReport();
}

class _EmployeeReport extends State<EmployeeReport> {
  final NetworkApiServices _apiServices = NetworkApiServices();
  final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  String? storeName;
  List<Data>? empreportlist = [];
  List<Data>? filteredreortlist = [];
  EmpReport? empReport;
  List<String>? storesList;
  String? selectedItem;
  int registered = 0;
  int unregistered = 0;
  int total = 0;

  @override
  void initState() {
    super.initState();
    storeName = widget.message;
    loadData();
    //Constants.showLoader(context);
  }

  Future<void> loadData() async {
    //setState((){
    //  Constants.showLoader(context);
    //});
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString("stores_list");
    if (kDebugMode) {
      print(userId);
    }
    storesList = (json.decode(userId!) as List<dynamic>)
        .map((map) => map['name'] as String)
        .toList();
    if (kDebugMode) {
      print(storesList);
    }
    int index = storesList!.indexWhere((item) => item.contains(storeName!));
    setState(() {
      selectedItem = storesList![index];
      //print(selectedItem);
      getupdateData(selectedItem);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'EMPLOYEE REPORT',
          style: Constants.fontStyle,
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      body: Container(
        margin: const EdgeInsets.all(15.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          //mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // SizedBox(
            //   width: double.infinity,
            //   child: DropdownButton(
            //     isExpanded: true,
            //     value: selectedItem,
            //     onChanged: (value) {
            //       setState(() {
            //         selectedItem = value;
            //         getupdateData(selectedItem);
            //       });
            //     },
            //     items: storesList?.map((value) {
            //       return DropdownMenuItem(
            //         value: value,
            //         child: Text(value),
            //       );
            //     }).toList(),
            //   ),
            // ),

            Container(
              padding: const EdgeInsets.symmetric(horizontal: 10.0),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: DropdownButtonHideUnderline(
                child: DropdownButton<String>(
                  menuMaxHeight: Constants.getDropdownItemHeight(context),
                  value: selectedItem,
                  onChanged: (newValue) {
                    setState(() {
                      selectedItem = newValue;
                      getupdateData(selectedItem);
                    });
                  },
                  items: storesList?.map((item) {
                    return DropdownMenuItem<String>(
                      value: item,
                      child: Text(item),
                    );
                  }).toList(),
                  icon: const Icon(Icons.arrow_drop_down),
                  isExpanded: true,
                ),
              ),
            ),

            const SizedBox(
              height: 10,
              width: 1,
            ),

            const Text('Summary',
                textAlign: TextAlign.left, style: Constants.headerfontStyle),
            const SizedBox(
              width: 0,
              height: 3,
            ),
            Container(
              height: 2,
              width: 40,
              color: const Color.fromARGB(255, 170, 57, 230),
            ),
            const SizedBox(
              height: 15,
              width: 1,
            ),

            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5.0),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.5),
                    spreadRadius: 2,
                    blurRadius: 5,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                children: [
                  Container(
                    margin: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 5.0),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      const Text(
                        '    Registered          :',
                        style: Constants.headerlistitems,
                      ),
                      Text('   $registered', style: Constants.headerlistitems1),
                    ],
                  ),
                  const SizedBox(width: 1, height: 10),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      const Text('    UnRegistered     :',
                          style: Constants.headerlistitems),
                      Text('   $unregistered',
                          style: Constants.headerlistitems1),
                    ],
                  ),
                  const SizedBox(width: 1, height: 10),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      const Text('    Total                     :',
                          style: Constants.headerlistitems),
                      Text('   $total', style: Constants.headerlistitems1),
                    ],
                  ),
                  const SizedBox(width: 1, height: 10),
                ],
              ),
            ),
            const SizedBox(
              height: 15,
              width: 1,
            ),
            const Text('Details',
                textAlign: TextAlign.left, style: Constants.headerfontStyle),
            const SizedBox(
              width: 0,
              height: 3,
            ),
            Container(
              height: 2,
              width: 30,
              color: const Color.fromARGB(255, 170, 57, 230),
            ),
            const SizedBox(
              height: 15,
              width: 1,
            ),
            Container(
              decoration: BoxDecoration(
                // border: Border.all(
                //   color: const Color.fromARGB(255, 123, 50, 254),
                //   style: BorderStyle.solid,
                //   width: 1.0,
                // ),
                color: const Color.fromARGB(255, 35, 22, 66),
                borderRadius: BorderRadius.circular(5.0),
              ),
              //color: Color.fromARGB(255, 123, 50, 254),
              height: 40,
              child: const Row(
                children: [
                  Expanded(
                    child: Text(
                      'EMP ID',
                      textAlign: TextAlign.center,
                      style: Constants.whitefontStyle,
                    ),
                  ),
                  VerticalDivider(
                    width: 1.0,
                    color: Colors.white,
                  ),
                  Expanded(
                    child: Text(
                      'EMP STATUS',
                      textAlign: TextAlign.center,
                      style: Constants.whitefontStyle,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: MediaQuery.of(context).size.height * 0.42,
              child: ListView.builder(
                itemCount: empreportlist?.length,
                itemBuilder: (context, index) {
                  return Padding(
                    padding: const EdgeInsets.all(0.0),
                    child: Container(
                      height: 40,
                      color: index % 2 == 0
                          ? const Color.fromARGB(255, 245, 242, 251)
                          : Colors.white,
                      child: Row(
                        children: [
                          if (empreportlist![index].rEGSTATUS ==
                                  'NOT REGISTERED' ||
                              empreportlist![index].rEGSTATUS ==
                                  'Not Registered') ...[
                            SizedBox(
                              width: MediaQuery.of(context).size.width / 2.2,
                              // height: 40,
                              child: Text(
                                empreportlist![index].eMPId.toString(),
                                style: Constants.reviewbuttonsfontStyle,
                                maxLines: 5,
                                overflow: TextOverflow.ellipsis,
                                textAlign: TextAlign.center,
                              ),
                            ),
                            const VerticalDivider(
                              width: 1.0,
                              color: Colors.white,
                            ),
                            SizedBox(
                              width: MediaQuery.of(context).size.width / 2.2,
                              child: Text(
                                empreportlist![index]
                                    .rEGSTATUS
                                    .toString()
                                    .toUpperCase(),
                                style: Constants.unregisterfontStyle,
                                overflow: TextOverflow.ellipsis,
                                textAlign: TextAlign.center,
                              ),
                            ),
                            // Expanded(
                            //   child: Text(
                            //       empreportlist![index].eMPId.toString(),
                            //       textAlign: TextAlign.center,
                            //       style: Constants.unregisterfontStyle),
                            // ),
                            // VerticalDivider(
                            //   width: 20.0,

                            //   color: Colors.white,
                            // ),
                            // Expanded(
                            //   child: Text(
                            //     empreportlist![index].rEGSTATUS.toString(),
                            //     textAlign: TextAlign.center,
                            //     style: Constants.unregisterfontStyle,
                            //   ),
                            // ),
                          ],
                          if (empreportlist![index].rEGSTATUS ==
                              'Registered') ...[
                            SizedBox(
                              width: MediaQuery.of(context).size.width / 2.2,
                              // height: 40,
                              child: Text(
                                empreportlist![index].eMPId.toString(),
                                style: Constants.reviewbuttonsfontStyle,
                                maxLines: 5,
                                overflow: TextOverflow.ellipsis,
                                textAlign: TextAlign.center,
                              ),
                            ),
                            const VerticalDivider(
                              width: 1.0,
                              color: Colors.white,
                            ),
                            SizedBox(
                              width: MediaQuery.of(context).size.width / 2.2,
                              child: Text(
                                empreportlist![index]
                                    .rEGSTATUS
                                    .toString()
                                    .toUpperCase(),
                                style: Constants.registerfontStyle,
                                overflow: TextOverflow.ellipsis,
                                textAlign: TextAlign.center,
                              ),
                            ),
                            // Expanded(
                            //   child: Text(
                            //     empreportlist![index].eMPId.toString(),
                            //     textAlign: TextAlign.center,
                            //     style: Constants.registerfontStyle,
                            //   ),
                            // ),
                            // Expanded(
                            //   child: Text(
                            //     empreportlist![index].rEGSTATUS.toString(),
                            //     textAlign: TextAlign.center,
                            //     style: Constants.registerfontStyle,
                            //   ),
                            // ),
                          ]
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void showProgressDialog(BuildContext context) {
  // Capture the context in a local variable
  BuildContext dialogContext = context;
  showDialog(
    context: dialogContext,
    builder: (BuildContext context) {
      return const Center(
        child: CircularProgressIndicator(
          color: Color.fromARGB(255, 173, 57, 230),
        ),
      );
    },
  );
}

  Future<void> getupdateData(String? selectedDropdownItem) async {
    if (await Constants.checkInternetConnectivity()) {
      showProgressDialog(context);
      // showDialog(
      //   context: context,
      //    builder: (context) {
      //      return const Center(
      //         child: CircularProgressIndicator(
      //      color: Color.fromARGB(255, 173, 57, 230),
      //     ));
      //  });

      Map<String, dynamic> body = {
        'STORE': selectedDropdownItem!,
      };
      dynamic response = await _apiServices.getPostApiResponse(
          'http://vaman.plutokm.com/regstatusreport', body);
      print("response is ----------->$response");
      final respon = await RemoteData().getUserReport(selectedDropdownItem);
      Map<String, dynamic> responseMap = jsonDecode(respon);
      empReport = EmpReport.fromJson(responseMap);
      empreportlist = empReport!.data;
      //Constants.dismissAlertDialog1(context);
      setState(() {
        total = empreportlist!.length;
        filteredreortlist = empReport!.data
            ?.where((alert) =>
                alert.rEGSTATUS == 'Not Registered' ||
                alert.rEGSTATUS == 'NOT REGISTERED')
            .toList();
        unregistered = filteredreortlist!.length;
        filteredreortlist = empReport!.data
            ?.where((alert) => alert.rEGSTATUS == 'Registered')
            .toList();
        registered = filteredreortlist!.length;
        Navigator.of(context).pop();
      });
    } else {
      Navigator.of(context).pop();
      Constants('Employee Report', 'Please check your internet connection').showAlertDialog(context, false);
    }
  }
}
