import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:storemonitor/Screens/Constants.dart';
import 'package:storemonitor/Services/RemoteData.dart';

import '../Models/EmployeesGraph.dart';

class DepartmentSearch extends StatefulWidget {
  final String message;
  final List<String>? list;

  const DepartmentSearch(
      {super.key, required this.message, required this.list});

  @override
  _DepartmentSearch createState() => _DepartmentSearch();
}

class Department {
  late int id;
  var name = '';
  var validate = '';

  Department({
    required this.id,
    required this.name,
    required this.validate,
  });
}

class _DepartmentSearch extends State<DepartmentSearch> {
  List<Department>? departmentlist = [];
  var empid = '';
  String? selectedDropdownItem;
  String? departmentItem;
  var isMeeters = '';
  var dynamicText = '';
  List<String>? departmentList = [];
  DateTime _selectedDate = DateTime.now();
  List<String>? storesList;

  @override
  void initState() {
    super.initState();
    _selectedDate = DateTime.now();
    dynamicText =
        'EMPLOYEES STATUS TODAY : ${DateFormat('dd/MM/yyyy').format(_selectedDate)}';
    isMeeters = widget.message;
    departmentList = widget.list;
    loadData();
  }

  List<List<dynamic>> parseJsonList(String jsonString) {
    List<dynamic> decodedList = json.decode(jsonString);
    return decodedList.cast<List<dynamic>>();
  }

  Future<void> loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString("stores_list");
    empid = prefs.getString('empId')!;
    storesList = (json.decode(userId!) as List<dynamic>)
        .map((map) => map['name'] as String)
        .toList();
    int index = storesList!.indexWhere((item) => item.contains(isMeeters));
    setState(() {
      selectedDropdownItem = storesList![index];
      getData(selectedDropdownItem!);
      //departmentItem = departmentList![0];
    });
    // FetchData();
  }

  Future<void> getData(String store) async {
    var response = await RemoteData().getEmployeesStatus(
      store,
    );
    Map<String, dynamic> responseMap = jsonDecode(response!.body);
    //Map<String, dynamic> responseMap = jsonDecode(response);
    final result = EmployeeGraph.fromJson(responseMap);
    setState(() {
      departmentList = result.departmentlist;
      departmentItem = departmentList![0];
    });
    if (kDebugMode) {
      print('store based on :$result.departmentlist');
      print(result.eMPLOYEEGRAPH);
    }
    //return result;
    FetchData(departmentItem);
  }

  Future<void> FetchData(String? dept) async {
    if (await Constants.checkInternetConnectivity()) {
      showDialog(
          context: context,
          builder: (context) {
            return const Center(
                child: CircularProgressIndicator(
              color: Color.fromARGB(255, 173, 57, 230),
            ));
          });
      final respon = await RemoteData()
          .getDepartmentSearch(selectedDropdownItem!, dept!, empid);
      List<dynamic> decodedList = json.decode(respon!.body);
      if (kDebugMode) {
        print(decodedList[0]);
      }
      List<List<dynamic>> parsedList = parseJsonList(respon.body);
      // Now you can access and use the parsedList variable
      departmentlist = [];
      for (List<dynamic> item in parsedList) {
        String role = item[0];
        int id = item[1];
        String name = item[2];
        String availability = item[3];
        departmentlist!
            .add(Department(id: item[1], name: item[2], validate: item[3]));
        if (kDebugMode) {
          print('$role, $id, $name, $availability');
        }
      }
      Navigator.of(context).pop();
      setState(() {
        departmentlist;
      });
    } else {
      Navigator.of(context).pop();
      Constants('Employee Report', 'Please check your internet connection')
          .showAlertDialog(context, false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            'Department Search',
            style: Constants.fontStyle,
          ),
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: Constants.getReturn(),
            ),
          ),
        ),
        body: SingleChildScrollView(
            child: Container(
          margin: const EdgeInsets.all(15.0),
          child: Column(
              //crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                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: selectedDropdownItem,
                      onChanged: (newValue) {
                        setState(() {
                          selectedDropdownItem = newValue;
                          getData(selectedDropdownItem!);
                          //FetchData();
                          departmentlist = [];
                        });
                      },
                      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,
                ),
                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: departmentItem,
                      onChanged: (newValue) {
                        setState(() {
                          departmentItem = newValue;
                          FetchData(departmentItem);
                        });
                      },
                      items: departmentList?.map((item) {
                        return DropdownMenuItem<String>(
                          value: item,
                          child: Text(item),
                        );
                      }).toList(),
                      icon: const Icon(Icons.arrow_drop_down),
                      isExpanded: true,
                    ),
                  ),
                ),
                const SizedBox(
                  height: 15,
                  width: 1,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      dynamicText,
                      textAlign: TextAlign.start,
                      style: Constants.headerlistitems,
                    ),
                  ],
                ),
                const SizedBox(width: 1, height: 15),
                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: Row(
                    children: [
                      SizedBox(
                        width: MediaQuery.of(context).size.width / 4.2,
                        child: const Text(
                          'EMP ID',
                          textAlign: TextAlign.center,
                          style: Constants.whitefontStyle,
                        ),
                      ),
                      const VerticalDivider(
                        width: 1.0,
                        color: Colors.white,
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width / 2.5,
                        child: const Text(
                          'EMP NAME   ',
                          textAlign: TextAlign.center,
                          style: Constants.whitefontStyle,
                        ),
                      ),
                      const VerticalDivider(
                        width: 1.0,
                        color: Colors.white,
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width / 3.8,
                        child: const Text(
                          'InStore Status',
                          textAlign: TextAlign.center,
                          style: Constants.whitefontStyle,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(width: 1, height: 10),
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.55,
                  child: ListView.builder(
                    itemCount: departmentlist?.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 (departmentlist![index].validate == 'Yes') ...[
                                SizedBox(
                                  width:
                                      MediaQuery.of(context).size.width / 4.2,
                                  // height: 40,
                                  child: Text(
                                    departmentlist![index].id.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.5,
                                  child: Text(
                                    departmentlist![index]
                                        .name
                                        .toString()
                                        .toUpperCase(),
                                    style: Constants.unregisterfontStyle,
                                    overflow: TextOverflow.ellipsis,
                                    textAlign: TextAlign.left,
                                    maxLines: 2,
                                  ),
                                ),
                                const VerticalDivider(
                                  width: 1.0,
                                  color: Colors.white,
                                ),
                                SizedBox(
                                  width:
                                      MediaQuery.of(context).size.width / 3.8,
                                  height: double.infinity,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Image.asset('assets/images/green.png',
                                          width: 16, height: 16),
                                    ],
                                  ),
                                )
                              ],

                              if (departmentlist![index].validate == 'No') ...[
                                SizedBox(
                                  width:
                                      MediaQuery.of(context).size.width / 4.2,
                                  // height: 40,
                                  child: Text(
                                    departmentlist![index].id.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.5,
                                  child: Text(
                                    departmentlist![index]
                                        .name
                                        .toString()
                                        .toUpperCase(),
                                    style: Constants.unregisterfontStyle,
                                    overflow: TextOverflow.ellipsis,
                                    textAlign: TextAlign.left,
                                    maxLines: 2,
                                  ),
                                ),
                                const VerticalDivider(
                                  width: 1.0,
                                  color: Colors.white,
                                ),
                                SizedBox(
                                  width:
                                      MediaQuery.of(context).size.width / 3.8,
                                  height: double.infinity,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Image.asset('assets/images/red.png',
                                          width: 16, height: 16),
                                    ],
                                  ),
                                )
                              ],

                              // 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,
                              //   ),
                              // ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ]),
        )));
  }
}
