import 'dart:convert';
import 'dart:core';
import 'package:flutter/material.dart';
import 'package:http/src/response.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:intl/intl.dart';
import '../Models/Notifications.dart';
import '../Services/RemoteData.dart';
import 'Constants.dart';

class NotificationReport extends StatefulWidget {
  final String message;
  final String selecteddate;

  const NotificationReport(
      {super.key, required this.message, required this.selecteddate});

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

class _NotificationReport extends State<NotificationReport> {
  String? selectedDropdownItem;
  var isMeeters = '';
  List<String>? storesList;
  DateTime _selectedDate1 = DateTime.now();
  final TextEditingController _dateTime1 = TextEditingController();
  Notifications? notificationreport;
  Totals? totals;
  late int total = 0, correct = 0, wrong = 0, accuracy = 0;
  List<Individual>? notificationslist = [];
  @override
  void initState() {
    super.initState();
    if (widget.selecteddate != '') {
      String dateString = widget.selecteddate;
      DateFormat format = DateFormat("yyyy/MM/dd");
      _selectedDate1 = format.parse(dateString);
      _dateTime1.text = DateFormat('yyyy/MM/dd').format(_selectedDate1);
      isMeeters = widget.message;
      loadData();
    }
  }

  Future<void> loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString("stores_list");
    //print(userId);
    storesList = (json.decode(userId!) as List<dynamic>)
        .map((map) => map['name'] as String)
        .toList();
    //print(storesList);
    int index = storesList!.indexWhere((item) => item.contains(isMeeters));

    setState(() {
      selectedDropdownItem = storesList![index];
      //print(selectedDropdownItem);
      getData(selectedDropdownItem!);
    });
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: _selectedDate1,
        firstDate: DateTime(1900),
        lastDate: DateTime.now(),
        builder: (context, child) {
          return Theme(
            data: Theme.of(context).copyWith(
              colorScheme: const ColorScheme.light(
                primary: Color.fromARGB(255, 125, 50, 253), // <-- SEE HERE
                onPrimary: Colors.white, // <-- SEE HERE
                onSurface: Colors.black, // <-- SEE HERE
              ),
              textButtonTheme: TextButtonThemeData(
                style: TextButton.styleFrom(
                  foregroundColor: const Color.fromARGB(
                      255, 125, 50, 253), // button text color
                ),
              ),
            ),
            child: child!,
          );
        });
    if (picked != null && picked != _selectedDate1) {
      setState(() {
        _selectedDate1 = picked;
        _dateTime1.text =
            '${_selectedDate1.year}/${_selectedDate1.month}/${_selectedDate1.day}';
        getData(selectedDropdownItem!);
      });
    }
  }

  void getData(String name) async {
    bool isInternetConnected = await Constants.checkInternetConnectivity();
    if (isInternetConnected) {
      showDialog(
          context: context,
          builder: (context) {
            return const Center(
                child: CircularProgressIndicator(
                    color: Color.fromARGB(255, 173, 57, 230)));
          });
      Response data;
      String selectedmonth = _selectedDate1.month.toString();
      String selectedday = _selectedDate1.day.toString();
      if (_selectedDate1.month < 10) {
        selectedmonth = '0${_selectedDate1.month}';
      }
      if (_selectedDate1.day < 10) {
        selectedday = '0${_selectedDate1.day}';
      }
      data = await RemoteData().getNotificationReport(selectedDropdownItem!,
          '${_selectedDate1.year}-$selectedmonth-$selectedday');
      if (data.statusCode != 200) {
        Constants('NotificationReport', data.statusCode.toString()).showAlertDialog(context, false);
        return;
      }
      Navigator.of(context).pop();
      //print('Data:$data');
      Map<String, dynamic> responseMap = jsonDecode(data.body);
      //responseMap["individual"];
      if (responseMap["individual"]!.isEmpty) {
        //print('is empty data ');
        setState(() {
          total = 0;
          correct = 0;
          wrong = 0;
          accuracy = 0;
          notificationslist = [];
        });
      } else {
        notificationreport = Notifications.fromJson(responseMap);
        setState(() {
          if (notificationreport!.individual.isNotEmpty) {
            notificationslist = notificationreport!.individual;
            totals = notificationreport!.totals;
            total = totals!.total;
            correct = totals!.yes;
            wrong = totals!.total - totals!.yes;
            accuracy = totals!.accuracy;
          } else {
            notificationslist = notificationreport!.individual;
            totals = notificationreport!.totals;
            total = 0;
            correct = 0;
            wrong = 0;
            accuracy = 0;
          }
        });
      }

      if (responseMap['status'] == 'success') {
        //});
      } else {
        // Constants('Review', data.statusCode.toString())
        //     .showAlertDialog(context);
        // Navigator.of(context).pop();
      }
    } else {}
    // } catch (e) {
    //   Constants('Review', e.).showAlertDialog(context);
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'NOTIFICATION REPORT',
          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: [
              // SizedBox(
              //   width: double.infinity,
              //   //height: double.infinity,
              //   child: DropdownButton(
              //     isExpanded: true,
              //     value: selectedDropdownItem,
              //     onChanged: (value) {
              //       setState(() {
              //         selectedDropdownItem = value;
              //         //getupdateData(selectedDropdownItem);
              //       });
              //     },
              //     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: selectedDropdownItem,
                    onChanged: (newValue) {
                      setState(() {
                        selectedDropdownItem = newValue;
                      });
                    },
                    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: 15,
                width: 1,
              ),
              TextFormField(
                controller: _dateTime1,
                //onTap: () => print('Date Picker'),
                decoration: InputDecoration(
                  contentPadding:
                      const EdgeInsets.symmetric(vertical: 15, horizontal: 10),
                  //isDense: true,
                  hintText: 'Select date',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  suffixIcon: IconButton(
                    icon: Image.asset(
                      'assets/images/date_icon.png',
                      width: 24,
                      height: 24,
                    ),
                    onPressed: () => _selectDate(context),
                  ),
                ),
              ),
              const SizedBox(width: 1, height: 15),
              Container(
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [Color(0xFF119887), Color(0xFF2bca83)],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(25),
                ),
                child: ElevatedButton(
                  onPressed: () {
                    getData(selectedDropdownItem!);
                  },
                  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(
                        'SUBMIT',
                        style: Constants.buttonsfontStyle,
                      ))),
                ),
              ),
              const SizedBox(
                width: 0,
                height: 15,
              ),
              const Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text('Summary',
                      textAlign: TextAlign.left,
                      style: Constants.headerfontStyle),
                ],
              ),
              const SizedBox(
                width: 0,
                height: 3,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  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(
                          '    Total Notifications :',
                          style: Constants.headerlistitems,
                        ),
                        Text(
                          '       $total',
                          style: Constants.headerlistitems1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                    const SizedBox(width: 1, height: 10),
                    Container(
                      height: 40,
                      color: const Color.fromARGB(255, 245, 242, 251),
                      padding: const EdgeInsets.all(5.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          const Text('   Correct Notifications :',
                              style: Constants.headerlistitems),
                          Text(
                            '  $correct',
                            style: Constants.headerlistitems1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 1, height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        const Text('    Wrong Notifications :',
                            style: Constants.headerlistitems),
                        Text(
                          '    $wrong',
                          style: Constants.headerlistitems1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                    const SizedBox(width: 1, height: 10),
                    Container(
                      height: 40,
                      color: const Color.fromARGB(255, 245, 242, 251),
                      padding: const EdgeInsets.all(5.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          const Text(
                            '   Accuracy :',
                            style: Constants.headerlistitems,
                            textAlign: TextAlign.center,
                          ),
                          Text(
                            '                           $accuracy%',
                            style: Constants.headerlistitems1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),
                    //const SizedBox(width: 1, height: 10),
                  ],
                ),
              ),
              const SizedBox(
                height: 15,
                width: 1,
              ),
              const Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text('Details',
                      textAlign: TextAlign.left,
                      style: Constants.headerfontStyle),
                ],
              ),
              const SizedBox(
                width: 0,
                height: 3,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                    height: 2,
                    width: 30,
                    color: const Color.fromARGB(255, 170, 57, 230),
                  ),
                ],
              ),
              const SizedBox(
                height: 10,
                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(
                        'REASON',
                        textAlign: TextAlign.center,
                        style: Constants.whitefontStyle,
                      ),
                    ),
                    SizedBox(width: 10),
                    VerticalDivider(
                      width: 1.0,
                      color: Colors.white,
                    ),
                    Expanded(
                      child: Text(
                        'CORRECT',
                        textAlign: TextAlign.center,
                        style: Constants.whitefontStyle,
                      ),
                    ),
                    VerticalDivider(
                      width: 1.0,
                      color: Colors.white,
                    ),
                    Expanded(
                      child: Text(
                        'WRONG',
                        textAlign: TextAlign.center,
                        style: Constants.whitefontStyle,
                      ),
                    ),
                    VerticalDivider(
                      width: 1.0,
                      color: Colors.white,
                    ),
                    Expanded(
                      child: Text(
                        'ACCURACY',
                        textAlign: TextAlign.center,
                        style: Constants.whitefontStyle,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                height: MediaQuery.of(context).size.height * 0.45,
                child: ListView.builder(
                  itemCount: notificationslist?.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: const EdgeInsets.all(2.0),
                      child: Container(
                        height: 60,
                        color: index % 2 == 0
                            ? const Color.fromARGB(255, 245, 242, 251)
                            : Colors.white,
                        child: Row(
                          children: [
                            const SizedBox(
                              width: 5,
                              height: 2,
                            ),
                            SizedBox(
                              width: MediaQuery.of(context).size.width / 4.3,
                              // height: 40,
                              child: Text(
                                Constants.capitalizeFirstLetter(
                                    notificationslist![index]
                                        .reason
                                        .toString()
                                        .toLowerCase()),
                                style: Constants.headerlistitems,
                                maxLines: 5,
                                overflow: TextOverflow.ellipsis,
                                textAlign: TextAlign.left,
                              ),
                            ),
                            const VerticalDivider(
                              width: 1.0,
                              color: Colors.white,
                            ),
                            SizedBox(
                              width: MediaQuery.of(context).size.width / 4.6,
                              child: Text(
                                notificationslist![index].yes.toString(),
                                style: Constants.headerlistitems1,
                                overflow: TextOverflow.ellipsis,
                                textAlign: TextAlign.center,
                              ),
                            ),
                            const VerticalDivider(
                              width: 1.0,
                              color: Colors.white,
                            ),
                            SizedBox(
                              width: MediaQuery.of(context).size.width / 4.5,
                              child: Text(
                                notificationslist![index].no.toString(),
                                style: Constants.headerlistitems1,
                                overflow: TextOverflow.ellipsis,
                                textAlign: TextAlign.center,
                              ),
                            ),
                            const VerticalDivider(
                              width: 1.0,
                              color: Colors.white,
                            ),
                            SizedBox(
                              width: MediaQuery.of(context).size.width / 4.8,
                              child: Text(
                                '${notificationslist![index].accuracy}%',
                                style: Constants.headerlistitems1,
                                overflow: TextOverflow.ellipsis,
                                textAlign: TextAlign.center,
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
