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: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/passo/bulding/additional_item/additional_item_bloc.dart';
import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart';
import 'package:unit2/bloc/passo/land/land_classification/land_classification_bloc.dart';
import 'package:unit2/bloc/passo/land/land_subclassification/land_subclassification_bloc.dart';
import 'package:unit2/bloc/passo/municipality/municipality_bloc.dart';
import 'package:unit2/model/passo/additional_items.dart';
import 'package:unit2/model/passo/city.dart';
import 'package:unit2/model/passo/class_components.dart';
import 'package:unit2/model/passo/land_appr.dart';
import 'package:unit2/model/passo/land_classification.dart';
import 'package:unit2/model/passo/land_subclassification.dart';
import 'package:unit2/model/passo/unit_construct.dart';
import 'package:unit2/screens/passo/Land/add_land.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_formBuilder_fields.dart';

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

  AddLandAppraisalEditModal(this.tempId);

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

class _AddLandAppraisalEditModal extends State<AddLandAppraisalEditModal> {
  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 BlocConsumer<LandAppraisalBloc, LandAppraisalState>(
        listener: (context, state) {
      if (state is LandAppraisalLoading) {
        final progress = ProgressHUD.of(context);
        progress!.showWithText("Please wait...");
      }
      if (state is LandAppraisalLoaded) {
        final progress = ProgressHUD.of(context);
        progress?.dismiss();
      }
      if (state is LandAppraisalErrorState) {
        final progress = ProgressHUD.of(context);
        progress?.dismiss();
      }
    }, buildWhen: (previous, current) {
      return false;
    }, builder: (context, state) {
      if (state is ShowAddLandAppraisalScreen) {
        return BlocConsumer<LandClassificationBloc, LandClassificationState>(
          listener: (context, state) {
            // TODO: implement listener
          },
          builder: (context, state) {
            if (state is LandClassificationLoaded) {
              final classification = state.land_classification;
              return BlocConsumer<LandSubClassificationBloc,
                  LandSubClassificationState>(
                listener: (context, state) {
                  // TODO: implement listener
                },
                builder: (context, state) {
                  if (state is LandSubClassificationLoaded) {
                    final subclassification = state.land_subclassification;
                    return BlocConsumer<MunicipalityBloc, MunicipalityState>(
                      listener: (context, state) {
                        // TODO: implement listener
                      },
                      builder: (context, state) {
                        if (state is MunicipalityLoaded) {
                          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.municipality
                                                      .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!;
                                                      });
                                                      final barangayBloc =
                                                          context.read<
                                                              LandSubClassificationBloc>();
                                                      barangayBloc.add(
                                                          LoadLandSubClassification(
                                                              classCode:
                                                                  classCode!,
                                                              cityCode:
                                                                  selectedCityCode!)); // 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!;
                                                        _classDesc =
                                                            selectedClass
                                                                .description!;
                                                      });
                                                      final barangayBloc =
                                                          context.read<
                                                              LandSubClassificationBloc>();
                                                      barangayBloc.add(
                                                          LoadLandSubClassification(
                                                              classCode:
                                                                  selectedClassCode!,
                                                              cityCode:
                                                                  cityCode)); // 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,
                                                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'));
                                                    var land_appraisal = LandAppr(
                                                        landapprDetailsId:
                                                            widget.tempId,
                                                        classification:
                                                            _classDesc,
                                                        subClass: _subClassDesc,
                                                        area: _areaValue
                                                            .toString(),
                                                        unitValue: _unitBase
                                                            .toString(),
                                                        baseMarketval:
                                                            _totalMarketValue(
                                                                    _unitBase,
                                                                    _areaValue)
                                                                .toString());

                                                    context
                                                        .read<
                                                            LandAppraisalBloc>()
                                                        .add(AddLandAppraisal(
                                                            land_appr:
                                                                land_appraisal));
                                                  },
                                                  style:
                                                      ElevatedButton.styleFrom(
                                                    primary: 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<
                                                            LandAppraisalBloc>()
                                                        .add(
                                                            LoadLandAppraisalEdit(
                                                          land_appr: <
                                                              LandAppr>[],
                                                          id: widget.tempId,
                                                        ));
                                                  },
                                                  style:
                                                      ElevatedButton.styleFrom(
                                                    primary: 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(LoadLandClassification());
                },
              );
            }
            return Container();
          },
        );
      }
      if (state is LandAppraisalErrorState) {
        return SomethingWentWrong(
          message: onError,
          onpressed: () {
            context.read<LandAppraisalBloc>().add(LoadLandAppraisal());
          },
        );
      }
      return Container();
    });
  }
}
