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:shared_preferences/shared_preferences.dart';
import 'package:unit2/bloc/passo/land/land_trees_improvements/land_trees_improvements_bloc.dart';
import 'package:unit2/bloc/passo/land/other_improvements/other_improvements_bloc.dart';
import 'package:unit2/model/passo/other_improvements.dart';
import 'package:unit2/model/passo/trees_improvements.dart';
import 'package:unit2/theme-data.dart/form-style.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/error_state.dart';

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

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

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

class _AddOtherImprovementModal extends State<AddOtherImprovementModal> {
  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 = "";
  int _notPaintedUnitVal = 0;
  int _secondHandUnitVal = 0;
  String cityCode = '';
  String cityDesc = '';
  int classCode = 1;
  String _classDesc = '';
  String _treeType = "";
  bool _nonfruitBearing = false;
  bool _fruitBearing = false;
  int qty = 0;
  int pr_qty = 0;
  int nonpr_qty = 0;

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

  final typeOfTree = [
    "Non-Fruit Bearing",
    "Fruit Bearing",
  ];

  _calculateBaseMarketValue() {
    double base = 0.00;
    if (_fruitBearing) {
      base = (pr_qty + nonpr_qty) * _unitValue;
    } else {
      base = qty * _unitValue;
    }
    return base;
  }

  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<OtherImprovementsBloc, OtherImprovementsState>(
        buildWhen: (previous, current) {
      return false;
    }, builder: (context, state) {
      if (state is ShowAddOtherImprovementScreen) {
        return BlocConsumer<LandTreesImprovementsBloc,
            LandTreesImprovementsState>(listener: (context, state) {
          // TODO: implement listener
        }, builder: (context, state) {
          if (state is LandTreesImprovementsLoaded) {
            final trees = state.trees_imp;
            return FormBuilder(
                key: otherImpKey,
                onChanged: () {
                  otherImpKey.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<TreesImprovements>(
                                  name: 'kinds_of_trees',
                                  autofocus: false,
                                  decoration: normalTextFieldStyle(
                                      "Kinds of Trees", ""),
                                  items: state.trees_imp
                                      .map((trees) =>
                                          DropdownMenuItem<TreesImprovements>(
                                            value: trees,
                                            child: Text(
                                              (trees.improvement ?? "") +
                                                  "   " +
                                                  (trees.subclassCode ?? ""),
                                            ),
                                          ))
                                      .toList(),
                                  onChanged: (selectedTree) {
                                    if (selectedTree != null) {
                                      setState(() {
                                        _unitValue = double.parse(
                                            selectedTree.pricePerTree!);
                                        _treeType = selectedTree.improvement!;
                                      });
                                    }
                                  },
                                )),
                          ),
                          Container(
                            child: Row(
                              children: [
                                Row(
                                  children: [
                                    Checkbox(
                                      value: _fruitBearing,
                                      onChanged: (bool? value) {
                                        setState(() {
                                          _fruitBearing = value!;
                                        });
                                      },
                                    ),
                                    Text('Fruit Bearing ?'),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          Visibility(
                            visible: !_fruitBearing,
                            child: Row(
                              children: [
                                Expanded(
                                  child: FormBuilderTextField(
                                    name: 'subClass',
                                    decoration: normalTextFieldStyle(
                                        "SubClass/Age", ""),
                                    validator:
                                        FormBuilderValidators.compose([]),
                                    onChanged: (value) {
                                      setState(() {
                                        _subClassDesc = value!;
                                      });
                                    },
                                  ),
                                ),
                                SizedBox(
                                  width: 10,
                                ),
                                Expanded(
                                  child: FormBuilderTextField(
                                    name: 'qty',
                                    decoration: normalTextFieldStyle("No.", ""),
                                    validator:
                                        FormBuilderValidators.compose([]),
                                    onChanged: (value) {
                                      setState(() {
                                        qty = int.parse(value!);
                                      });
                                    },
                                  ),
                                ),
                              ],
                            ),
                            replacement: Column(
                              children: [
                                FormBuilderTextField(
                                  name: 'no_of_productive',
                                  decoration: normalTextFieldStyle(
                                      "No. of Productive", ""),
                                  validator: FormBuilderValidators.compose([]),
                                  onChanged: (value) {
                                    setState(() {
                                      pr_qty = int.parse(value!);
                                    });
                                  },
                                ),
                                const SizedBox(height: 10),
                                FormBuilderTextField(
                                  name: 'no_of_nonproductive',
                                  decoration: normalTextFieldStyle(
                                      "No. of Non-Productive", ""),
                                  validator: FormBuilderValidators.compose([]),
                                  onChanged: (value) {
                                    setState(() {
                                      nonpr_qty = 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(_unitValue))),
                          ),
                          const SizedBox(height: 10),
                          const Text('Base 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(_calculateBaseMarketValue().toString() ==
                                      "0.00"
                                  ? "00.0"
                                  : _calculateBaseMarketValue())),
                            ),
                          ),
                          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 improvement = OtherImprovements(
                                        landapprDetailsId:
                                            tempID.getInt('landid')! - 1,
                                        kindsOfTrees: _treeType,
                                        subclassAge: _subClassDesc,
                                        quantity: qty,
                                        unitValue: _unitValue.toString(),
                                        baseMarketval:
                                            _calculateBaseMarketValue()
                                                .toString(),
                                        noOfProductive: pr_qty,
                                        noOfNonproductive: nonpr_qty,
                                        fruitBearing: _fruitBearing);

                                    context.read<OtherImprovementsBloc>().add(
                                        AddOtherImprovement(
                                            other_imp: improvement));
                                  },
                                  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<OtherImprovementsBloc>()
                                        .add(const LoadOtherImprovement());
                                  },
                                  style: ElevatedButton.styleFrom(
                                    primary: Colors.black,
                                  ),
                                  child: const Text("Cancel"),
                                ),
                              ),
                            ],
                          )
                        ],
                      ),
                    ),
                  ),
                ));
          }
          if (state is LandTreesImprovementsErrorState) {
            return SomethingWentWrong(
              message: onError,
              onpressed: () {
                context
                    .read<LandTreesImprovementsBloc>()
                    .add(LoadLandTreesImprovements());
              },
            );
          }
          return Container();
        });
      }
      if (state is OtherImprovementErrorState) {
        return SomethingWentWrong(
          message: onError,
          onpressed: () {
            context.read<OtherImprovementsBloc>().add(LoadOtherImprovement());
          },
        );
      }
      return Container();
    });
  }
}
