import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.dart';
import 'package:fluttericon/linecons_icons.dart';
import 'package:intl/intl.dart';
import 'package:peasmartcare/blocs/electricity_statistic/electricity_statistic_bloc.dart';
import 'package:peasmartcare/blocs/electricity_statistic_pea_number_list/electricity_statistic_pea_number_list_bloc.dart';
import 'package:peasmartcare/blocs/electricity_statistic_type_list/electricity_statistic_type_list_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/customer_info.dart';
import 'package:peasmartcare/components/header_content.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/components/pea_bottom_bar.dart';
import 'package:peasmartcare/components/profile_avatar.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:peasmartcare/models/electricity_statistic_model.dart';
import 'package:peasmartcare/models/electricity_statistic_pea_number_model.dart';
import 'package:peasmartcare/models/electricity_statistic_type_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:peasmartcare/widgets/error_box.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/not_found_box.dart';

class ElectricityStatisticPage extends StatefulWidget {
  @override
  _ElectricityStatisticPageState createState() => _ElectricityStatisticPageState();
}

class _ElectricityStatisticPageState extends State<ElectricityStatisticPage> {
  final _formKey = GlobalKey<FormState>();
  final dateFormat = DateFormat("dd/MM/yyyy");
  final numberFormat = NumberFormat("00");
  DateTime _startDateVal = DateTime(DateTime.now().year, 1, 1); //DateTime.now();
  DateTime _endDateVal = DateTime(DateTime.now().year, 12, 31); //DateTime.now();
  final bool animate = true;
  String _typeDropdownValue;
  String _typeDropdownName;
  String _peaNumberDropdownValue;
  String _peaNumberDropdownName;

  @override
  void initState() {
    context.read<ElectricityStatisticBloc>().add(ElectricityStatisticClearData());
    context.read<ElectricityStatisticTypeListBloc>().add(ElectricityStatisticTypeListGetList());
    context.read<ElectricityStatisticPeaNumberListBloc>().add(ElectricityStatisticPeaNumberListGetList());
    _peaNumberDropdownValue = null;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: PEAAppBar(
        title: "สถิติการใช้ไฟฟ้า",
        actions: <Widget>[
          ProfileAvatar(),
        ],
      ),
      bottomNavigationBar: PEABottomBar(),
      body: BodyLayout(
        top: deviceSize.width > 500 ? 175 : 205,
        header: CustomerInfo(),
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                HeaderContent(
                  title: "สถิติการใช้ไฟฟ้า",
                  icon: ImageAsset.electricityStatisticImg,
                ),
                _body(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _body() {
    Size deviceSize = MediaQuery.of(context).size;
    return Form(
      key: _formKey,
      child: Positioned(
        child: Padding(
          padding: const EdgeInsets.only(top: 70),
          child: Center(
            child: Column(
              children: <Widget>[
                Container(
                  width: deviceSize.width - 40,
                  // height: 205,
                  child: Card(
                    elevation: 3,
                    child: Container(
                      padding: const EdgeInsets.all(15),
                      child: Column(
                        children: <Widget>[
                          BlocListener<ElectricityStatisticPeaNumberListBloc, ElectricityStatisticPeaNumberListState>(
                            listener: (context, state) {
                              if (state is ElectricityStatisticPeaNumberListErrorUnauthorized) {
                                Navigator.of(context).popUntil((route) => route.isFirst);
                                Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(builder: (context) => LogoutPage()),
                                );
                              }
                            },
                            child: BlocBuilder<ElectricityStatisticPeaNumberListBloc, ElectricityStatisticPeaNumberListState>(builder: (context, state) {
                              if (state is ElectricityStatisticPeaNumberListLoading) {
                                return DropdownButtonFormField<dynamic>(
                                  hint: Text(
                                    "รหัสเครื่องวัดไฟฟ้า",
                                    style: TextStyle(color: Color(AppData.greyColor)),
                                  ),
                                  icon: Icon(Icons.keyboard_arrow_down),
                                  isExpanded: true,
                                  onChanged: (val) {},
                                  items: [],
                                );
                              } else if (state is ElectricityStatisticPeaNumberListLoaded) {
                                List<ElectricityStatisticPeaNumberModel> typeList = state.result;

                                return DropdownButtonFormField<dynamic>(
                                  validator: (value) {
                                    if (value == null || value.isEmpty) {
                                      return "กรุณาเลือกรหัสเครื่องวัดไฟฟ้า";
                                    }
                                    return null;
                                  },
                                  value: _peaNumberDropdownValue,
                                  hint: Text(
                                    "รหัสเครื่องวัดไฟฟ้า",
                                    style: TextStyle(color: Color(AppData.greyColor)),
                                  ),
                                  icon: Icon(Icons.keyboard_arrow_down),
                                  isExpanded: true,
                                  onChanged: (val) {
                                    setState(() {
                                      _peaNumberDropdownValue = val;
                                    });
                                  },
                                  items: typeList.map<DropdownMenuItem<dynamic>>(
                                    (value) {
                                      return DropdownMenuItem<dynamic>(
                                        value: value.peaNumber ?? '',
                                        child: RichText(
                                          text: TextSpan(
                                            style: DefaultTextStyle.of(context).style,
                                            children: <TextSpan>[
                                              TextSpan(
                                                text: "เครื่องวัด : ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: "${value.peaNumber}  ${value.address}"),
                                            ],
                                          ),
                                        ),
                                        // child: Column(
                                        //   children: [
                                        //     Text(
                                        //       "เครื่องวัด : ",
                                        //       style: TextStyle(fontWeight: FontWeight.bold),
                                        //     ),
                                        //     Text("${value.peaNumber}  ${value.address}"),
                                        //   ],
                                        // ),
                                      );
                                    },
                                  ).toList(),
                                  selectedItemBuilder: (BuildContext context) {
                                    return typeList.map<Widget>((item) {
                                      return Text(
                                        "${(item.peaNumber ?? '')} : ${(item.address ?? '')}",
                                        overflow: TextOverflow.ellipsis,
                                      );
                                    }).toList();
                                  },
                                );
                              }

                              return EmptyBox();
                            }),
                          ),
                          SizedBox(height: 20),
                          BlocListener<ElectricityStatisticTypeListBloc, ElectricityStatisticTypeListState>(
                            listener: (context, state) {
                              if (state is ElectricityStatisticTypeListErrorUnauthorized) {
                                Navigator.of(context).popUntil((route) => route.isFirst);
                                Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(builder: (context) => LogoutPage()),
                                );
                              }
                            },
                            child: BlocBuilder<ElectricityStatisticTypeListBloc, ElectricityStatisticTypeListState>(builder: (context, state) {
                              if (state is ElectricityStatisticTypeListLoading) {
                                return DropdownButtonFormField<dynamic>(
                                  hint: Text(
                                    "ประเภทสถิติ",
                                    style: TextStyle(color: Color(AppData.greyColor)),
                                  ),
                                  icon: Icon(Icons.keyboard_arrow_down),
                                  isExpanded: true,
                                  onChanged: (val) {},
                                  items: [],
                                );
                              } else if (state is ElectricityStatisticTypeListLoaded) {
                                List<ElectricityStatisticTypeModel> typeList = state.result;

                                return DropdownButtonFormField<dynamic>(
                                  validator: (value) {
                                    if (value == null || value.isEmpty) {
                                      return "กรุณาเลือกประเภทสถิติ";
                                    }
                                    return null;
                                  },
                                  value: _typeDropdownValue,
                                  hint: Text(
                                    "ประเภทสถิติ",
                                    style: TextStyle(color: Color(AppData.greyColor)),
                                  ),
                                  icon: Icon(Icons.keyboard_arrow_down),
                                  isExpanded: true,
                                  onChanged: (val) {
                                    ElectricityStatisticTypeModel type = typeList.singleWhere((item) => item.value == val);

                                    setState(() {
                                      _typeDropdownValue = val;
                                      _typeDropdownName = type.name;
                                    });
                                  },
                                  items: typeList.map<DropdownMenuItem<dynamic>>(
                                    (value) {
                                      return DropdownMenuItem<dynamic>(
                                        value: value.value ?? '',
                                        child: Text(value.name ?? ''),
                                      );
                                    },
                                  ).toList(),
                                  selectedItemBuilder: (BuildContext context) {
                                    return typeList.map<Widget>((item) {
                                      return Text(item.name ?? '');
                                    }).toList();
                                  },
                                );
                              }

                              return EmptyBox();
                            }),
                          ),
                          SizedBox(height: 20),
                          Container(
                            padding: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                            child: Table(
                              columnWidths: {0: FixedColumnWidth(deviceSize.width / 2.35)},
                              children: [
                                TableRow(
                                  children: [
                                    TableCell(
                                      child: Text("วันที่เริ่ม"),
                                    ),
                                    TableCell(
                                      child: Text("วันที่สิ้นสุด"),
                                    ),
                                  ],
                                ),
                                TableRow(
                                  children: [
                                    TableCell(
                                      child: _startDate(),
                                    ),
                                    TableCell(
                                      child: _endDate(),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: 20),
                          Padding(
                            padding: const EdgeInsets.only(top: 8.0),
                            child: RaisedButton(
                              color: Color(AppData.blueColor),
                              child: const Text('ค้นหา', style: TextStyle(color: Color(AppData.whiteColor))),
                              onPressed: () {
                                if (_formKey.currentState.validate()) {
                                  context.read<ElectricityStatisticBloc>().add(
                                        ElectricityStatisticOnSearch(
                                          peaNumber: _peaNumberDropdownValue,
                                          type: _typeDropdownValue,
                                          startDate: dateFormat.format(_startDateVal),
                                          endDate: dateFormat.format(_endDateVal),
                                        ),
                                      );
                                }
                              },
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 10),
                BlocListener<ElectricityStatisticBloc, ElectricityStatisticState>(
                  listener: (context, state) {
                    if (state is ElectricityStatisticErrorUnauthorized) {
                      Navigator.of(context).popUntil((route) => route.isFirst);
                      Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(builder: (context) => LogoutPage()),
                      );
                    }
                  },
                  child: BlocBuilder<ElectricityStatisticBloc, ElectricityStatisticState>(
                    builder: (context, state) {
                      if (state is ElectricityStatisticLoading) {
                        return Loading();
                      } else if (state is ElectricityStatisticLoaded) {
                        List<ElectricityStatisticModel> resultList = state.result;

                        return resultList != null
                            ? Row(
                                children: [
                                  RotatedBox(
                                    quarterTurns: -1,
                                    child: Text(
                                      "เดือน",
                                      style: TextStyle(fontSize: 18),
                                    ),
                                  ),
                                  Column(
                                    children: [
                                      Container(
                                        width: deviceSize.width - 40,
                                        height: deviceSize.height / 1.5,
                                        constraints: BoxConstraints(
                                          maxHeight: 500,
                                        ),
                                        child: Card(
                                          elevation: 3,
                                          child: Padding(
                                            padding: const EdgeInsets.all(10),
                                            child: charts.BarChart(
                                              _createData(resultList),
                                              animate: animate,
                                              vertical: false,
                                              barRendererDecorator: charts.BarLabelDecorator<String>(),
                                              domainAxis: charts.OrdinalAxisSpec(
                                                renderSpec: charts.SmallTickRendererSpec(labelRotation: 0),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                      SizedBox(height: 15),
                                      Text(
                                        _typeDropdownName ?? "",
                                        style: TextStyle(fontSize: 18),
                                      ),
                                    ],
                                  ),
                                ],
                              )
                            : EmptyBox();
                      } else if (state is ElectricityStatisticNotFound) {
                        return NotFoundBox();
                      } else if (state is ElectricityStatisticError) {
                        return ErrorBox(
                          message: state.message,
                        );
                      }

                      return EmptyBox();
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _startDate() {
    DateTime lastDayOfMonth = DateTime(DateTime.now().year, DateTime.now().month + 1, 0);
    return Row(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 20),
          child: Text(
            // dateFormat.format(_startDateVal),
            "${numberFormat.format(_startDateVal.day)}/${numberFormat.format(_startDateVal.month)}/${_startDateVal.year + 543}",
          ),
        ),
        InkWell(
          highlightColor: Colors.transparent,
          splashColor: Colors.transparent,
          child: Icon(
            Linecons.calendar,
            size: 25,
            color: Color(AppData.yellowColor),
          ),
          onTap: () async {
            DateTime startDate = await showRoundedDatePicker(
              context: context,
              fontFamily: AppData.notoSansThaiFont,
              era: EraMode.BUDDHIST_YEAR,
              theme: ThemeData(primarySwatch: Colors.purple),
              initialDate: _startDateVal,
              // firstDate: DateTime(DateTime.now().year - 2, 1, 1), //DateTime.now().subtract(Duration(days: 1)),
              // lastDate: DateTime(DateTime.now().year + 1, DateTime.now().month, lastDayOfMonth.day), //DateTime(DateTime.now().year + 1),
              firstDate: DateTime(DateTime.now().year - 100, 1, 1),
              lastDate: DateTime(DateTime.now().year + 100, 12, 31),
              borderRadius: 5,
            ); //as DateTime

            setState(() {
              _startDateVal = startDate ?? _startDateVal;
            });
          },
        ),
      ],
    );
  }

  Widget _endDate() {
    DateTime lastDayOfMonth = DateTime(DateTime.now().year, DateTime.now().month + 1, 0);
    return Row(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 20),
          child: Text(
            // dateFormat.format(_endDateVal),
            "${numberFormat.format(_endDateVal.day)}/${numberFormat.format(_endDateVal.month)}/${_endDateVal.year + 543}",
          ),
        ),
        InkWell(
          highlightColor: Colors.transparent,
          splashColor: Colors.transparent,
          child: Icon(
            Linecons.calendar,
            size: 25,
            color: Color(AppData.yellowColor),
          ),
          onTap: () async {
            DateTime endDate = await showRoundedDatePicker(
              context: context,
              fontFamily: AppData.notoSansThaiFont,
              era: EraMode.BUDDHIST_YEAR,
              theme: ThemeData(primarySwatch: Colors.purple),
              initialDate: _endDateVal,
              // firstDate: DateTime.now().subtract(Duration(days: 1)),
              // lastDate: DateTime(DateTime.now().year + 1, DateTime.now().month,
              // firstDate: DateTime(DateTime.now().year - 2, 1, 1),
              // lastDate: DateTime(DateTime.now().year + 1, DateTime.now().month, lastDayOfMonth.day), //DateTime(DateTime.now().year + 1),
              firstDate: DateTime(DateTime.now().year - 100, 1, 1),
              lastDate: DateTime(DateTime.now().year + 100, 12, 31),
              borderRadius: 5,
            ); //as DateTime

            setState(() {
              _endDateVal = endDate ?? _endDateVal;
            });
          },
        ),
      ],
    );
  }

  static List<charts.Series<ElectricityStatisticModel, String>> _createData(List<ElectricityStatisticModel> dataList) {
    final formatter = new NumberFormat("#,###.00");
    return [
      charts.Series<ElectricityStatisticModel, String>(
        id: 'Static',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        domainFn: (ElectricityStatisticModel items, _) => items.name,
        measureFn: (ElectricityStatisticModel items, _) => items.value,
        data: dataList,
        labelAccessorFn: (ElectricityStatisticModel items, _) => '${formatter.format(items.value)}',
      )
    ];
  }
}
