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';

class WeeklyAudit extends StatefulWidget {
  final String message;

  const WeeklyAudit({super.key, required this.message});
  //const WeeklyAudit({Key? key, required String message}) : super(key: key);

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

class _CheckBoxListState extends State<WeeklyAudit> {
  var mt;
  bool isvisible = false;
  final List<SimpleModel> _items = [];
  String? userid;

  Future<void> getData() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    userid = sharedPreferences.getString('empId')!;
  }

  @override
  void initState() {
    super.initState();
    mt = widget.message;
    String daysOfTheWeek = DateFormat('EEEE').format(DateTime.now());
    if (daysOfTheWeek == 'Monday' || daysOfTheWeek == 'Tuesday') {
      isvisible = true;
    } else {
      isvisible = false;
    }
    getData();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      getWeekAuditData(mt, isvisible);
    });

    // setState(() {
    //   getWeekAuditData(mt, isvisible);
    // });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        //debugShowCheckedModeBanner: false,
        title: const Text(
          'Weekly Audit',
          style: Constants.fontStyle,
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
        bottom: const PreferredSize(
          preferredSize: Size.fromHeight(80),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.fromLTRB(15, 2, 4, 4),
                child: Text(
                  'Alert Reason',
                  style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20),
                child: Text(
                  '     #Notifications\n       (last 7 days)\n',
                  style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 10),
                child: Text(
                  'Audited?',
                  style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.white),
                ),
              ),
            ],
          ),
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.fromLTRB(4, 2, 10, 4),
        children: List<Widget>.generate(_items.length, (index) {
          final SimpleModel item = _items[index];
          final Color backgroundColor = index % 2 == 0
              ? Colors.white
              : const Color.fromARGB(255, 246, 242, 252);

          return Container(
            color: backgroundColor,
            child: CheckboxListTile(
              title: Row(
                children: [
                  Expanded(
                    child: Align(
                      alignment: Alignment.topLeft,
                      child: Text(item.title),
                    ),
                  ),
                  Expanded(
                    child: Align(
                      alignment: Alignment.topLeft,
                      child: Text('\t\t\t\t\t\t\t\t\t ${item.alerts}'),
                    ),
                  ),
                ],
              ),
              value: item.isChecked,
              onChanged: (bool? val) {
                setState(() {
                  item.isChecked = val!;
                  if (_items.isNotEmpty) {
                    int count = 0;
                    for (SimpleModel simpleModel in _items) {
                      if (kDebugMode) {
                        print(simpleModel.isChecked);
                      }
                      if (simpleModel.isChecked) {
                        count++;
                      }
                    }
                    if (kDebugMode) {
                      print(count);
                    }
                  }
                });
              },
              activeColor: const Color.fromARGB(255, 159, 57, 140),
              checkColor: Colors.white,
            ),
          );
        }),
      ),

      // ListView(
      //   padding: const EdgeInsets.fromLTRB(4, 2, 4, 4),
      //   children:
      //   _items
      //       .map(
      //         (SimpleModel item) => CheckboxListTile(
      //           title: Row(
      //             children: [
      //               Expanded(
      //                 child: Align(
      //                   alignment: Alignment.topLeft,
      //                   child: Text(item.title),
      //                 ),
      //               ),
      //               Expanded(
      //                 child: Align(
      //                   alignment: Alignment.topLeft,
      //                   child: Text('\t\t\t ' + item.alerts.toString()),
      //                 ),
      //               ),
      //             ],
      //           ),
      //           value: item.isChecked,
      //           onChanged: (bool? val) {
      //             setState(() {
      //               item.isChecked = val!;
      //               //_items[index].isChecked = val!;
      //               if (_items.isNotEmpty) {
      //                 int count = 0;
      //                 for (SimpleModel simpleModel in _items) {
      //                   if (kDebugMode) {
      //                     print(simpleModel.isChecked);
      //                   }
      //                   if (simpleModel.isChecked) {
      //                     count++;
      //                   }
      //                 }
      //                 if (kDebugMode) {
      //                   print(count);
      //                 }
      //               }
      //             });
      //             // activeColor:
      //             // Color.fromARGB(255, 235, 48, 201);
      //             // checkColor:
      //             // Colors.white;
      //             // controlAffinity:
      //             // ListTileControlAffinity.leading;
      //           },
      //           activeColor: const Color.fromARGB(255, 159, 57, 140),
      //           checkColor: Colors.white,
      //         ),
      //       )
      //       .toList(),
      // ),
      bottomNavigationBar: isvisible
          ? Padding(
              padding: const EdgeInsets.all(20.0),
              child: SizedBox(
                height: 50.0,
                child: ElevatedButton(
                  onPressed: () {
                    if (_items.isNotEmpty) {
                      bool hasTrue =
                          _items.any((data) => data.isChecked == true);
                      if (hasTrue) {
                        List<Map<String, dynamic>>? jsonArray = _items
                            .map((simpleModel) => simpleModel.toJson())
                            .toList();
                        getUpdateData(mt, jsonArray);
                        if (kDebugMode) {
                          print('if condition$jsonArray');
                        }
                      } else {
                        if (kDebugMode) {
                          print('else condition');
                        }
                        Constants('Weekly Audit', 'Check Atleast one checkbox')
                            .showAlertDialog(context, false);
                      }
                    }
                    String daysOfTheWeek =
                        DateFormat('EEEE').format(DateTime.now());
                    if (kDebugMode) {
                      print('Day : $daysOfTheWeek');
                    }
                  },
                  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('SUBMIT'),
                ),
              ),
            )
          : null,
    );
  }

  Future<void> getWeekAuditData(String store, bool active) async {
    showDialog(
        context: context,
        builder: (context) {
          return const Center(
              child: CircularProgressIndicator(
            color: Color.fromARGB(255, 173, 57, 230),
          ));
        });
    print(store);
    print(active);
    final response = await RemoteData().getWeekly(store, active);
    //Map<String, dynamic> responseMap = jsonDecode(response);
    List<Map<String, dynamic>> jsonArray =
        jsonDecode(response).cast<Map<String, dynamic>>();
    for (var jsonMap in jsonArray) {
      String code = jsonMap['AlertReason'];
      String alerts = jsonMap['Notification'];
      if (alerts == 'nan') {
        alerts = '0.0';
      }
      String str = jsonMap['AuditStatus'];
      bool status = (str.toLowerCase() == 'true');
      print(status);
      SimpleModel person = SimpleModel(code, alerts, status);
      _items.add(person);
    }
    Navigator.pop(context);
    setState(() {
      _items;
    });
  }

  void getUpdateData(String store, List<Map<String, dynamic>> jsonArray) async {
    showDialog(
        context: context,
        builder: (context) {
          return const Center(
              child: CircularProgressIndicator(
            color: Color.fromARGB(255, 173, 57, 230),
          ));
        });
    final response =
        await RemoteData().getWeeklyUpdate(userid!, store, jsonArray);
    if (response.isNotEmpty) {
      Map<String, dynamic> responseMap = jsonDecode(response);
      if (kDebugMode) {
        print(responseMap);
      }
      Navigator.pop(context);
    }
  }

  // @override
  // Widget build(BuildContext context) => MaterialApp(
  //       home: Scaffold(
  //         appBar: AppBar(
  //           //debugShowCheckedModeBanner: false,
  //           title: const Text('Checkbox in ListView'),
  //         ),
  //         body: ListView(
  //           padding: const EdgeInsets.all(8),
  //           children: _items
  //               .map(
  //                 (SimpleModel item) => CheckboxListTile(
  //                   title: Text(item.title),
  //                   value: item.isChecked,
  //                   onChanged: (bool? val) {
  //                     setState(() {
  //                       item.isChecked = val!;
  //                       if (_items.length > 0) {
  //                         int count = 0;
  //                         for (SimpleModel simpleModel in _items) {
  //                           print(simpleModel.isChecked);
  //                           if (simpleModel.isChecked) {
  //                             count++;
  //                           }
  //                         }
  //                         print(count);
  //                       }
  //                     });
  //                   },
  //                 ),
  //               )
  //               .toList(),
  //         ),
  //         bottomNavigationBar: isvisible
  //             ? Padding(
  //                 padding: const EdgeInsets.all(20.0),
  //                 child: SizedBox(
  //                   height: 50.0,
  //                   child: ElevatedButton(
  //                     onPressed: () {
  //                       if (_items.isNotEmpty) {
  //                         int count = 0;
  //                         for (SimpleModel simpleModel in _items) {
  //                           if (kDebugMode) {
  //                             print(simpleModel.isChecked);
  //                           }
  //                           if (simpleModel.isChecked) {
  //                             count++;
  //                           }
  //                         }
  //                         if (kDebugMode) {
  //                           print(count);
  //                         }
  //                       }
  //                       String daysOfTheWeek =
  //                           DateFormat('EEEE').format(DateTime.now());
  //                       print('Day : $daysOfTheWeek');
  //                     },
  //                     child: const Text('SUBMIT'),
  //                   ),
  //                 ),
  //               )
  //             : null,
  //       ),
  //     );
}

class SimpleModel {
  String title;
  String alerts;
  bool isChecked;

  SimpleModel(this.title, this.alerts, this.isChecked);

  Map<String, dynamic> toJson() {
    return {
      'Alert reason': title.toString(),
      'Notification': alerts,
      'AuditStatus': isChecked,
    };
  }
}
