import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:unit2/bloc/passo/bulding/class_components/class_components_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart';
import 'package:unit2/bloc/passo/bulding/unit_construct/unit_construct_bloc.dart';
import 'package:unit2/model/passo/bldg_loc.dart';
import 'package:unit2/model/passo/class_components.dart';
import 'package:unit2/model/passo/general_description.dart';
import 'package:unit2/model/passo/land_ref.dart';
import 'package:unit2/model/passo/property_appraisal.dart';
import 'package:unit2/model/passo/property_info.dart';
import 'package:unit2/model/passo/structural_materials_ii.dart';
import 'package:unit2/screens/passo/Building/add_building_components/additional_items.dart';
import 'package:unit2/screens/passo/Building/add_building_components/bldg_location_landref.dart';
import 'package:unit2/screens/passo/Building/add_building_components/general_description.dart';
import 'package:unit2/screens/passo/Building/add_building_components/property_appraisal.dart';
import 'package:unit2/screens/passo/Building/add_building_components/property_assessment.dart';
import 'package:unit2/screens/passo/Building/add_building_components/property_info.dart';
import 'package:unit2/screens/passo/Building/add_building_components/structural_materials.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:im_stepper/stepper.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/error_state.dart';

GlobalKey<FormBuilderState> formKey = GlobalKey<FormBuilderState>();

class AddBuilding extends StatefulWidget {
  @override
  _AddBuilding createState() => _AddBuilding();
}

class _AddBuilding extends State<AddBuilding> {
  int activeStep = 0; // Initial step set to 5.
  int upperBound = 6;

  bool saveStep1 = false;
  bool saveStep2 = false;
  bool saveStep3 = false;
  bool saveStep4 = false;
  bool saveStep5 = false;
  bool saveStep6 = false;
  bool saveStep7 = false;
  int tempId = 0;

  Future<void> _loadTempId() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      tempId = (prefs.getInt('tempid') ?? 0);
    });
  }

  void PrevBtn() {
    setState(() {
      activeStep--;
    });
  }

  void NextBtn() {
    setState(() {
      activeStep++;
    });
  }

  void onPutStructuralMaterials() {
    if (activeStep < upperBound) {
      setState(() {
        activeStep++;
      });
    }
    // var strucMaterials = StructureMaterialsII(
    //     foundation: _foundations.getSelectedAsString().split(","),
    //     columns: _coumns.getSelectedAsString().split(","),
    //     beams: _beams.getSelectedAsString().split(","),
    //     trussFraming:
    //         _trussframing.getSelectedAsString().split(","),
    //     roof: _roof.getSelectedAsString().split(","),
    //     flooring: _flooring.getSelectedAsString().split(","),
    //     walls: _walls.getSelectedAsString().split(","));
  }

  void onPutPropertyAppraisal() {}
  void bldgPrevBtn() {
    if (activeStep > 0) {
      setState(() {
        activeStep--;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: primary,
        centerTitle: true,
        title: const Text("Building FAAS"),
      ),
      body: ProgressHUD(
          padding: const EdgeInsets.all(24),
          backgroundColor: Colors.black87,
          indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
          child: BlocConsumer<PropertyInfoBloc, PropertyInfoState>(listener: (
            context,
            state,
          ) {
            if (state is PropertyInfoLoading) {
              final progress = ProgressHUD.of(context);
              progress!.showWithText("Please wait...");
            }
            if (state is PropertyInfoLoaded) {
              final progress = ProgressHUD.of(context);
              progress?.dismiss();
            }
            if (state is PropertyInfoErrorState) {
              final progress = ProgressHUD.of(context);
              progress?.dismiss();
            }
            if (state is ShowGenDescErrorAlertState ||
                state is ShowLandRefErrorAlertState ||
                state is ShowStrucMatErrorAlertState) {
              final progress = ProgressHUD.of(context);
              progress?.dismiss();
              Fluttertoast.showToast(
                  msg: "Slow internet connection, please try again!");
            }
            if (state is ShowLandRefSuccessAlertState ||
                state is ShowGenDescSuccessAlertState ||
                state is ShowStrucMatSuccessAlertState) {
              final progress = ProgressHUD.of(context);
              progress?.dismiss();
              NextBtn();
            }
          }, builder: (context, state) {
            if (state is PropertyInfoLoading ||
                state is PropertyInfoLoaded ||
                state is PropertyInfoErrorState ||
                state is ShowBldgLocErrorAlertState ||
                state is ShowGenDescErrorAlertState ||
                state is ShowLandRefErrorAlertState ||
                state is ShowStrucMatErrorAlertState ||
                state is ShowBldgLocSuccessAlertState ||
                state is ShowLandRefSuccessAlertState ||
                state is ShowGenDescSuccessAlertState ||
                state is ShowStrucMatSuccessAlertState) {
              return BlocConsumer<UnitConstructBloc, UnitConstructState>(
                listener: (
                  context,
                  state,
                ) {
                  if (state is UnitConstructLoading) {
                    final progress = ProgressHUD.of(context);
                    progress!.showWithText("Please wait...");
                  }
                  if (state is UnitConstructLoaded ||
                      state is UnitConstructErrorState) {
                    final progress = ProgressHUD.of(context);
                    progress?.dismiss();
                  }
                },
                builder: (context, state) {
                  if (state is UnitConstructLoaded) {
                    final unit = state.unit;
                    return BlocConsumer<ClassComponentsBloc,
                        ClassComponentsState>(
                      listener: (
                        context,
                        state,
                      ) {
                        if (state is ClassComponentLoading) {
                          final progress = ProgressHUD.of(context);
                          progress!.showWithText("Please wait...");
                        }
                        if (state is ClassComponentLoaded ||
                            state is ClassComponentErrorState) {
                          final progress = ProgressHUD.of(context);
                          progress?.dismiss();
                        }
                      },
                      builder: (context, state) {
                        if (state is ClassComponentLoaded) {
                          final classes = state.classes;

                          return Column(
                            children: [
                              NumberStepper(
                                numbers: [1, 2, 3, 4, 5, 6, 7],
                                stepPadding: 5,
                                activeStepColor: primary,
                                numberStyle: TextStyle(color: Colors.white),
                                lineColor: primary,
                                // activeStep property set to activeStep variable defined above.
                                activeStep: activeStep,
                                activeStepBorderColor: Colors.white,
                                activeStepBorderWidth: 1,
                                // This ensures step-tapping updates the activeStep.
                                onStepReached: (index) {
                                  setState(() {
                                    activeStep = index;
                                  });
                                },
                                enableStepTapping: false,
                              ),
                              Expanded(
                                child: StatefulBuilder(builder:
                                    (BuildContext context,
                                        StateSetter setState) {
                                  return FormBuilder(
                                    key: formKey,
                                    onChanged: () {
                                      formKey.currentState?.save();
                                    },
                                    autovalidateMode: AutovalidateMode.disabled,
                                    child: Container(
                                      child: content(
                                        unit,
                                        classes,
                                        PrevBtn,
                                        NextBtn,
                                      ),
                                    ),
                                  );
                                }),
                              ),
                            ],
                          );
                        }
                        if (state is ClassComponentErrorState) {
                          return SomethingWentWrong(
                            message: onError,
                            onpressed: () {
                              context
                                  .read<ClassComponentsBloc>()
                                  .add(LoadClassComponents());
                            },
                          );
                        }
                        return Container();
                      },
                    );
                  }
                  if (state is UnitConstructErrorState) {
                    return SomethingWentWrong(
                      message: onError,
                      onpressed: () {
                        context
                            .read<UnitConstructBloc>()
                            .add(LoadUnitConstruct());
                      },
                    );
                  }
                  return Container();
                },
              );
            }

            return Container();
          })),
    );
  }

  Widget content(unit, List<ClassComponents> classes, PrevBtn, NextBtn) {
    switch (activeStep) {
      case 0:
        return PropertyInfoPage(NextBtn);

      case 1:
        return BldgLocationLandrefPage(PrevBtn, NextBtn);

      case 2:
        return GeneralDescriptionPage(unit, NextBtn, PrevBtn);

      case 3:
        return StructuralMaterialsPage(PrevBtn, NextBtn);

      case 4:
        return AdditionalItemPage(unit, classes, PrevBtn, NextBtn);

      case 5:
        return PropertyAppraisalPage(NextBtn, PrevBtn);

      case 6:
        return PropertyAssessmentPage(onSAveAll);

      default:
        return Text("Property Info");
    }
  }

  void onSAveAll() {
    return Navigator.of(context).pop();
  }
}
