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/barangay/barangay_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart';

import 'package:unit2/bloc/passo/municipality/municipality_bloc.dart';
import 'package:unit2/model/location/barangay.dart';
import 'package:unit2/model/passo/bldg_loc.dart';

import 'package:unit2/model/passo/city.dart';
import 'package:unit2/model/passo/land_ref.dart';
import 'package:unit2/screens/passo/Building/add_building.dart';
import 'package:unit2/theme-data.dart/form-style.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/error_state.dart';
import 'package:unit2/widgets/passo/custom_button.dart';
import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart';

import '../../../../model/passo/barangay.dart';

class BldgLocationLandrefPage extends StatefulWidget {
  final VoidCallback PrevBtn;
  final VoidCallback NextBtn;
  BldgLocationLandrefPage(this.PrevBtn, this.NextBtn);

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

class _BldgLocationLandrefPage extends State<BldgLocationLandrefPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ProgressHUD(
        padding: const EdgeInsets.all(24),
        backgroundColor: Colors.black87,
        indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
        child: BlocConsumer<MunicipalityBloc, MunicipalityState>(
          listener: (context, state) {
            if (state is MunicipalityLoading) {
              final progress = ProgressHUD.of(context);
              progress!.showWithText("Please wait...");
            }
            if (state is MunicipalityLoaded) {
              final progress = ProgressHUD.of(context);
              progress?.dismiss();
            }
            if (state is MunicipalityErrorState) {
              final progress = ProgressHUD.of(context);
              progress?.dismiss();
              // Fluttertoast.showToast(
              //     msg: onError,
              //     fontSize: 24,
              //     toastLength: Toast.LENGTH_LONG,
              //     gravity: ToastGravity.CENTER,
              //     backgroundColor: Colors.black,
              //     textColor: Colors.white);
            }
          },
          builder: (context, state) {
            if (state is MunicipalityLoaded) {
              List<City> cityList = state.municipality;

              return BlocConsumer<BarangayBloc, BarangayState>(
                listener: (context, state) {
                  if (state is BarangayLoading) {
                    final progress = ProgressHUD.of(context);
                    progress!.showWithText("Please wait...");
                  }
                  if (state is BarangayLoaded) {
                    final progress = ProgressHUD.of(context);
                    progress?.dismiss();
                  }
                  if (state is BarangayErrorState) {
                    final progress = ProgressHUD.of(context);
                    progress?.dismiss();
                    // Fluttertoast.showToast(
                    //     msg: onError,
                    //     fontSize: 24,
                    //     toastLength: Toast.LENGTH_LONG,
                    //     gravity: ToastGravity.CENTER,
                    //     backgroundColor: Colors.black,
                    //     textColor: Colors.white);
                  }
                },
                builder: (context, state) {
                  if (state is BarangayLoaded) {
                    List<Brgy> brgyList = state.brgy;
                    List<String> brgyNAmes = brgyList
                        .map((brgy) => brgy.barangayDescription)
                        .toList()
                        .cast<String>();
                    return SingleChildScrollView(
                      child: Padding(
                        padding: const EdgeInsets.all(20.0),
                        child: Column(
                          children: [
                            Container(
                              margin: const EdgeInsets.only(
                                  left: 0, top: 20, right: 0, bottom: 10),
                              child: const Text('BUILDING LOCATION',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18),
                                  textAlign: TextAlign.left),
                            ),
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  Expanded(
                                      // optional flex property if flex is 1 because the default flex is 1
                                      flex: 1,
                                      child: customTextField(
                                          "Province / City", "", 'province')),
                                  const SizedBox(width: 10.0),
                                  Expanded(
                                      flex: 1,
                                      child: FormBuilderDropdown<City>(
                                        name: 'municipality',
                                        autofocus: false,
                                        decoration: normalTextFieldStyle(
                                            "Municipality", ""),
                                        items: cityList
                                            .map((city) =>
                                                DropdownMenuItem<City>(
                                                  value: city,
                                                  child: Text(city
                                                      .cityDescription!), // Use cityDescription instead of cityName
                                                ))
                                            .toList(),
                                        onChanged: (selectedCity) {
                                          if (selectedCity != null) {
                                            final selectedCityCode =
                                                selectedCity.cityCode;
                                            final barangayBloc =
                                                context.read<BarangayBloc>();
                                            barangayBloc.add(LoadBarangay(
                                                id: selectedCityCode!)); // Use selectedCityCode directly
                                          }
                                        },
                                      )),
                                ]),
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: customTextField(
                                        "No. / Street", "", 'street'),
                                  ),
                                  const SizedBox(width: 10.0),
                                  Expanded(
                                      // optional flex property if flex is 1 because the default flex is 1
                                      flex: 1,
                                      child: customDropDownField(
                                          "Brgy. / District",
                                          "",
                                          'brgy',
                                          brgyNAmes))
                                ]),
                            Container(
                              margin: const EdgeInsets.only(
                                  left: 0, top: 20, right: 0, bottom: 10),
                              child: const Text('LAND REFERENCE',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18),
                                  textAlign: TextAlign.left),
                            ),
                            customTextField("Land Owner", "", 'l_owner'),
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: customTextField(
                                        "OCT/TCT/CLOA No.", "", 'oct_tct_cloa'),
                                  ),
                                  const SizedBox(width: 10.0),
                                  Expanded(
                                      // optional flex property if flex is 1 because the default flex is 1
                                      flex: 1,
                                      child: customTextField(
                                          "Survey No.", "", 'survey_no'))
                                ]),
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: customTextField(
                                        "Lot No.", "", 'lot_no'),
                                  ),
                                  const SizedBox(width: 10.0),
                                  Expanded(
                                      // optional flex property if flex is 1 because the default flex is 1
                                      flex: 1,
                                      child: customTextField(
                                          "Blk No.", "", 'blk_no'))
                                ]),
                            Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  Expanded(
                                    flex: 1,
                                    child: customTextField(
                                        "TD / ARP No.", "", 'l_td_arp'),
                                  ),
                                  const SizedBox(width: 10.0),
                                  Expanded(
                                      // optional flex property if flex is 1 because the default flex is 1
                                      flex: 1,
                                      child:
                                          customTextField("Area", "", 'area'))
                                ]),
                            SizedBox(
                              height: 50,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                CustomButton(
                                  icon: const Icon(Icons.chevron_left_rounded,
                                      color: Colors.white),
                                  onPressed: () {
                                    {
                                      widget.PrevBtn();
                                    }
                                    ;
                                  },
                                ),
                                CustomButton(
                                  icon: const Icon(Icons.chevron_right_rounded,
                                      color: Colors.white),
                                  onPressed: () async {
                                    {
                                      final tempID =
                                          await SharedPreferences.getInstance();
                                      var bldgLocData = BldgLoc(
                                        id: tempID.getInt('tempid')! - 1,
                                        street: formKey
                                            .currentState?.value['street'],
                                        barangay:
                                            formKey.currentState?.value['brgy'],
                                        municipality: formKey
                                            .currentState
                                            ?.value['municipality']
                                            .cityDescription,
                                        province: formKey
                                            .currentState?.value['province'],
                                      );
                                      var landRefData = LandRef(
                                        id: tempID.getInt('tempid')! - 1,
                                        owner: formKey
                                            .currentState?.value['l_owner'],
                                        cloaNo: formKey.currentState
                                            ?.value['oct_tct_cloa'],
                                        lotNo: formKey
                                            .currentState?.value['lot_no'],
                                        tdn: formKey
                                            .currentState?.value['l_td_arp'],
                                        area:
                                            formKey.currentState?.value['area'],
                                        surveyNo: formKey
                                            .currentState?.value['survey_no'],
                                        blkNo: formKey
                                            .currentState?.value['blk_no'],
                                      );
                                      context.read<PropertyInfoBloc>()
                                        ..add(UpdateBldgLoc(
                                            bldg_loc: bldgLocData))
                                        ..add(UpdateLandRef(
                                            land_ref: landRefData));

                                      widget.NextBtn();
                                    }
                                    ;
                                  },
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                    );
                  }
                  if (state is BarangayErrorState) {
                    return SomethingWentWrong(
                      message: onError,
                      onpressed: () {
                        context.read<BarangayBloc>().add(LoadBarangay(id: '1'));
                      },
                    );
                  }
                  return Container();
                },
              );
            }
            if (state is MunicipalityErrorState) {
              return SomethingWentWrong(
                message: onError,
                onpressed: () {
                  context.read<MunicipalityBloc>().add(LoadMunicipality());
                },
              );
            }
            return Container();
          },
        ),
      ),
    );
  }

  Future<bool> _waitForAddPropertyInfoToComplete() async {
    // Wait for the state change indicating completion
    final propertyInfoState = context.read<PropertyInfoBloc>().state;

    if (propertyInfoState is PropertyInfoErrorState) {
      // Check if the add operation was successful
      return true; // You'll need to define this in your state class
    }

    // Return false if the state didn't change as expected
    return false;
  }
}
