import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/survey_question/survey_question_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/components/profile_avatar.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/models/survey_question_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/pages/survey/survey_choice/survey_choice_checkbox.dart';
import 'package:peasmartcare/pages/survey/survey_choice/survey_choice_date.dart';
import 'package:peasmartcare/pages/survey/survey_choice/survey_choice_date_time.dart';
import 'package:peasmartcare/pages/survey/survey_choice/survey_choice_decimal.dart';
import 'package:peasmartcare/pages/survey/survey_choice/survey_choice_dropdown.dart';
import 'package:peasmartcare/pages/survey/survey_choice/survey_choice_integer.dart';
import 'package:peasmartcare/pages/survey/survey_choice/survey_choice_radio.dart';
import 'package:peasmartcare/pages/survey/survey_choice/survey_choice_text.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';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class SurveyQuestion extends StatefulWidget {
  final String surveyName;

  const SurveyQuestion({Key key, this.surveyName}) : super(key: key);

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

class _SurveyQuestionState extends State<SurveyQuestion> {
  final _formKey = GlobalKey<FormState>();
  int _currentIndex = 0;

  @override
  void initState() {
    context.read<SurveyQuestionBloc>().add(SurveyQuestionGetList());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PEAAppBar(
        title: "บันทึกแบบสำรวจข้อมูล",
        actions: <Widget>[
          ProfileAvatar(),
        ],
      ),
      body: BodyLayout(
        top: 0,
        layoutType: LayoutType.ONLY_CHILD,
        child: Column(
          children: <Widget>[_buildItem()],
        ),
      ),
    );
  }

  Widget _buildItem() {
    Size deviceSize = MediaQuery.of(context).size;
    return BlocListener<SurveyQuestionBloc, SurveyQuestionState>(
      listener: (context, state) {
        if (state is SurveyQuestionLoaded) {
          if (state.saveSuccess != null && state.saveSuccess) {
            SweetAlert.show(
              context,
              subtitle: "ส่งแบบสำรวจสำเร็จ",
              style: SweetAlertStyle.success,
              showCancelButton: false,
              onPress: (bool isConfirm) {
                if (isConfirm) {
                  Navigator.pop(context);
                  Navigator.pop(context);
                  return false;
                }
              },
            );

            // Navigator
          } else if (state.saveSuccess != null && !state.saveSuccess) {
            SweetAlert.show(
              context,
              subtitle: "ส่งแบบสำรวจไม่สำเร็จ",
              style: SweetAlertStyle.error,
            );
          }
        } else if (state is SurveyQuestionErrorUnauthorized) {
          Navigator.of(context).popUntil((route) => route.isFirst);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogoutPage()),
          );
        }
      },
      child: BlocBuilder<SurveyQuestionBloc, SurveyQuestionState>(
        builder: (context, state) {
          if (state is SurveyQuestionLoading) {
            return Loading();
          } else if (state is SurveyQuestionNotFound) {
            return NotFoundBox(name: "ยังไม่มีคำถามของแบบสำรวจนี้");
          } else if (state is SurveyQuestionLoaded) {
            SurveyQuestionModel survey = state.result;
            _currentIndex = state.currentIndex;
            return Container(
              child: SafeArea(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.only(top: 15, bottom: 15),
                        child: Text(
                          widget.surveyName,
                          style: TextStyle(
                              color: Color(
                                AppData.whiteColor,
                              ),
                              fontWeight: FontWeight.bold,
                              fontSize: 24),
                        ),
                      ),
                      Container(
                        width: double.infinity,
                        child: Card(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                          color: Colors.purple[100],
                          child: Padding(
                            padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  "${_currentIndex + 1}. ${survey.question}",
                                  style: TextStyle(
                                    color: Color(AppData.purpleColor),
                                    fontSize: 20,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      _buildChoice(survey, state.isNext, state.customerId),
                    ],
                  ),
                ),
              ),
            );
          } else if (state is SurveyQuestionError) {
            return ErrorBox(
              message: state.message,
            );
          }

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

  Widget _buildChoice(SurveyQuestionModel survey, bool isNext, String customerId) {
    return (() {
      switch (survey.type) {
        case 1:
          {
            return SurveyChoiceText(
              surveyId: survey.id,
              bloc: context.read<SurveyQuestionBloc>(),
              surveyChoiceList: survey.choiceList,
              currentIndex: _currentIndex,
              isNext: isNext,
              customerId: customerId,
              isValidate: true,
            );
          }
          break;
        case 2:
          {
            return SurveyChoiceInteger(
              surveyId: survey.id,
              bloc: context.read<SurveyQuestionBloc>(),
              surveyChoiceList: survey.choiceList,
              currentIndex: _currentIndex,
              isNext: isNext,
              customerId: customerId,
              minLength: 1,
              maxLength: 5,
              isValidate: true,
            );
          }
          break;
        case 3:
          {
            return SurveyChoiceDecimal(
              surveyId: survey.id,
              bloc: context.read<SurveyQuestionBloc>(),
              surveyChoiceList: survey.choiceList,
              currentIndex: _currentIndex,
              isNext: isNext,
              customerId: customerId,
              minLength: 1,
              maxLength: 5,
              isValidate: true,
            );
          }
          break;
        case 4:
          {
            return SurveyChoiceDate(
              surveyId: survey.id,
              bloc: context.read<SurveyQuestionBloc>(),
              surveyChoiceList: survey.choiceList,
              currentIndex: _currentIndex,
              isNext: isNext,
              customerId: customerId,
              // startDate: DateTime.now().subtract(Duration(days: 1)),
              // endDate: DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day + 10),
              isValidate: true,
            );
          }
          break;
        case 5:
          {
            return SurveyChoiceDateTime(
              surveyId: survey.id,
              bloc: context.read<SurveyQuestionBloc>(),
              surveyChoiceList: survey.choiceList,
              currentIndex: _currentIndex,
              isNext: isNext,
              customerId: customerId,
              // startDate: DateTime.now().subtract(Duration(days: 1)),
              // endDate: DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day + 10),
              isValidate: true,
            );
          }
          break;
        case 6:
          {
            return SurveyChoiceDropdown(
              surveyId: survey.id,
              bloc: context.read<SurveyQuestionBloc>(),
              questionName: survey.question,
              surveyChoiceList: survey.choiceList,
              currentIndex: _currentIndex,
              isNext: isNext,
              customerId: customerId,
              isValidate: true,
            );
          }
          break;
        case 7:
          {
            return SurveyChoiceRadio(
              surveyId: survey.id,
              bloc: context.read<SurveyQuestionBloc>(),
              questionName: survey.question,
              surveyChoiceList: survey.choiceList,
              currentIndex: _currentIndex,
              isNext: isNext,
              customerId: customerId,
              isValidate: true,
            );
          }
          break;
        case 8:
          {
            return SurveyChoiceCheckbox(
              surveyId: survey.id,
              bloc: context.read<SurveyQuestionBloc>(),
              questionName: survey.question,
              surveyChoiceList: survey.choiceList,
              currentIndex: _currentIndex,
              isNext: isNext,
              customerId: customerId,
              isValidate: true,
            );
          }
          break;
        default:
          {
            return NotFoundBox(name: "ยังไม่มีคำถามของแบบสำรวจนี้");
          }
          break;
      }
    }());
  }
}
