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/offline/offline_passo/admin/barangay_admin/barangay_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/building/landref/landref_location_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/building/location/location_bloc.dart';
import 'package:unit2/screens/offline/passo/building/edit/edit_building.dart';
import 'package:unit2/screens/offline/passo/building/edit/property_owner_info_edit.dart';
import 'package:unit2/theme-data.dart/form-style.dart';

import '../../../../../model/passo/barangay.dart';
import '../../../../../model/passo/bldg_loc.dart';
import '../../../../../model/passo/city.dart';
import '../../../../../model/passo/land_ref.dart';
import '../../../../../widgets/passo/custom_button.dart';
import '../../../../../widgets/passo/custom_formBuilder_fields.dart';

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

  BldgLocLandRefEditOffline(this.tempId, this.NextBtn, this.PrevBtn);
  @override
  _BldgLocLandRefEditOffline createState() => _BldgLocLandRefEditOffline();
}

class _BldgLocLandRefEditOffline extends State<BldgLocLandRefEditOffline> {
  Set<String> seenCityCodes = Set<String>();
  @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<LocationBloc, LocationState>(
          listener: (context, state) {
            // if (state is LocationLoading) {
            //   final progress = ProgressHUD.of(context);
            //   progress!.showWithText("Please wait...");
            // }

            // if (state is LocationErrorState) {
            //   final progress = ProgressHUD.of(context);
            //   progress?.dismiss();
            // }
          },
          builder: (context, state) {
            if (state is SpecificLocationLoaded) {
              final bldgloc = state.location;
              return BlocConsumer<LandrefLocationBloc, LandrefLocationState>(
                listener: (context, state) {
                  // if (state is LandrefLoading) {
                  //   final progress = ProgressHUD.of(context);
                  //   progress!.showWithText("Please wait...");
                  // }
                  // if (state is LandrefErrorState) {
                  //   final progress = ProgressHUD.of(context);
                  //   progress?.dismiss();
                  // }
                },
                builder: (context, state) {
                  if (state is SpecificLandrefLoaded) {
                    final landRef = state.landref;
                    return BlocConsumer<MunicipalitiesAdminBloc,
                        MunicipalitiesAdminState>(listener: (context, state) {
                      // if (state is MunicipalityLoading) {
                      //   final progress = ProgressHUD.of(context);
                      //   progress!.showWithText("Please wait...");
                      // }
                      // if (state is MunicipalityErrorState) {
                      //   final progress = ProgressHUD.of(context);
                      //   progress?.dismiss();
                      // }
                    }, builder: (context, state) {
                      if (state is MunicipalitiesLoaded) {
                        final cityList = state.city;
                        Set<City> uniqueItems = {};

                        // Iterate through the dropdownItems list to filter out duplicates
                        for (var item in cityList) {
                          uniqueItems.add(item);
                        }
                        return BlocConsumer<BarangayAdminBloc,
                            BarangayAdminState>(listener: (context, state) {
                          if (state is BarangayLoaded) {
                            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();
                          // }
                        }, 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: offlineBldgEditKey,
                              initialValue: {
                                'street': bldgloc.street ?? "",
                                'province': bldgloc.province ?? "",
                                'l_owner': landRef.owner,
                                'oct_tct_cloa': landRef.cloaNo ?? "no",
                                'survey_no': landRef.surveyNo ?? "",
                                'lot_no': landRef.lotNo ?? "",
                                'blk_no': landRef.blkNo ?? "",
                                'l_td_arp': landRef.tdn ?? "",
                                'area': landRef.area ?? ""
                              },
                              enabled: true,
                              onChanged: () {
                                offlineBldgEditKey.currentState!.save();
                                debugPrint(offlineBldgEditKey
                                    .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: 20),
                                        child: const Text('BUILDING LOCATION',
                                            style: TextStyle(
                                                fontWeight: FontWeight.bold,
                                                fontSize: 18),
                                            textAlign: TextAlign.center),
                                      ),
                                      Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceEvenly,
                                          children: <Widget>[
                                            Expanded(
                                              child: Container(
                                                height: 45.0,
                                                width: double.infinity,
                                                decoration: BoxDecoration(
                                                  color: Colors.white,
                                                  border: Border.all(
                                                    color: Colors.grey,
                                                    width: 1.0,
                                                  ),
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          5.0),
                                                ),
                                                child: const Align(
                                                  alignment: Alignment.center,
                                                  child: Text(
                                                    "AGUSAN DEL NORTE",
                                                    style:
                                                        TextStyle(fontSize: 15),
                                                  ),
                                                ),
                                              ),
                                            ),
                                            const SizedBox(width: 10.0),
                                            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<BarangayAdminBloc>();
                                                //   barangayBloc.add(LoadBarangay(
                                                //       id: selectedCityCode!
                                                //           .cityCode!));
                                                // },
                                              ),
                                            ),
                                          ]),
                                      Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceEvenly,
                                          children: <Widget>[
                                            Expanded(
                                                // optional flex property if flex is 1 because the default flex is 1
                                                flex: 1,
                                                child: customDropDownField(
                                                    bldgloc.barangay,
                                                    "",
                                                    'brgy',
                                                    brgyNAmes)),
                                            const SizedBox(width: 10.0),
                                            Expanded(
                                              flex: 1,
                                              child: customTextField(
                                                  "No. / Street",
                                                  "",
                                                  'street',
                                                  TextInputType.text),
                                            ),

                                            // Expanded(
                                            //     // optional flex property if flex is 1 because the default flex is 1
                                            //     flex: 1,
                                            //     child: customDropDownField(
                                            //         bldgloc.barangay ?? "",
                                            //         "Barangay",
                                            //         'brgy',
                                            //         brgyNAmes))
                                          ]),
                                      Container(
                                        margin: const EdgeInsets.only(
                                            left: 0,
                                            top: 20,
                                            right: 0,
                                            bottom: 20),
                                        child: const Text('LAND REFERENCE',
                                            style: TextStyle(
                                                fontWeight: FontWeight.bold,
                                                fontSize: 18),
                                            textAlign: TextAlign.center),
                                      ),
                                      customTextField("Land Owner", "",
                                          'l_owner', TextInputType.text),
                                      Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceEvenly,
                                          children: <Widget>[
                                            Expanded(
                                              flex: 1,
                                              child: customTextField(
                                                  "OCT/TCT/CLOA No.",
                                                  "",
                                                  'oct_tct_cloa',
                                                  TextInputType.phone),
                                            ),
                                            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',
                                                    TextInputType.phone))
                                          ]),
                                      Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceEvenly,
                                          children: <Widget>[
                                            Expanded(
                                              flex: 1,
                                              child: customTextField(
                                                  "Lot No.",
                                                  "",
                                                  'lot_no',
                                                  TextInputType.phone),
                                            ),
                                            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',
                                                    TextInputType.phone))
                                          ]),
                                      Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceEvenly,
                                          children: <Widget>[
                                            Expanded(
                                              flex: 1,
                                              child: customTextField(
                                                  "TD / ARP No.",
                                                  "",
                                                  'l_td_arp',
                                                  TextInputType.phone),
                                            ),
                                            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',
                                                    TextInputType.phone))
                                          ]),
                                      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,
                                                  bldgapprDetailsId:
                                                      widget.tempId,
                                                  assessedById: '1',
                                                  assessedByName: 'cyril',
                                                  street: offlineBldgEditKey
                                                          .currentState
                                                          ?.value['street'] ??
                                                      bldgloc.street,
                                                  barangay: offlineBldgEditKey
                                                          .currentState
                                                          ?.value['brgy'] ??
                                                      bldgloc.barangay,
                                                  municipality: offlineBldgEditKey
                                                          .currentState
                                                          ?.value[
                                                              'municipality']
                                                          ?.cityDescription ??
                                                      bldgloc.municipality,
                                                  province: offlineBldgEditKey
                                                          .currentState
                                                          ?.value['province'] ??
                                                      bldgloc.province,
                                                );
                                                var landRefData = LandRef(
                                                  id: widget.tempId,
                                                  bldgapprDetailsId:
                                                      widget.tempId,
                                                  assessedById: '1',
                                                  assessedByName: 'cyril',
                                                  owner: offlineBldgEditKey
                                                          .currentState
                                                          ?.value['l_owner'] ??
                                                      landRef.owner,
                                                  cloaNo: offlineBldgEditKey
                                                              .currentState
                                                              ?.value[
                                                          'oct_tct_cloa'] ??
                                                      landRef.cloaNo,
                                                  lotNo: offlineBldgEditKey
                                                          .currentState
                                                          ?.value['lot_no'] ??
                                                      landRef.lotNo,
                                                  tdn: offlineBldgEditKey
                                                          .currentState
                                                          ?.value['l_td_arp'] ??
                                                      landRef.tdn,
                                                  area: offlineBldgEditKey
                                                          .currentState
                                                          ?.value['area'] ??
                                                      landRef.area,
                                                  surveyNo: offlineBldgEditKey
                                                              .currentState
                                                              ?.value[
                                                          'survey_no'] ??
                                                      landRef.surveyNo,
                                                  blkNo: offlineBldgEditKey
                                                          .currentState
                                                          ?.value['blk_no'] ??
                                                      landRef.blkNo,
                                                );
                                                context
                                                    .read<LocationBloc>()
                                                    .add(UpdateBldgLoc(
                                                        id: widget.tempId,
                                                        bldgLoc: bldgLocData));
                                                context
                                                    .read<LandrefLocationBloc>()
                                                    .add(UpdateBldgLandRef(
                                                        id: widget.tempId,
                                                        landRef: 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();
          },
        ),
      ),
    );
  }
}
