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:unit2/bloc/passo/barangay/barangay_bloc.dart';
import 'package:unit2/bloc/passo/bulding/landref/landref_bloc.dart';
import 'package:unit2/bloc/passo/bulding/location/location_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/passo/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/edit_building/property_owner_info.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';

class BldgLocLandRefEdit extends StatefulWidget {
  final int tempId;
  final VoidCallback NextBtn;
  final VoidCallback PrevBtn;

  BldgLocLandRefEdit(this.tempId, this.NextBtn, this.PrevBtn);
  @override
  _BldgLocLandRefEdit createState() => _BldgLocLandRefEdit();
}

class _BldgLocLandRefEdit extends State<BldgLocLandRefEdit> {
  Set<String> seenCityCodes = Set<String>();
  @override
  Widget build(BuildContext context) {
    return ProgressHUD(
      padding: const EdgeInsets.all(24),
      backgroundColor: Colors.black87,
      indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
      child: BlocConsumer<LocationBloc, LocationState>(
        listener: (context, state) {
          if (state is LocationLoading) {
            final progress = ProgressHUD.of(context);
            progress!.showWithText("Please wait...");
          }
          if (state is LocationLoaded) {
            final progress = ProgressHUD.of(context);
            progress?.dismiss();
          }
          if (state is LocationErrorState) {
            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 LocationLoaded) {
            final bldgloc = state.bldgloc;
            return BlocConsumer<LandrefBloc, LandrefState>(
              listener: (context, state) {
                if (state is LandrefLoading) {
                  final progress = ProgressHUD.of(context);
                  progress!.showWithText("Please wait...");
                }
                if (state is LandrefLoaded) {
                  final progress = ProgressHUD.of(context);
                  progress?.dismiss();
                }
                if (state is LandrefErrorState) {
                  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 LandrefLoaded) {
                  final landRef = state.landRef;
                  return 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) {
                      final cityList = state.municipality;
                      Set<City> uniqueItems = {};

                      // Iterate through the dropdownItems list to filter out duplicates
                      for (var item in cityList) {
                        uniqueItems.add(item);
                      }
                      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 FormBuilder(
                            key: keys,
                            initialValue: {
                              'street': bldgloc.street,
                              // 'brgy': bldgloc.barangay,
                              // 'municipality': bldgloc.municipality,
                              'province': bldgloc.province,
                              'l_owner': landRef.owner,
                              'oct_tct_cloa': landRef.cloaNo,
                              'survey_no': landRef.surveyNo,
                              'lot_no': landRef.lotNo,
                              'blk_no': landRef.blkNo,
                              'l_td_arp': landRef.tdn,
                              'area': landRef.area
                            },
                            enabled: true,
                            onChanged: () {
                              keys.currentState!.save();
                              debugPrint(keys.currentState!.value.toString());
                            },
                            autovalidateMode: AutovalidateMode.disabled,
                            skipDisabled: true,
                            child: SingleChildScrollView(
                              child: Padding(
                                padding: const EdgeInsets.all(20.0),
                                child: ListView(
                                  shrinkWrap: true,
                                  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(
                                            flex: 1,
                                            child: FormBuilderDropdown<City>(
                                              name: 'municipality',
                                              autofocus: false,
                                              decoration: normalTextFieldStyle(
                                                bldgloc.municipality ??
                                                    "Municipality",
                                                "",
                                              ),
                                              items: uniqueItems
                                                  .map(
                                                    (city) =>
                                                        DropdownMenuItem<City>(
                                                      value: city,
                                                      child: Text(
                                                          city.cityDescription ??
                                                              ''),
                                                    ),
                                                  )
                                                  .toList(),
                                              onChanged: (selectedCityCode) {
                                                // Find the corresponding City object using selectedCityCode
                                                final selectedCity = cityList
                                                    .firstWhere((city) =>
                                                        city.cityCode ==
                                                        selectedCityCode);

                                                final barangayBloc = context
                                                    .read<BarangayBloc>();
                                                barangayBloc.add(LoadBarangay(
                                                    id: selectedCityCode!
                                                        .cityCode!));
                                              },
                                            ),
                                          ),
                                          const SizedBox(width: 10.0),
                                          Expanded(
                                              // optional flex property if flex is 1 because the default flex is 1
                                              flex: 1,
                                              child: customTextField(
                                                  "Province / City",
                                                  "",
                                                  'province'))
                                        ]),
                                    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(
                                                  bldgloc.barangay,
                                                  "",
                                                  '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: () {
                                            {
                                              var bldgLocData = BldgLoc(
                                                id: widget.tempId,
                                                street: keys.currentState
                                                    ?.value['street'],
                                                barangay: keys.currentState
                                                    ?.value['brgy'],
                                                municipality: keys
                                                        .currentState
                                                        ?.value['municipality']
                                                        ?.cityDescription ??
                                                    bldgloc.municipality,
                                                province: keys.currentState
                                                    ?.value['province'],
                                              );
                                              var landRefData = LandRef(
                                                id: widget.tempId,
                                                owner: keys.currentState
                                                    ?.value['l_owner'],
                                                cloaNo: keys.currentState
                                                    ?.value['oct_tct_cloa'],
                                                lotNo: keys.currentState
                                                    ?.value['lot_no'],
                                                tdn: keys.currentState
                                                    ?.value['l_td_arp'],
                                                area: keys.currentState
                                                    ?.value['area'],
                                                surveyNo: keys.currentState
                                                    ?.value['survey_no'],
                                                blkNo: keys.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: '01'));
                            },
                          );
                        }
                        return Container();
                      });
                    }
                    if (state is MunicipalityErrorState) {
                      return SomethingWentWrong(
                        message: onError,
                        onpressed: () {
                          context
                              .read<MunicipalityBloc>()
                              .add(LoadMunicipality());
                        },
                      );
                    }
                    return Container();
                  });
                }
                if (state is LandrefErrorState) {
                  return SomethingWentWrong(
                    message: onError,
                    onpressed: () {
                      context.read<LandrefBloc>().add(
                          LoadLandref(id: widget.tempId, landRef: LandRef()));
                    },
                  );
                }
                return Container();
              },
            );
          }

          if (state is LocationErrorState) {
            return SomethingWentWrong(
              message: onError,
              onpressed: () {
                context
                    .read<LocationBloc>()
                    .add(LoadLocation(id: widget.tempId, bldgloc: BldgLoc()));
              },
            );
          }
          return Container();
        },
      ),
    );
  }
}
