import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/survey_list/survey_list_bloc.dart';
import 'package:peasmartcare/blocs/survey_question/survey_question_bloc.dart';
import 'package:peasmartcare/blocs/survey_subject/survey_subject_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/header_content.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/components/profile_avatar.dart';
import 'package:peasmartcare/components/customer_info.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/models/survey_subject_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/pages/survey/survey_list.dart';
import 'package:peasmartcare/pages/survey/survey_question.dart';
import 'package:peasmartcare/utils/share_data_util.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SurveyPage extends StatefulWidget {
  final String surveyId;

  const SurveyPage({Key key, this.surveyId}) : super(key: key);

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

class _SurveyPageState extends State<SurveyPage> {
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  String surveyId = "";
  String surveyName = "";

  @override
  void initState() {
    context.read<SurveySubjectBloc>().add(SurveySubjectGetData(surveyId: widget.surveyId));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: PEAAppBar(
        title: "บันทึกแบบสำรวจข้อมูล",
        actions: <Widget>[
          ProfileAvatar(),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          context.read<SurveyQuestionBloc>().add(SurveyQuestionAddSurveyId(
                surveyId: surveyId,
              ));
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => SurveyQuestion(
                      surveyId: surveyId,
                      surveyName: surveyName,
                      customerId: ShareDataUtil.getCustomerId(),
                      fullname: ShareDataUtil.getFullname(),
                    )),
          );
        },
        tooltip: "ร้องเรียน",
        child: Icon(Icons.add, color: Color(AppData.whiteColor)),
        backgroundColor: Color(AppData.yellowColor),
      ),
      body: BodyLayout(
        header: CustomerInfo(),
        onPullRefresh: _onRefresh,
        refreshController: _refreshController,
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                HeaderContent(
                  title: BlocListener<SurveySubjectBloc, SurveySubjectState>(
                    listener: (context, state) {
                      if (state is SurveySubjectLoaded) {
                        SurveySubjectModel item = state.result;
                        setState(() {
                          surveyName = item.subject.trim();
                          surveyId = item.id;
                        });
                      } else if (state is SurveySubjectErrorUnauthorized) {
                        Navigator.of(context).popUntil((route) => route.isFirst);
                        Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(builder: (context) => LogoutPage()),
                        );
                      }
                    },
                    child: BlocBuilder<SurveySubjectBloc, SurveySubjectState>(
                      builder: (context, state) {
                        if (state is SurveySubjectLoaded) {
                          SurveySubjectModel item = state.result;
                          return AutoSizeText(
                            "${item.code.trim()} : ${item.subject.trim()}",
                            style: TextStyle(
                              color: Color(AppData.yellowColor),
                              fontWeight: FontWeight.bold,
                              fontSize: 24,
                            ),
                            maxLines: 1,
                          );
                        }
                        return EmptyBox(heightFactor: 0);
                      },
                    ),
                  ),
                  icon: ImageAsset.surveyImg,
                ),
                _body(),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _body() {
    return Positioned(
      child: Padding(
        padding: const EdgeInsets.only(top: 70),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SurveyList(surveyName: surveyName),
          ],
        ),
      ),
    );
  }

  Future<void> _onRefresh() async {
    context.read<SurveyListBloc>().add(SurveyListGetList());

    await Future.delayed(Duration(milliseconds: 1000));
    _refreshController.refreshCompleted();
  }
}
