import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.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/model/offline/offline_profile.dart';
import 'package:unit2/screens/offline/passo/building/add/add_building.dart';

import '../../../../../model/passo/barangay.dart';
import '../../../../../model/passo/city.dart';
import '../../../../../theme-data.dart/form-style.dart';
import '../../../../../widgets/passo/custom_button.dart';
import '../../../../../widgets/passo/custom_formBuilder_fields.dart';
import 'package:intl/intl.dart';

class LandRefLocationOfflinePage extends StatefulWidget {
  final VoidCallback PrevBtn;
  final VoidCallback NextBtn;
  final OfflineProfile offlineProfile;

  LandRefLocationOfflinePage(this.PrevBtn, this.NextBtn, this.offlineProfile);

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

class _LandRefLocationOfflinePage extends State<LandRefLocationOfflinePage> {
  final DateTime now;
  final String formatter;
  bool sameOwner = false;

  _LandRefLocationOfflinePage()
      : now = DateTime.now(),
        formatter = DateFormat.yMMMMd('en_US').format(DateTime.now());

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<MunicipalitiesAdminBloc, MunicipalitiesAdminState>(
      listener: (context, state) {
        // TODO: implement listener
      },
      builder: (context, state) {
        if (state is MunicipalitiesLoaded) {
          final city = state.city;
          return BlocConsumer<BarangayAdminBloc, BarangayAdminState>(
            listener: (context, state) {
              // TODO: implement listener
            },
            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(
                                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(
                                        "Municipality", ""),
                                    items: city
                                        .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<BarangayAdminBloc>();
                                        barangayBloc.add(LoadBarangayInMunicipality(
                                            cityCode:
                                                selectedCityCode!)); // Use selectedCityCode directly
                                      }
                                    },
                                  )),
                            ]),
                        Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: <Widget>[
                              Expanded(
                                flex: 1,
                                child: customTextField("No. / Street", "",
                                    'street', TextInputType.text),
                              ),
                              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),
                        ),
                        Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                SizedBox(
                                  width: 50, // Adjust the width as needed
                                  height: 50, // Adjust the height as needed
                                  child: Checkbox(
                                    checkColor: Colors.white,
                                    value: sameOwner,
                                    onChanged: (bool? value) {
                                      setState(() {
                                        sameOwner = value!;
                                        offlineBldgKey.currentState!
                                            .patchValue({
                                          'l_owner': offlineBldgKey.currentState
                                                  ?.value['fname'] +
                                              ' ' +
                                              offlineBldgKey.currentState
                                                  ?.value['mname'] +
                                              ' ' +
                                              offlineBldgKey
                                                  .currentState?.value['lname']
                                        });
                                        offlineBldgKey.currentState!
                                            .patchValue({
                                          'l_td_arp': offlineBldgKey
                                              .currentState?.value['arp_td']
                                        });
                                      });
                                    },
                                  ),
                                ),
                                Text('Same building owner')
                              ],
                            ),
                            // Other widgets in the column
                          ],
                        ),
                        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.streetAddress),
                              ),
                              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))
                            ]),
                        const SizedBox(
                          height: 50,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            CustomButton(
                              icon: const Icon(Icons.chevron_left_rounded,
                                  color: Colors.white),
                              onPressed: () {
                                {
                                  widget.PrevBtn();
                                }
                                ;
                              },
                            ),
                            // Builder(builder: (context) {
                            //   return CustomButton(
                            //     icon: const Icon(
                            //         Icons.chevron_right_rounded,
                            //         color: Colors.white),
                            //     onPressed: () async {
                            //       {
                            //         try {
                            //           final progress =
                            //               ProgressHUD.of(context);
                            //           Future.delayed(Duration(seconds: 3),
                            //               () {
                            //             progress?.dismiss();
                            //           });
                            //           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: "Agusan Del Norte");
                            //           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));
                            //         } catch (e) {
                            //           Fluttertoast.showToast(
                            //               msg:
                            //                   "Slow internet connection, please try again!");
                            //         }
                            //       }
                            //       ;
                            //     },
                            //   );
                            // })
                            Builder(builder: (context) {
                              return CustomButton(
                                icon: const Icon(
                                  Icons.chevron_right_rounded,
                                  color: Colors.white,
                                ),
                                onPressed: () async {
                                  // Rest of your code...
                                  final tempID =
                                      await SharedPreferences.getInstance();

                                  print('id check');
                                  print(tempID.getInt('tempid')!);

                                  context.read<LocationBloc>().add(AddLocation(
                                      id: 1,
                                      bldgapprDetailsId:
                                          tempID.getInt('tempid')!,
                                      assessedById:
                                          widget.offlineProfile.id.toString(),
                                      assessedByName:
                                          widget.offlineProfile.firstName!,
                                      dateCreated: 'None',
                                      dateModified: 'NOne',
                                      street: offlineBldgKey
                                              .currentState?.value['street'] ??
                                          "",
                                      barangay: offlineBldgKey
                                              .currentState?.value['brgy'] ??
                                          "",
                                      municipality: offlineBldgKey
                                              .currentState
                                              ?.value['municipality']
                                              .cityDescription ??
                                          "",
                                      province: "AGUSAN DEL NORTE",
                                      genCode: "5th"));

                                  context.read<LandrefLocationBloc>().add(AddLandRef(
                                      id: 1,
                                      bldgapprDetailsId:
                                          tempID.getInt('tempid')!,
                                      assessedById:
                                          widget.offlineProfile.id.toString(),
                                      assessedByName:
                                          widget.offlineProfile.firstName!,
                                      dateCreated: 'None',
                                      dateModified: 'None',
                                      owner: offlineBldgKey
                                              .currentState?.value['l_owner'] ??
                                          "",
                                      cloaNo: offlineBldgKey.currentState
                                              ?.value['oct_tct_cloa'] ??
                                          "",
                                      lotNo: offlineBldgKey
                                              .currentState?.value['lot_no'] ??
                                          "",
                                      tdn: offlineBldgKey.currentState
                                              ?.value['l_td_arp'] ??
                                          "",
                                      area:
                                          offlineBldgKey.currentState?.value['area'] ?? "0",
                                      surveyNo: offlineBldgKey.currentState?.value['survey_no'] ?? "",
                                      blkNo: offlineBldgKey.currentState?.value['blk_no'] ?? "",
                                      genCode: '5th'));

                                  widget.NextBtn();
                                },
                              );
                            })
                          ],
                        )
                      ],
                    ),
                  ),
                );
              }
              return Container();
            },
          );
        }
        return Container();
      },
    );
  }
}
