import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/model/Timeline_model.dart';
import 'package:timeline_tile/timeline_tile.dart';

class service_Timeline extends StatefulWidget {
  var customerId, company;
  service_Timeline(this.customerId, this.company);
  @override
  _service_TimelineState createState() =>
      _service_TimelineState(this.customerId, this.company);
}

class _service_TimelineState extends State<service_Timeline> {
  var customerId, company;
  _service_TimelineState(this.customerId, this.company);
  String companyName = "";
  bool activeWeek = false;
  bool activeMonth = false;
  bool activeAll = false;
  bool isLoading = false;
  @override
  void initState() {
    super.initState();

    activeWeek = true;
    activeMonth = false;
    activeAll = false;

    print('service_Timeline');
    companyName = company;
    loadData(); // ดึงข้อมูล
  }

  loadWeekMonthData() async {
    try {
      final list = await TimelineModel.getData(this.customerId);
      setState(() {
        buttonActive(false, true, false);
        TimelineModel.data.clear();
        var i = 1;
        DateTime date;
        int n = DateTime.now().month;
        int y = DateTime.now().year;
        list.forEach((v) {
          final t = TimelineModel.fromJson(v);
          List<String> d = t.timelineDate.split("/");
          int y = int.tryParse(d[2].split(" ")[0]);
          if (y > 2500) {
            y = (y - 543);
            d[2] = y.toString();
          }
          String x = d[2] + "-" + d[1] + "-" + d[0];

          date = DateTime.parse(x);
          if (date.month == n && date.year == y) {
            TimelineModel.data.add(t); // loop เก็บข้อมูล
          }
          i = i + 1;
        });
      });
    } catch (e) {
      print(e);
    }
  }

  loadData() async {
    setState(() {
      isLoading = true;
    });
    final list = await TimelineModel.getData(
        this.customerId); // ไปเรียกฟังชั่นดึงข้อมูลจาก api

    print(list);
    setState(() {
      buttonActive(false, false, true);
      TimelineModel.data.clear();
      list.forEach((v) {
        final timelineList = TimelineModel.fromJson(v);
        TimelineModel.data.add(timelineList); // loop เก็บข้อมูล
        TimelineModel.data.sort((a, b) =>
            AppConvert.dateTimeThaiToEng(b.timelineDate)
                .compareTo(AppConvert.dateTimeThaiToEng(a.timelineDate)));
      });
    });
    isLoading = false;
  }

  loadWeekData() async {
    try {
      final list = await TimelineModel.getData(
          this.customerId); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      setState(() {
        buttonActive(true, false, false);
        TimelineModel.data.clear();
        var i = 1;
        DateTime date;
        DateTime first_of_week =
            DateTime.now().add(new Duration(days: -DateTime.now().weekday));
        print("First day of week : " + first_of_week.toString());
        print("Today is : " + DateTime.now().toString());
        list.forEach((v) {
          final t = TimelineModel.fromJson(v);
          List<String> d = t.timelineDate.split("/");
          int y = int.tryParse(d[2].split(" ")[0]);
          if (y > 2500) {
            d[2] = (y - 543).toString();
          }
          String x = d[2] + "-" + d[1] + "-" + d[0];

          date = DateTime.parse(x);
          if (date.isAfter(first_of_week)) {
            //print(i.toString()+" "+date.toString());
            TimelineModel.data.add(t); // loop เก็บข้อมูล
          }
          i = i + 1;
        });
      });
    } catch (e) {
      print(e);
    }
  }

  buttonActive(week, month, all) {
    setState(() {
      activeWeek = week;
      activeMonth = month;
      activeAll = all;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;
    double _height = MediaQuery.of(context).size.height;
    Widget _btnWeek = OutlineButton(
      textColor: activeWeek ? Colors.teal[800] : Color(0xFF6200EE),
      highlightedBorderColor: Colors.black.withOpacity(0.12),
      onPressed: () {
        loadWeekData();
      },
      child: Text("สัปดาห์นี้"),
    );
    Widget _btnAll = OutlineButton(
      textColor: activeAll ? Colors.teal[800] : Color(0xFF6200EE),
      highlightedBorderColor: Colors.black.withOpacity(0.12),
      onPressed: () {
        loadData();
      },
      child: Text("ทั้งหมด"),
    );
    Widget _btnMonth = OutlineButton(
      textColor: activeMonth ? Colors.teal[800] : Color(0xFF6200EE),
      highlightedBorderColor: Colors.black.withOpacity(0.12),
      onPressed: () {
        loadWeekMonthData();
      },
      child: Text("เดือนนี้"),
    );

    return Material(
      color: AppColors.bgColor,
      child: Stack(
        children: <Widget>[
          Header.header2(context),
          Header.mainMenu(context),
          Container(
            //            icon เมนู
            width: _width,
            //color: Colors.black26,
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 360),
              left: mediaQuery(context, 'w', 60),
              right: mediaQuery(context, 'w', 60),
              bottom: mediaQuery(context, 'h', 30),
            ),
            child: Column(
              children: <Widget>[
                Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(
                    bottom: mediaQuery(context, 'h', 60),
                  ),
                  child: Text(
                    AppStrings.service_Timeline,
                    style: TextStyle(
                      color: Color(0xFFB58E38),
                      fontSize: mediaQuery(context, 'h', 60),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: _width,
            height: mediaQuery(context, 'h', 1700),
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 480),
              left: mediaQuery(context, 'w', 60),
              right: mediaQuery(context, 'w', 60),
            ),
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                    // _btnWeek,
                    // Text(' '),
                    // _btnMonth,
                    // Text(' '),
                    // _btnAll,
                  ]),
                  Text(
                    companyName,
                    style: TextStyle(
                      color: AppColors.color_text,
                      fontSize: mediaQuery(context, 'h', 50),
                    ),
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 40),
                  ),
                  Column(
                    /* children: List.generate(TimelineModel.timelineListTest.length, (index) {
                    return _buildContent(
                      context,
                      (index + 1).toString(),
                      TimelineModel.timelineListTest[index]["timelineDate"],
                      TimelineModel.timelineListTest[index]["timelineType"],
                      TimelineModel.timelineListTest[index]["timelineDetail"],
                    );
                  }),*/
                    children: List.generate(TimelineModel.data.length, (index) {
                      return _buildContent(
                        context,
                        (index + 1).toString(),
                        TimelineModel.data[index].timelineDate,
                        TimelineModel.data[index].timelineType,
                        TimelineModel.data[index].timelineDetail,
                      );
                    }),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

_buildContent(
  context,
  number,
  Date,
  Type,
  Detail,
) {
  return TimelineTile(
    alignment: TimelineAlign.left,
    indicatorStyle: const IndicatorStyle(
      width: 25,
      color: Colors.red,
      padding: EdgeInsets.only(
        left: 0,
        right: 10,
      ),
    ),
    rightChild: Container(
      width: mediaQuery(context, 'w', 1005),
//      height: mediaQuery(context, 'h', 380),
      padding: EdgeInsets.all(
        mediaQuery(context, 'h', 50),
      ),
      margin: EdgeInsets.only(
        bottom: mediaQuery(context, 'h', 40),
      ),
      decoration: BoxDecoration(
        borderRadius: new BorderRadius.all(
          Radius.circular(
            mediaQuery(context, 'h', 20),
          ),
        ),
        boxShadow: [
          appShadow(),
        ],
        color: Colors.white,
      ),
      child: Row(
        children: <Widget>[
          GestureDetector(
            onTap: () {
//            showDialog(
//              context: context,
//              builder: (BuildContext context) => Detell_manny(),
//            );
            },
            child: Container(
              width: mediaQuery(context, 'w', 780),
              child: Wrap(
                spacing: 5.0,
                runSpacing: 5.0,
                direction: Axis.vertical,
                children: <Widget>[
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      /* Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'ลำดับ : ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 42),
                            ),
                          ),
                          Text(
                            number,
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),*/
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          // Text(
                          //   'ประเภท : ',
                          //   style: TextStyle(
                          //     color: AppColors.color_text,
                          //     fontSize: mediaQuery(context, 'h', 42),
                          //   ),
                          // ),
                          Text(
                            Type,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 47),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'วันที่ : ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 42),
                            ),
                          ),
                          Text(
                            Date + " น.",
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'รายละเอียด : ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 42),
                            ),
                          ),
                          Text(
                            Detail,
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    ),
  );
}
