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

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

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

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

class _FootFall extends State<FootFall> {
  DateTime _selectedDate = DateTime.now();
  final TextEditingController _dateTime = TextEditingController();
  Future<Foot?>? _futureFoot;
  String? selectedDropdownItem;
  var isMeeters = '';
  List<String>? storesList;

  //var graph  = """<!DOCTYPE html>\n<html>\n<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n\n<body>\n<div id=\"Employees\" style=\"width:50%; max-width:150px; height:50px;\"></div>\n\n<script>\ngoogle.charts.load('current', {'packages':['corechart']});\ngoogle.charts.setOnLoadCallback(drawChart);\n\nfunction drawChart() {\n  var data = google.visualization.arrayToDataTable([\n    ['TIME OF DAY', 'MALE',{ role: 'annotation'},'FEMALE',{ role: 'annotation'},],\n['10-11', 8, '8', 19, '19'], ['11-12', 12, '12', 21, '21'], ['12-13', 18, '18', 13, '13'], ['13-14', 17, '17', 14, '14'], ['14-15', 10, '10', 20, '20'], ['15-16', 8, '8', 21, '21'], ['16-17', 11, '11', 19, '19'], ['17-18', 12, '12', 13, '13'], ['18-19', 13, '13', 16, '16'], ['19-20', 8, '8', 22, '22'], ['20-21', 14, '14', 15, '15'], ['21-22', 7, '7', 17, '17'],\n    \n  ]);\n\n   var options = {\n   \t \n   \t \n     legend:'top',\n     chartArea:{left:30,bottom:50,top:40,width:\"90%\",height:\"50%\"},\n     width:1080,\n     height:800,\n     \n     colors: ['#65d9eb', '#e263eb'],\n     hAxis:{\n          title:'---- Time of Day ----',\n          titleTextStyle:{\n\t\t\t  fontSize: 18,\n              bold: true,},\n          },    \n     vAxis:{\n     \t\t  fontSize: 18,\n              bold:true,\n              title:'Footfall --->',\n              \n              titleTextStyle:{\n\t\t\t  fontSize: 18,\n              bold: true,},},\n     annotations:{\n          alwaysOutside: false,\n                      highContrast: true,  // default is true, but be sure\n                      textStyle: {\n                      \tfontSize: 14,\n                        bold: true\n                      }                 \n\n       },\n\n\n      };\n\n  var chart = new google.visualization.AreaChart(document.getElementById('Employees'));\n    chart.draw(data, options);\n  }\n</script>\n\n</body>\n</html>\n""";]

  @override
  void initState() {
    super.initState();
    isMeeters = widget.message;
    loadData();
    //_selectedDate   = DateTime.now();
    String dateString = widget.selecteddate;
    DateFormat format = DateFormat("yyyy/MM/dd");
    _selectedDate = format.parse(dateString);
    _dateTime.text = DateFormat('yyyy/MM/dd').format(_selectedDate);
    //getData(selectedDropdownItem!);
  }

  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}';
      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}';
      }
      _futureFoot = getData(selectedDropdownItem!,
          '${_selectedDate.year}-$selectedmonth-$selectedday');
    });
  }

  Future<void> loadData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString("storeName");
    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];
      _futureFoot = getData(
        selectedDropdownItem!,
        'none',
      );
    });
  }

  Future<Foot?> getData(String store, String day) async {
    var response = await RemoteData().getFootFall(store, day);
    Map<String, dynamic> responseMap = jsonDecode(response);
    final result = Foot.fromJson(responseMap);
    //print(result);
    return result;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Image.asset(
            "assets/images/back_arrow.png",
            width: 24,
            height: 24,
            color: Colors.white,
          ),
          //color: Colors.white,
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          "FOOT FALL",
          style: Constants.fontStyle,
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
        actions: [
          SizedBox(
            width: 80, // Increase the width value as desired
            height: 80, // Increase the height value as desired
            child: IconButton(
              icon: Image.asset(
                'assets/images/info.png',
              ),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => CheckList(
                      message: selectedDropdownItem!,
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
      body: GestureDetector(
        onForcePressUpdate: (details) {
          if (kDebugMode) {
            print('force press update');
          }
        },
        onHorizontalDragStart: (details) {
          if (kDebugMode) {
            print('force press start');
          }
        },
        onHorizontalDragDown: (details) {},
        child: FutureBuilder<Foot?>(
          future: _futureFoot,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(
                  child: CircularProgressIndicator(
                      color: Color.fromARGB(255, 173, 57, 230)));
            } else if (snapshot.hasData) {
              final foot = snapshot.data!;
              return SingleChildScrollView(
                child: Container(
                  margin: const EdgeInsets.fromLTRB(15, 0, 15, 0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      const SizedBox(
                        width: 10,
                        height: 10,
                      ),
                      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;
                                _futureFoot = getData(
                                  selectedDropdownItem!,
                                  'none',
                                );
                              });
                            },
                            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,
                      ),
                      TextFormField(
                        controller: _dateTime,
                        readOnly: true,
                        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,
                        width: 1,
                      ),
                      const Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text('Store Footfall',
                              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: 10,
                        width: 1,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Container(
                              width: double.infinity,
                              decoration: BoxDecoration(
                                gradient: const LinearGradient(
                                  begin: Alignment.bottomLeft,
                                  end: Alignment.bottomCenter,
                                  colors: [
                                    Color(0xFFfd680e),
                                    Color(0xFFf1245f),
                                    //Color(0xFFC2185B),
                                  ],
                                ),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Column(
                                children: [
                                  Row(
                                    children: [
                                      Column(
                                        children: [
                                          Container(
                                            padding: const EdgeInsets.all(1),
                                            child: Image.asset(
                                              'assets/images/people.png',
                                              width: 50,
                                              height: 50,
                                            ),
                                          ),
                                          Container(
                                            padding: const EdgeInsets.fromLTRB(
                                                10, 10, 0, 20),
                                            child: const Center(
                                              child: Text(
                                                'FOOTFALL',
                                                style:
                                                    Constants.buttonsfontStyle,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                      const SizedBox(
                                        width: 3,
                                        height: 3,
                                      ),
                                      Column(
                                        children: [
                                          Container(
                                            padding: const EdgeInsets.fromLTRB(
                                                10, 0, 0, 20),
                                            child: Image.asset(
                                              'assets/images/footfall_icon.png',
                                              width: 50,
                                              height: 50,
                                            ),
                                          ),
                                          Container(
                                            padding: const EdgeInsets.fromLTRB(
                                                10, 0, 0, 0),
                                            child: Center(
                                              child: Text(
                                                '${foot.fadults! + foot.fkids! + foot.fteens! + foot.madults! + foot.mkids! + foot.mteens!}',
                                                style: Constants
                                                    .footfallheaderfontStyle,
                                                //textAlign: TextAlign.right,
                                              ),
                                            ),
                                          ),
                                          Container(
                                            //padding: const EdgeInsets.all(3),
                                            padding: const EdgeInsets.fromLTRB(
                                                10, 0, 0, 2),
                                            child: const Center(
                                              child: Text(
                                                'Members',
                                                style:
                                                    Constants.footfallfontStyle,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                          const SizedBox(
                            width: 5,
                            height: 1,
                          ),
                          Expanded(
                            child: Container(
                              width: MediaQuery.of(context).size.width / 2.3,
                              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: [
                                  const SizedBox(
                                    width: 1,
                                    height: 7,
                                  ),
                                  const Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: [
                                      SizedBox(
                                        width: 30,
                                        height: 1,
                                      ),
                                      Expanded(
                                        child: Text(
                                          'Adults',
                                          textAlign: TextAlign.center,
                                          style: Constants.listitems,
                                        ),
                                      ),
                                      Expanded(
                                        child: Text(
                                          'Kids',
                                          textAlign: TextAlign.center,
                                          style: Constants.listitems,
                                        ),
                                      ),
                                      Expanded(
                                        child: Text(
                                          'MTens',
                                          textAlign: TextAlign.center,
                                          style: Constants.listitems,
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 8,
                                    width: 2,
                                  ),
                                  const Divider(
                                    height: 2,
                                    thickness: 1,
                                    color: Colors.grey,
                                    indent: 5,
                                    endIndent: 5,
                                  ),
                                  const SizedBox(
                                    height: 5,
                                    width: 2,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: [
                                      Image.asset(
                                        'assets/images/men.png',
                                        width: 25,
                                        height: 25,
                                      ),
                                      const SizedBox(
                                        width: 8,
                                        height: 1,
                                      ),
                                      Expanded(
                                        child: Text(
                                          foot.madults.toString(),
                                          textAlign: TextAlign.center,
                                          style: const TextStyle(
                                              fontWeight: FontWeight.bold,
                                              color: Color.fromARGB(
                                                  255, 63, 123, 173)),
                                        ),
                                      ),
                                      Expanded(
                                        child: Text(
                                          foot.mkids.toString(),
                                          textAlign: TextAlign.center,
                                          style: const TextStyle(
                                            color: Color.fromARGB(
                                                255, 63, 123, 173),
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: Text(
                                          foot.mteens.toString(),
                                          textAlign: TextAlign.center,
                                          style: const TextStyle(
                                            color: Color.fromARGB(
                                                255, 63, 123, 173),
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 10,
                                    width: 2,
                                  ),
                                  const Divider(
                                    height: 5,
                                    thickness: 1,
                                    color: Colors.grey,
                                    indent: 5,
                                    endIndent: 5,
                                  ),
                                  const SizedBox(
                                    height: 8,
                                    width: 2,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: [
                                      Image.asset(
                                        'assets/images/woman.png',
                                        width: 25,
                                        height: 25,
                                      ),
                                      const SizedBox(
                                        width: 5,
                                        height: 1,
                                      ),
                                      Expanded(
                                        child: Text(
                                          foot.fadults.toString(),
                                          textAlign: TextAlign.center,
                                          style: const TextStyle(
                                            color: Color.fromARGB(
                                                255, 235, 25, 42),
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: Text(
                                          foot.fkids.toString(),
                                          textAlign: TextAlign.center,
                                          style: const TextStyle(
                                            color: Color.fromARGB(
                                                255, 235, 25, 42),
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: Text(
                                          foot.fteens.toString(),
                                          textAlign: TextAlign.center,
                                          style: const TextStyle(
                                            color: Color.fromARGB(
                                                255, 235, 25, 42),
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    width: 1,
                                    height: 10,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 16),
                      SizedBox(
                        width: MediaQuery.of(context).size.width,
                        height: 350,
                        child: Container(
                            margin: const EdgeInsets.fromLTRB(0, 10, 0, 10),
                            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(
                              //crossAxisAlignment: CrossAxisAlignment.stretch,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                const SizedBox(
                                  width: 0,
                                  height: 10,
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: const [
                                    Text('Hourly Customer Trend',
                                        textAlign: TextAlign.left,
                                        style: Constants.headerfontStyle),
                                  ]
                                      .map((e) => Padding(
                                          padding:
                                              const EdgeInsets.only(left: 10),
                                          child: e))
                                      .toList(),
                                ),
                                const SizedBox(
                                  width: 0,
                                  height: 3,
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Container(
                                      height: 2,
                                      width: 40,
                                      color: const Color.fromARGB(
                                          255, 170, 57, 230),
                                    ),
                                  ]
                                      .map((e) => Padding(
                                          padding:
                                              const EdgeInsets.only(left: 10),
                                          child: e))
                                      .toList(),
                                ),
                                const SizedBox(
                                  height: 8,
                                ),
                                Center(
                                  child: SizedBox(
                                    width: MediaQuery.of(context).size.width,
                                    height: 280,
                                    child: InAppWebView(
                                      initialData: InAppWebViewInitialData(
                                          data: foot.hourlygraph ?? ""),
                                      initialOptions: InAppWebViewGroupOptions(
                                        crossPlatform: InAppWebViewOptions(
                                            // enable other options if needed
                                            //supportZoom: false,
                                            ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            )),
                      ),
                      SizedBox(
                        width: MediaQuery.of(context).size.width,
                        height: 350,
                        child: Container(
                            //margin: const EdgeInsets.all(5.0),
                            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: [
                                const SizedBox(
                                  width: 0,
                                  height: 10,
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    const Text('Gender Breakup',
                                        textAlign: TextAlign.left,
                                        style: Constants.headerfontStyle)
                                  ]
                                      .map((e) => Padding(
                                          padding:
                                              const EdgeInsets.only(left: 10),
                                          child: e))
                                      .toList(),
                                ),
                                const SizedBox(
                                  width: 0,
                                  height: 3,
                                ),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    Container(
                                      height: 2,
                                      width: 40,
                                      color: const Color.fromARGB(
                                          255, 170, 57, 230),
                                    ),
                                  ]
                                      .map((e) => Padding(
                                          padding:
                                              const EdgeInsets.only(left: 10),
                                          child: e))
                                      .toList(),
                                ),
                                const SizedBox(
                                  height: 8,
                                ),
                                Center(
                                  child: SizedBox(
                                    width: MediaQuery.of(context).size.width,
                                    height: 280,
                                    child: InAppWebView(
                                      initialData: InAppWebViewInitialData(
                                          data: foot.genderhourlygraph ?? ""),
                                      initialOptions: InAppWebViewGroupOptions(
                                        crossPlatform: InAppWebViewOptions(
                                            // enable options that are common to both platforms
                                            //supportZoom: false,
                                            ),
                                        android: AndroidInAppWebViewOptions(
                                          // enable Android-specific options if needed
                                          supportMultipleWindows: true,
                                        ),
                                        ios: IOSInAppWebViewOptions(
                                          // enable iOS-specific options if needed
                                          allowsInlineMediaPlayback: true,
                                          //supportZoom: false,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                Container()
                              ],
                            )),
                      ),
                    ],
                  ),
                ),
              );
            } else if (snapshot.hasError) {
              return Center(child: Text("Error: ${snapshot.error}"));
            } else {
              return const Center(child: Text("No data"));
            }
          },
        ),
      ),
    );
  }

  TextStyle reviewbuttonsfontStyle(Color color) {
    return TextStyle(
      fontFamily: 'Poppins',
      fontSize: 14,
      fontWeight: FontWeight.normal,
      color: color,
    );
  }
}
