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/offline/offline_passo/admin/trees_improvements/trees_improvements_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/land/other_improvements/other_improvements_bloc.dart';

import '../../../../../model/passo/trees_improvements.dart';
import '../../../../../theme-data.dart/form-style.dart';
import '../../../../../utils/text_container.dart';
import '../../../../../widgets/error_state.dart';

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

  AddOtherImprovementModalEditOffline(this.tempId);

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

class _AddOtherImprovementModalEditOffline
    extends State<AddOtherImprovementModalEditOffline> {
  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 ShowOtherImprovementScreen) {
        return BlocConsumer<TreesImprovementsBloc, TreesImprovementsState>(
            listener: (context, state) {
          // TODO: implement listener
        }, builder: (context, state) {
          if (state is TreesImprovementsLoaded) {
            final trees = state.treesImprovements;
            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.treesImprovements
                                      .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'));

                                    context
                                        .read<OtherImprovementsBloc>()
                                        .add(AddOtherImprovements(
                                          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 == true ? '1' : '0',
                                        ));
                                  },
                                  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<OtherImprovementsBloc>()
                                        .add(const LoadOtherImprovements());
                                  },
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: 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 OtherImprovementsErrorState) {
        return SomethingWentWrong(
          message: onError,
          onpressed: () {
            context.read<OtherImprovementsBloc>().add(LoadOtherImprovements());
          },
        );
      }
      return Container();
    });
  }
}
