import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:storemonitor/Models/chartdata.dart';
import 'package:storemonitor/Screens/EmployeeStatus.dart';
import 'package:storemonitor/Screens/IssueVideos.dart';
import 'package:storemonitor/Screens/MyHomePage.dart';
import 'package:storemonitor/Screens/NavBar.dart';
import 'package:intl/intl.dart';
import 'package:storemonitor/Services/RemoteData.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'Constants.dart';
import 'FootFall.dart';
import 'NotificationReport.dart';
import 'Review.dart';
import 'UserRegistration.dart';

class Home extends StatefulWidget {
  final String message;
  const Home({super.key, required this.message});
  //const Home({super.key});
  @override
  _Home createState() => _Home();
}

class _Home extends State<Home> {
  String? selectedDropdownItem;
  String? empId;
  List<String>? namesList;
  late List<GDPData> _chartData;
  DateTime _selectedDate = DateTime.now();
  final TextEditingController _dateTime = TextEditingController();
  bool isAuthenticated = false;
  bool iswarehouserelated = false;

  @override
  void initState() {
    super.initState();
    loadData();
    _chartData = getChartData(0, 0);
    _selectedDate = DateTime.now();
    _dateTime.text = DateFormat('yyyy/MM/dd').format(_selectedDate);
  }

  loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString("stores_list");
    empId = prefs.getString('empId');
    print(empId);
    namesList = (json.decode(userId!) as List<dynamic>)
        .map((map) => map['name'] as String)
        .toList();
    selectedDropdownItem = namesList![0];
    getupdateData(selectedDropdownItem);
    if (prefs.getString('access') == 'ADMIN' ||
        prefs.getString('access') == 'MANAGER') {
      setState(() {
        isAuthenticated = true;
      });
    } else {
      setState(() {
        isAuthenticated = false;
      });
    }

    if (selectedDropdownItem == 'WH KISMATPUR' ||
        selectedDropdownItem == 'WH BANGALORE' ||
        selectedDropdownItem == 'WH VIJAYAWADA' ||
        selectedDropdownItem == 'WH KANCHI') {
      iswarehouserelated = false;
    } else {
      iswarehouserelated = false;
    }

    // if(prefs.getBool('warehouse') == true) {
    //   setState(() {
    //     iswarehouserelated = true;
    //   });
    // } else {
    //   setState(() {
    //     iswarehouserelated = false;
    //   });
    // }
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: _selectedDate,
        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),
                onPrimary: Colors.white,
                onSurface: Colors.black,
              ),
              textButtonTheme: TextButtonThemeData(
                style: TextButton.styleFrom(
                  foregroundColor: const Color.fromARGB(255, 125, 50, 253),
                ),
              ),
            ),
            child: child!,
          );
        });
    setState(() {
      _selectedDate = picked!;
      _dateTime.text =
          '${_selectedDate.year}/${_selectedDate.month}/${_selectedDate.day}';
      getupdateData(selectedDropdownItem);
    });
  }

  //9866438056

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: NavBar(
        message: selectedDropdownItem.toString(),
      ),
      appBar: AppBar(
        title: const Text(
          'STORE MONITOR',
          style: Constants.fontStyle,
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: GestureDetector(
          onForcePressUpdate: (details) {
            print('force press update');
          },
          onHorizontalDragStart: (details) {
            print('force press start');
          },
          onHorizontalDragDown: (details) {
            print('force press down');
            //Navigator.pop(context);
          },

          // onHorizontalDragUpdate: (dragDetail) {
          //   print('Testing');
          //   if (dragDetail.delta.direction > 0) {
          //     Navigator.pop(context);
          //     print('Hitted =====>');
          //   }
          // },

          child: Container(
            margin: const EdgeInsets.all(12.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              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;
                          getupdateData(selectedDropdownItem);
                          if (selectedDropdownItem == 'WH KISMATPUR' ||
                              selectedDropdownItem == 'WH BANGALORE' ||
                              selectedDropdownItem == 'WH VIJAYAWADA' ||
                              selectedDropdownItem == 'WH KANCHI') {
                            iswarehouserelated = true;
                          } else {
                            iswarehouserelated = false;
                          }
                        });
                      },
                      items: namesList?.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: _dateTime,
                  onTap: () {},
                  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(height: 10),
                const Text('AI Powered Alerts',
                    textAlign: TextAlign.right,
                    style: Constants.headerfontStyle),
                const SizedBox(
                  width: 0,
                  height: 5,
                ),
                Container(
                  height: 2,
                  width: 60,
                  color: const Color.fromARGB(255, 170, 57, 243),
                ),
                const SizedBox(
                  height: 15,
                  width: 1,
                ),
                Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.5),
                        spreadRadius: 2,
                        blurRadius: 5,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: SfCircularChart(
                    //backgroundColor: Colors.white,
                    margin: const EdgeInsets.all(10),
                    legend: Legend(
                      isVisible: true,
                      position: LegendPosition.top,
                    ),
                    tooltipBehavior: TooltipBehavior(
                      enable: true,
                      textStyle:
                          const TextStyle(fontSize: 22.0, color: Colors.white),
                    ),

                    palette: const <Color>[
                      Color.fromARGB(255, 4, 145, 74),
                      Color.fromARGB(255, 241, 92, 34)
                    ],
                    series: <CircularSeries>[
                      PieSeries<GDPData, String>(
                        dataSource: _chartData,
                        xValueMapper: (GDPData data, _) => data.continent,
                        yValueMapper: (GDPData data, _) => data.gdp,
                        dataLabelSettings: const DataLabelSettings(
                          isVisible: true,
                          textStyle:
                              TextStyle(fontSize: 32.0, color: Colors.white),
                        ),
                        enableTooltip: true,
                        radius: '100%',
                        explode: true,
                      ),
                    ],
                    onDataLabelRender: (DataLabelRenderArgs args) {
                      args.textStyle = args.textStyle.copyWith(
                        fontSize: 18, // Set the desired font size
                        fontFamily: 'Poppins',
                        fontWeight: FontWeight.bold,
                      ); // Set the desired font size
                    },
                  ),
                ),
                const SizedBox(
                  height: 15,
                  width: 1,
                ),
                Row(mainAxisAlignment: MainAxisAlignment.start, children: [
                  Expanded(
                    child: SizedBox(
                      width: MediaQuery.of(context).size.width * 0.448,
                      child: GestureDetector(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => Review(
                                      message: selectedDropdownItem.toString(),
                                      selecteddate:
                                          '${_selectedDate.year}/${_selectedDate.month}/${_selectedDate.day}',
                                    )),
                          );
                        },
                        child: Container(
                          margin: const EdgeInsets.only(
                              left: 0, top: 0, right: 2, bottom: 0),
                          width: MediaQuery.of(context).size.width * 0.44,
                          height: MediaQuery.of(context).size.width * 0.22,
                          padding: const EdgeInsets.all(5),
                          decoration: BoxDecoration(
                            gradient: const LinearGradient(
                              begin: Alignment.bottomLeft,
                              end: Alignment.bottomRight,
                              colors: [
                                Color(0xFFFF1412),
                                //Color(0xFFC2185B),
                                Color(0xFFFF714C),
                              ],
                            ),
                            borderRadius: BorderRadius.circular(7),
                          ),
                          child: Row(
                            children: [
                              Image.asset(
                                'assets/images/review.png',
                              ), // replace with your image
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                  const VerticalDivider(width: 10.0),
                  Expanded(
                    child: Container(
                      margin: const EdgeInsets.only(
                          left: 0, top: 0, right: 0, bottom: 0),
                      width: MediaQuery.of(context).size.width * 0.44,
                      child: Visibility(
                        //visible: isAuthenticated,
                        child: GestureDetector(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => EmployeeStatus(
                                      message:
                                          selectedDropdownItem.toString())),
                            );
                          },
                          child: Container(
                            width: MediaQuery.of(context).size.width * 0.44,
                            height: MediaQuery.of(context).size.width * 0.22,
                            padding: const EdgeInsets.all(5),
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(
                                begin: Alignment.bottomLeft,
                                end: Alignment.bottomCenter,
                                colors: [
                                  Color(0xFFc89181),
                                  Color(0xFFf5b97e),
                                  //Color(0xFFC2185B),
                                ],
                              ),
                              borderRadius: BorderRadius.circular(7),
                            ),
                            child: Row(
                              children: [
                                Image.asset(
                                  'assets/images/emp.png',
                                  // width: 145,
                                  // height: 160,
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ]),
                const SizedBox(
                  height: 10,
                  width: 1,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        margin: const EdgeInsets.only(
                            left: 0, top: 0, right: 2, bottom: 0),
                        width: MediaQuery.of(context).size.width * 0.44,
                        child: Visibility(
                          //visible: isAuthenticated,
                          child: GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => NotificationReport(
                                          message:
                                              selectedDropdownItem.toString(),
                                          selecteddate:
                                              '${_selectedDate.year}/${_selectedDate.month}/${_selectedDate.day}',
                                        )),
                              );
                            },
                            child: Container(
                              width: MediaQuery.of(context).size.width * 0.44,
                              height: MediaQuery.of(context).size.width * 0.22,
                              padding: const EdgeInsets.all(5),
                              decoration: BoxDecoration(
                                gradient: const LinearGradient(
                                  begin: Alignment.bottomLeft,
                                  end: Alignment.bottomCenter,
                                  colors: [
                                    Color(0xFF6e87d6),
                                    //Color(0xFFC2185B),
                                    Color(0xFF48c5ef),
                                  ],
                                ),
                                borderRadius: BorderRadius.circular(7),
                              ),
                              child: Row(
                                children: [
                                  Image.asset(
                                    'assets/images/accuracy.png',
                                    // width: 145,
                                    // height: 160,
                                  ),
                                  // replace with your image
                                  // const SizedBox(
                                  //     width:
                                  //         10), // add some space between the image and the text
                                  // const Expanded(
                                  //   child: Text(
                                  //     'Accuracy',
                                  //     overflow: TextOverflow.ellipsis,
                                  //     style: Constants.buttonsfontStyle,
                                  //     textAlign: TextAlign.center,
                                  //   ),
                                  // ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    const VerticalDivider(width: 10.0),
                    Expanded(
                      child: Container(
                        margin: const EdgeInsets.only(
                            left: 0, top: 0, right: 0, bottom: 0),
                        width: MediaQuery.of(context).size.width * 0.44,
                        child: Visibility(
                          //visible: isAuthenticated,
                          child: GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => FootFall(
                                          message:
                                              selectedDropdownItem.toString(),
                                          selecteddate:
                                              '${_selectedDate.year}/${_selectedDate.month}/${_selectedDate.day}',
                                        )),
                              );
                            },
                            child: Container(
                              width: MediaQuery.of(context).size.width * 0.44,
                              height: MediaQuery.of(context).size.width * 0.22,
                              padding: const EdgeInsets.all(3),
                              decoration: BoxDecoration(
                                gradient: const LinearGradient(
                                  begin: Alignment.bottomLeft,
                                  end: Alignment.bottomCenter,
                                  colors: [
                                    Color(0xFF872b8e),
                                    //Color(0xFFC2185B),
                                    Color(0xFFcf2b72),
                                  ],
                                ),
                                borderRadius: BorderRadius.circular(7),
                              ),
                              child: Row(
                                children: [
                                  Image.asset(
                                    'assets/images/footfall.png',
                                    // width: 145,
                                    // height: 160,
                                  ),
                                  // replace with your image
                                  // const SizedBox(
                                  //     width:
                                  //         10), // add some space between the image and the text
                                  // const Expanded(
                                  //   child: Text(
                                  //     'Foot Fall',
                                  //     overflow: TextOverflow.ellipsis,
                                  //     style: Constants.buttonsfontStyle,
                                  //     textAlign: TextAlign.center,
                                  //   ),
                                  // ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 10,
                  width: 1,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        margin: const EdgeInsets.only(
                            left: 0, top: 0, right: 0, bottom: 0),
                        width: MediaQuery.of(context).size.width * 0.44,
                        child: GestureDetector(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => UserRegistration(
                                      message:
                                          selectedDropdownItem.toString())),
                            );
                          },
                          child: Container(
                            width: MediaQuery.of(context).size.width * 0.44,
                            height: MediaQuery.of(context).size.width * 0.22,
                            padding: const EdgeInsets.all(5),
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(
                                begin: Alignment.bottomLeft,
                                end: Alignment.bottomRight,
                                colors: [
                                  Color(0xFF6a706f),
                                  //Color(0xFFC2185B),
                                  Color(0xFF91b3b1),
                                ],
                              ),
                              borderRadius: BorderRadius.circular(7),
                            ),
                            child: Row(
                              children: [
                                Image.asset(
                                  'assets/images/emp_registration.png',
                                  // width: 145,
                                  // height: 160,
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                    const VerticalDivider(width: 10.0),
                    Expanded(
                      child: Container(
                        margin: const EdgeInsets.only(
                            left: 0, top: 0, right: 0, bottom: 0),
                        width: MediaQuery.of(context).size.width * 0.44,
                        child: Visibility(
                          //visible: iswarehouserelated,
                          child: GestureDetector(
                            onTap: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => IssueVideos(
                                          message:
                                              selectedDropdownItem.toString(),
                                        )),
                              );

                              // Navigator.push(
                              //   context,
                              //   MaterialPageRoute(
                              //       builder: (context) => CameraGridItems()),
                              // );
                            },
                            child: Container(
                              width: MediaQuery.of(context).size.width * 0.44,
                              height: MediaQuery.of(context).size.width * 0.22,
                              padding: const EdgeInsets.all(3),
                              decoration: BoxDecoration(
                                gradient: const LinearGradient(
                                  begin: Alignment.bottomLeft,
                                  end: Alignment.bottomRight,
                                  colors: [
                                    Color(0xFF525589),
                                    Color(0xFFaca8e0),
                                    //Color(0xFFC2185B),
                                  ],
                                ),
                                borderRadius: BorderRadius.circular(7),
                              ),
                              child: Row(
                                children: [
                                  Image.asset(
                                    'assets/images/videos.png',
                                    // width: 145,
                                    // height: 160,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 10,
                  width: 1,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Container(
                        margin: const EdgeInsets.only(
                            left: 0, top: 0, right: 0, bottom: 0),
                        width: MediaQuery.of(context).size.width * 0.44,
                        child: GestureDetector(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => MyHomePage(
                                          message:
                                              'https://vaman.plutokm.com/sa_mob_report/$empId',
                                        )));
                          },
                          child: Container(
                            width: MediaQuery.of(context).size.width * 0.44,
                            height: MediaQuery.of(context).size.width * 0.22,
                            padding: const EdgeInsets.all(5),
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(
                                begin: Alignment.bottomLeft,
                                end: Alignment.bottomRight,
                                colors: [
                                  Color(0xFF2c3e50),
                                  //Color(0xFFC2185B),
                                  Color(0xFF5aacba),
                                ],
                              ),
                              borderRadius: BorderRadius.circular(7),
                            ),
                            child: Row(
                              children: [
                                Image.asset(
                                  'assets/images/weekly_report.png',
                                  // width: 145,
                                  // height: 160,
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                    const VerticalDivider(width: 10.0),
                    Expanded(
                      child: Container(
                        margin: const EdgeInsets.only(
                            left: 0, top: 0, right: 0, bottom: 0),
                        width: MediaQuery.of(context).size.width * 0.44,
                        child: GestureDetector(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => UserRegistration(
                                      message:
                                          selectedDropdownItem.toString())),
                            );
                          },
                          child: Container(
                            width: MediaQuery.of(context).size.width * 0.44,
                            height: MediaQuery.of(context).size.width * 0.22,
                            padding: const EdgeInsets.all(5),
                            // decoration: BoxDecoration(
                            //   gradient: const LinearGradient(
                            //     begin: Alignment.bottomLeft,
                            //     end: Alignment.bottomRight,
                            //     colors: [
                            //       // Color(0xFF6a706f),
                            //       // //Color(0xFFC2185B),
                            //       // Color(0xFF91b3b1),
                            //     ],
                            //   ),
                            //   borderRadius: BorderRadius.circular(7),
                            // ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  List<GDPData> getChartData(int res, int un) {
    final List<GDPData> chartData = [
      GDPData('Resolved', res),
      GDPData('UnResolved', un),
    ];
    return chartData;
  }

  Future<void> getupdateData(String? selectedDropdownItem) async {
    showDialog(
        context: context,
        builder: (context) {
          return const Center(
              child: CircularProgressIndicator(
            color: Color.fromARGB(255, 173, 57, 230),
          ));
        });
    String selectedmonth = _selectedDate.month.toString();
    String selectedday = _selectedDate.day.toString();
    if (_selectedDate.month < 10) {
      selectedmonth = '0${_selectedDate.month}';
    }
    if (_selectedDate.day < 10) {
      selectedday = '0${_selectedDate.day}';
    }
    final String respon;
    if (Platform.isAndroid) {
      //Response data;
      respon = await RemoteData().geAlertSummary(selectedDropdownItem!,
          '${_selectedDate.year}-$selectedmonth-$selectedday', 'Android');
    } else {
      respon = await RemoteData().geAlertSummary(selectedDropdownItem!,
          '${_selectedDate.year}-$selectedmonth-$selectedday', 'Ios');
    }
    if (kDebugMode) {
      print(respon);
    }
    Navigator.of(context).pop();

    final chart = chartdataFromJson(respon);
    setState(() {
      _chartData =
          getChartData(int.parse(chart.resolved), int.parse(chart.unresolved));
    });
  }
}

class MyData {
  String? store;
}

class GDPData {
  GDPData(this.continent, this.gdp);
  final String continent;
  final int gdp;
}
