import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:intl/intl.dart';
import 'package:searchfield/searchfield.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/land_classification/land_classification_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/land_subclassification/land_subclassification_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/municipalities_admin/municipalities_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart';
import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart';
import 'package:unit2/screens/offline/passo/building/add/add_building.dart';
import 'package:unit2/screens/offline/passo/land/add/add_land.dart';
import 'package:unit2/widgets/error_state.dart';

import '../../../../../model/passo/city.dart';
import '../../../../../model/passo/land_appr.dart';
import '../../../../../model/passo/land_classification.dart';
import '../../../../../model/passo/land_subclassification.dart';
import '../../../../../theme-data.dart/form-style.dart';
import '../../../../../utils/text_container.dart';

class AddLandAppraisalOfflineModal extends StatefulWidget {
  // final List<UnitConstruct> unit;
  // final List<ClassComponents> options;
  // final int tempId;

  // AddLandAppraisalModal(this.unit, this.options, this.tempId);

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

class _AddLandAppraisalOfflineModal
    extends State<AddLandAppraisalOfflineModal> {
  final focus = FocusNode();
  bool isPainted = false;
  bool isSecondHand = false;
  TextEditingController textEditingController = TextEditingController();
  double _unitBase = 0;
  int _areaValue = 0;
  final double _depValue = 0;
  double _unitValue = 0;
  String _subClassDesc = "";
  int _classId = 0;
  String _structureType = "";
  bool _withoutBUCC = false;
  int _notPaintedUnitVal = 0;
  int _secondHandUnitVal = 0;
  String cityCode = '';
  String cityDesc = '';
  int classCode = 1;
  String _classDesc = '';

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

  BoxDecoration box1() {
    return const BoxDecoration(boxShadow: [
      BoxShadow(color: Colors.black12, spreadRadius: 5, blurRadius: 5)
    ], color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(3)));
  }

  double _amountofDepreciation(unitVal, unitBase, area, depreciation) {
    return ((unitVal * unitBase) * area) * depreciation;
  }

  double _totalMarketValue(unitBase, area) {
    return unitBase * area;
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<LandPropertyAppraisalBloc, LandPropertyAppraisalState>(
        buildWhen: (previous, current) {
      return false;
    }, builder: (context, state) {
      if (state is ShowAddItemsScreen) {
        return BlocConsumer<LandClassificationBloc, LandClassificationState>(
          listener: (context, state) {
            // TODO: implement listener
          },
          builder: (context, state) {
            if (state is LandClassificationLoaded) {
              final classification = state.landClassification;
              return BlocConsumer<LandSubclassificationBloc,
                  LandSubclassificationState>(
                listener: (context, state) {
                  // TODO: implement listener
                },
                builder: (context, state) {
                  if (state is LandSubClassificationLoaded) {
                    final subclassification = state.landSubClassification;
                    return BlocConsumer<MunicipalitiesAdminBloc,
                        MunicipalitiesAdminState>(
                      listener: (context, state) {
                        // TODO: implement listener
                      },
                      builder: (context, state) {
                        if (state is MunicipalitiesLoaded) {
                          return FormBuilder(
                              key: appraisalLandKey,
                              onChanged: () {
                                appraisalLandKey.currentState?.save();
                              },
                              autovalidateMode: AutovalidateMode.disabled,
                              child: Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Container(
                                    child: SingleChildScrollView(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisSize: MainAxisSize.min,
                                        children: <Widget>[
                                          Container(
                                            margin: const EdgeInsets.only(
                                                left: 0,
                                                top: 10,
                                                right: 0,
                                                bottom: 0),
                                            child: Expanded(
                                                flex: 1,
                                                child:
                                                    FormBuilderDropdown<City>(
                                                  name:
                                                      'appraisal_municipality',
                                                  autofocus: false,
                                                  decoration:
                                                      normalTextFieldStyle(
                                                          cityDesc ??
                                                              "Municipality",
                                                          ""),
                                                  items: state.city
                                                      .map((municipality) =>
                                                          DropdownMenuItem<
                                                              City>(
                                                            value: municipality,
                                                            child: Text(municipality
                                                                .cityDescription!), // Use cityDescription instead of cityName
                                                          ))
                                                      .toList(),
                                                  onChanged: (selectedCity) {
                                                    if (selectedCity != null) {
                                                      final selectedCityCode =
                                                          selectedCity.cityCode;
                                                      setState(() {
                                                        cityCode =
                                                            selectedCityCode!;
                                                        cityDesc = selectedCity
                                                            .cityDescription!;
                                                        _classDesc = "";
                                                        appraisalLandKey
                                                            .currentState
                                                            ?.patchValue({
                                                          'classification':
                                                              LandClassification(),
                                                        });
                                                      });
                                                      final barangayBloc =
                                                          context.read<
                                                              LandSubclassificationBloc>();
                                                      barangayBloc.add(
                                                          LoadSpecificLandSubClassification(
                                                              cityCode:
                                                                  cityCode,
                                                              classCode:
                                                                  classCode)); // Use selectedCityCode directly
                                                    }
                                                  },
                                                )),
                                          ),
                                          Container(
                                            margin: const EdgeInsets.only(
                                                left: 0,
                                                top: 10,
                                                right: 0,
                                                bottom: 0),
                                            child: Expanded(
                                                flex: 1,
                                                child: FormBuilderDropdown<
                                                    LandClassification>(
                                                  name: 'classification',
                                                  autofocus: false,
                                                  decoration:
                                                      normalTextFieldStyle(
                                                          _classDesc
                                                                  .toString() ??
                                                              "Classification",
                                                          ""),
                                                  items: classification
                                                      .map((classification) =>
                                                          DropdownMenuItem<
                                                              LandClassification>(
                                                            value:
                                                                classification,
                                                            child: Text(
                                                                classification
                                                                    .description!), // Use cityDescription instead of cityName
                                                          ))
                                                      .toList(),
                                                  onChanged: (selectedClass) {
                                                    if (selectedClass != null) {
                                                      final selectedClassCode =
                                                          selectedClass.id;
                                                      setState(() {
                                                        classCode =
                                                            selectedClassCode ??
                                                                0;
                                                        _classDesc = selectedClass
                                                                .description ??
                                                            '';
                                                      });
                                                      final barangayBloc =
                                                          context.read<
                                                              LandSubclassificationBloc>();
                                                      barangayBloc.add(
                                                          LoadSpecificLandSubClassification(
                                                              cityCode:
                                                                  cityCode,
                                                              classCode:
                                                                  classCode)); // Use selectedCityCode directly
                                                    }
                                                  },
                                                )),
                                          ),
                                          Container(
                                            margin: const EdgeInsets.only(
                                                left: 0,
                                                top: 10,
                                                right: 0,
                                                bottom: 0),
                                            child: SizedBox(
                                              height: 45,
                                              child: SearchField(
                                                itemHeight: 70,
                                                suggestions: subclassification
                                                    .map((LandSubClassification
                                                            subclass) =>
                                                        SearchFieldListItem(
                                                            '${subclass.subclassCode} - ${subclass.subclassDescription}',
                                                            item: subclass,
                                                            child: ListTile(
                                                              title: Text(
                                                                '${subclass.subclassCode} - ${subclass.subclassDescription!.toUpperCase()}',
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                              ),
                                                            )))
                                                    .toList(),

                                                validator: FormBuilderValidators
                                                    .required(
                                                        errorText:
                                                            "This field is required"),

                                                searchInputDecoration:
                                                    normalTextFieldStyle(
                                                            "Structure Type",
                                                            "")
                                                        .copyWith(
                                                            suffixIcon:
                                                                const Icon(Icons
                                                                    .arrow_drop_down)),
                                                ////agency suggestion tap
                                                focusNode: focus,
                                                suggestionState:
                                                    Suggestion.expand,
                                                suggestionDirection:
                                                    SuggestionDirection.up,
                                                onSuggestionTap: (subclass) {
                                                  setState(() {
                                                    _unitBase = double.parse(
                                                        subclass.item!
                                                            .baseUnitMarketval!);
                                                    _subClassDesc =
                                                        '${subclass.item!.subclassCode} - ${subclass.item!.subclassDescription}';
                                                  });
                                                  focus.unfocus();
                                                },
                                              ),
                                            ),
                                          ),
                                          const SizedBox(height: 10),
                                          FormBuilderTextField(
                                            name: 'land_appraisal_area',
                                            decoration: normalTextFieldStyle(
                                                "Area", ""),
                                            validator:
                                                FormBuilderValidators.compose(
                                                    []),
                                            onChanged: (value) {
                                              setState(() {
                                                _areaValue = int.parse(value!);
                                              });
                                            },
                                          ),
                                          const SizedBox(height: 10),
                                          const Text('Market Value'),
                                          const SizedBox(height: 5),
                                          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: Align(
                                                alignment: Alignment.center,
                                                child: Text(
                                                    NumberFormat.currency(
                                                            locale: 'en-PH',
                                                            symbol: "₱")
                                                        .format(
                                                            _totalMarketValue(
                                                                _unitBase,
                                                                _areaValue)))),
                                          ),
                                          const SizedBox(height: 10),
                                          Row(
                                            children: [
                                              Container(
                                                width: 120,
                                                height: 60,
                                                padding:
                                                    const EdgeInsets.all(8.0),
                                                child: ElevatedButton(
                                                  onPressed: () async {
                                                    final tempID =
                                                        await SharedPreferences
                                                            .getInstance();
                                                    print(tempID
                                                        .getInt('landid'));

                                                    context
                                                        .read<
                                                            LandPropertyAppraisalBloc>()
                                                        .add(AddLandPropertyAppraisal(
                                                            landapprDetailsId:
                                                                tempID.getInt(
                                                                        'landid')! +
                                                                    1,
                                                            classification:
                                                                _classDesc,
                                                            subClass:
                                                                _subClassDesc,
                                                            area: _areaValue
                                                                .toString(),
                                                            unitValue: _unitBase
                                                                .toString(),
                                                            baseMarketval:
                                                                _totalMarketValue(
                                                                        _unitBase,
                                                                        _areaValue)
                                                                    .toString()));
                                                  },
                                                  style:
                                                      ElevatedButton.styleFrom(
                                                    backgroundColor:
                                                        Colors.black,
                                                  ),
                                                  child: const Text("Submit"),
                                                ),
                                              ),
                                              const SizedBox(
                                                  width:
                                                      5), // Use SizedBox for horizontal spacing in a Row
                                              Container(
                                                width: 120,
                                                height: 60,
                                                padding:
                                                    const EdgeInsets.all(8.0),
                                                child: ElevatedButton(
                                                  onPressed: () {
                                                    context
                                                        .read<
                                                            LandPropertyAppraisalBloc>()
                                                        .add(
                                                            const LoadLandPropertyAppraisal());
                                                  },
                                                  style:
                                                      ElevatedButton.styleFrom(
                                                    backgroundColor:
                                                        Colors.black,
                                                  ),
                                                  child: const Text("Cancel"),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  )));
                        }
                        // if (state is MunicipalityErrorState) {
                        //   return SomethingWentWrong(
                        //     message: onError,
                        //     onpressed: () {
                        //       context
                        //           .read<MunicipalityBloc>()
                        //           .add(LoadMunicipality());
                        //     },
                        //   );
                        // }
                        return Container();
                      },
                    );
                  }
                  // if (state is LandSubClassificationErrorState) {
                  //   return SomethingWentWrong(
                  //     message: onError,
                  //     onpressed: () {
                  //       context.read<LandSubClassificationBloc>().add(
                  //           const LoadLandSubClassification(
                  //               cityCode: '1', classCode: 1));
                  //     },
                  //   );
                  // }
                  return Container();
                },
              );
            }
            // if (state is LandClassificationErrorState) {
            //   return SomethingWentWrong(
            //     message: onError,
            //     onpressed: () {
            //       context
            //           .read<LandClassificationBloc>()
            //           .add(const LoadLandClassification());
            //     },
            //   );
            // }
            return Container();
          },
        );
      }
      if (state is LandAppraisalErrorState) {
        return SomethingWentWrong(
          message: onError,
          onpressed: () {
            context
                .read<LandPropertyAppraisalBloc>()
                .add(const LoadLandPropertyAppraisal());
          },
        );
      }
      return Container();
    });
  }
}
