import 'dart:convert';

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: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/class_components_admin.dart/class_components_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/building/additional_items_offline/additional_items_offline_bloc.dart';
import 'package:unit2/model/offline/offline_profile.dart';
import 'package:unit2/model/passo/additional_items.dart';
import 'package:unit2/model/passo/class_components%20_offline.dart';
import 'package:unit2/model/passo/class_components.dart';
import 'package:unit2/model/passo/unit_construct.dart';
import 'package:unit2/theme-data.dart/form-style.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/error_state.dart';

// Function to get stored building type
Future<UnitConstruct> getStoredBldgType() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String? jsonString = prefs.getString('selected_bldg_type');
  if (jsonString != null) {
    Map<String, dynamic> json = jsonDecode(jsonString);
    return UnitConstruct.fromJson(json);
  }
  // Return a default UnitConstruct if no data is found
  return UnitConstruct.defaultConstruct();
}

class AddExtraItemsOffline extends StatefulWidget {
  final OfflineProfile offlineProfile;
  AddExtraItemsOffline(this.offlineProfile);

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

class _AddExtraItemsOffline extends State<AddExtraItemsOffline> {
  GlobalKey<FormBuilderState> formKey = GlobalKey<FormBuilderState>();
  final focus = FocusNode();
  final focusAddItems = FocusNode();
  bool isPainted = false;
  bool isSecondHand = false;
  TextEditingController textEditingController = TextEditingController();
  double _unitBase = 0;
  double _areaValue = 0;
  final double _depValue = 0;
  double _unitValue = 0;
  String _className = "";
  int _classId = 0;
  String _structureType = "";
  bool _withoutBUCC = false;
  int _notPaintedUnitVal = 0;
  int _secondHandUnitVal = 0;

  final DateTime now;
  final String formatter;

  _AddExtraItemsOffline()
      : now = DateTime.now(),
        formatter = DateFormat.yMMMMd('en_US').format(DateTime.now()),
        _unitConstruct = UnitConstruct.defaultConstruct();

  UnitConstruct _unitConstruct;

  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    UnitConstruct unitConstruct = await getStoredBldgType();
    setState(() {
      _unitConstruct = unitConstruct;
      _isLoading = false;
    });
  }

  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(unitVal, unitBase, area, depreciation, withBUCC,
      className, painted, secondHand, paintedUnitVal, secondhandUntVal) {
    if (withBUCC == false) {
      if (painted == true || secondHand == true) {
        final deductions = (paintedUnitVal + secondhandUntVal) / 100;

        print(deductions);
        return (((unitVal - deductions) * unitBase) * area);
      } else {
        return ((unitVal * unitBase) * area);
      }
    } else {
      return (unitVal * area);
    }
  }

  double _calculateMarketValue(unitVal, unitBase, area, withBUCC) {
    if (withBUCC == false) {
      return ((unitVal * unitBase) * area);
    } else {
      return (unitVal * area);
    }
  }

  void assignSelectedBldgValues() async {
    UnitConstruct? storedBldgType = await getStoredBldgType();
    if (_withoutBUCC) {
      _unitBase = _unitValue;
      _structureType =
          storedBldgType!.bldgType + ' - ' + storedBldgType.building;
      formKey.currentState!.patchValue({'buccValue': '100'});
    } else {
      _unitBase = double.parse(storedBldgType!.unitValue);
      _structureType =
          storedBldgType!.bldgType + ' - ' + storedBldgType.building;
      ;
      formKey.currentState!.patchValue({'unitValue': storedBldgType.unitValue});
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AdditionalItemsOfflineBloc, AdditionalItemsOfflineState>(
        buildWhen: (previous, current) {
      return false;
    }, builder: (context, state) {
      if (state is ShowAddItemsScreen) {
        return BlocConsumer<ClassComponentsAdminBloc,
            ClassComponentsAdminState>(
          listener: (context, state) {
            // TODO: implement listener
          },
          builder: (context, state) {
            if (state is ClassComponentsAdminLoaded) {
              final classes = state.classes;
              return BlocConsumer<UnitConstructionAdminBloc,
                  UnitConstructionAdminState>(
                listener: (context, state) {
                  // TODO: implement listener
                },
                builder: (context, state) {
                  if (state is UnitConstructLoaded) {
                    return FormBuilder(
                        key: formKey,
                        onChanged: () {
                          formKey.currentState?.save();
                        },
                        autovalidateMode: AutovalidateMode.disabled,
                        child: SingleChildScrollView(
                          padding: const EdgeInsets.all(2.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: SizedBox(
                                  height: 45,
                                  child: SearchField(
                                    itemHeight: 70,
                                    suggestions: classes
                                        .map((ClassComponentsOffline clss) =>
                                            SearchFieldListItem(
                                                '${clss.componentName}',
                                                item: clss,
                                                child: ListTile(
                                                  title: Text(
                                                    '${clss.componentName}',
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                  ),
                                                )))
                                        .toList(),

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

                                    searchInputDecoration: normalTextFieldStyle(
                                            "Additional Improvements", "")
                                        .copyWith(
                                            suffixIcon: const Icon(
                                                Icons.arrow_drop_down)),
                                    ////agency suggestion tap
                                    focusNode: focusAddItems,
                                    suggestionState: Suggestion.expand,
                                    onSuggestionTap: (value) {
                                      setState(() {
                                        if (value.item!.minBaseUnitvalPercent !=
                                            '0.00') {
                                          setState(() {
                                            _unitValue = double.parse(value
                                                .item!.minBaseUnitvalPercent!);
                                            _className =
                                                value.item!.componentName!;
                                            _classId = value.item!.id!;
                                            _withoutBUCC =
                                                value.item!.withoutBucc == 1
                                                    ? true
                                                    : false;
                                          });
                                          formKey.currentState!.patchValue({
                                            'unitValue': value
                                                .item!.minBaseUnitvalPercent
                                          });
                                          formKey.currentState!.patchValue({
                                            'buccValue': (double.parse(value
                                                        .item!
                                                        .minBaseUnitvalPercent!) *
                                                    100)
                                                .toString()
                                          });
                                        }
                                        if (value.item!.maxBaseUnitvalPercent !=
                                            '0.00') {
                                          setState(() {
                                            _unitValue = double.parse(value
                                                .item!.maxBaseUnitvalPercent!);
                                            _className =
                                                value.item!.componentName!;
                                            _classId = value.item!.id!;
                                            _withoutBUCC =
                                                value.item!.withoutBucc == 1
                                                    ? true
                                                    : false;
                                          });
                                          formKey.currentState!.patchValue({
                                            'unitValue': value
                                                .item!.maxBaseUnitvalPercent
                                          });
                                          formKey.currentState!.patchValue({
                                            'buccValue': (double.parse(value
                                                        .item!
                                                        .maxBaseUnitvalPercent!) *
                                                    100)
                                                .toString()
                                          });
                                        }
                                        if (value.item!.minUnitvalSqrmtr !=
                                            '0.00') {
                                          setState(() {
                                            _unitValue = double.parse(
                                                value.item!.minUnitvalSqrmtr!);
                                            _className =
                                                value.item!.componentName!;
                                            _classId = value.item!.id!;
                                            _withoutBUCC =
                                                value.item!.withoutBucc == 1
                                                    ? true
                                                    : false;
                                          });
                                          formKey.currentState!.patchValue({
                                            'unitValue':
                                                value.item!.minUnitvalSqrmtr
                                          });
                                          formKey.currentState!
                                              .patchValue({'buccValue': '100'});
                                        }
                                        if (value.item!.maxUnitvalSqrmtr !=
                                            '0.00') {
                                          setState(() {
                                            _unitValue = double.parse(
                                                value.item!.maxUnitvalSqrmtr!);
                                            _className =
                                                value.item!.componentName!;
                                            _classId = value.item!.id!;
                                            _withoutBUCC =
                                                value.item!.withoutBucc == 1
                                                    ? true
                                                    : false;
                                          });
                                          formKey.currentState!.patchValue({
                                            'unitValue':
                                                value.item!.maxUnitvalSqrmtr
                                          });
                                          formKey.currentState!
                                              .patchValue({'buccValue': '100'});
                                        }
                                        if (value.item!.minAddBaseunitval !=
                                            '0.00') {
                                          setState(() {
                                            _unitValue = double.parse(
                                                value.item!.minAddBaseunitval!);
                                            _className =
                                                value.item!.componentName!;
                                            _classId = value.item!.id!;
                                            _withoutBUCC =
                                                value.item!.withoutBucc == 1
                                                    ? true
                                                    : false;
                                          });
                                          formKey.currentState!.patchValue({
                                            'unitValue':
                                                value.item!.minAddBaseunitval
                                          });
                                          formKey.currentState!
                                              .patchValue({'buccValue': '100'});
                                        }
                                        if (value.item!.maxAddBaseunitval !=
                                            '0.00') {
                                          setState(() {
                                            _unitValue = double.parse(
                                                value.item!.maxAddBaseunitval!);
                                            _className =
                                                value.item!.componentName!;
                                            _classId = value.item!.id!;
                                            _withoutBUCC =
                                                value.item!.withoutBucc == 1
                                                    ? true
                                                    : false;
                                          });
                                          formKey.currentState!.patchValue({
                                            'unitValue':
                                                value.item!.maxAddBaseunitval
                                          });
                                          formKey.currentState!
                                              .patchValue({'buccValue': '100'});
                                        }
                                        if (value.item!.minDeductBaserate !=
                                            '0.00') {
                                          setState(() {
                                            _unitValue = double.parse(
                                                value.item!.minDeductBaserate!);
                                            _className =
                                                value.item!.componentName!;
                                            _classId = value.item!.id!;
                                            _withoutBUCC =
                                                value.item!.withoutBucc == 1
                                                    ? true
                                                    : false;
                                          });
                                          formKey.currentState!.patchValue({
                                            'unitValue':
                                                value.item!.minDeductBaserate
                                          });
                                          formKey.currentState!
                                              .patchValue({'buccValue': '100'});
                                        }
                                        if (value.item!.maxDeductBaserate !=
                                            '0.00') {
                                          setState(() {
                                            _unitValue = double.parse(
                                                value.item!.maxDeductBaserate!);
                                            _className =
                                                value.item!.componentName!;
                                            _classId = value.item!.id!;
                                            _withoutBUCC =
                                                value.item!.withoutBucc == 1
                                                    ? true
                                                    : false;
                                          });
                                          formKey.currentState!.patchValue({
                                            'unitValue':
                                                value.item!.maxDeductBaserate
                                          });
                                          formKey.currentState!
                                              .patchValue({'buccValue': '100'});
                                        }
                                        assignSelectedBldgValues();
                                        focusAddItems.unfocus();
                                      });
                                    },
                                  ),
                                ),
                              ),
                              const SizedBox(height: 10),
                              Container(
                                margin: const EdgeInsets.only(
                                    left: 0, top: 10, right: 0, bottom: 0),
                                child: SizedBox(
                                  height: 45,
                                  child: SearchField(
                                    enabled: false,
                                    itemHeight: 70,
                                    suggestions: state.unit
                                        .map((UnitConstruct unit) =>
                                            SearchFieldListItem(
                                                _unitConstruct.bldgType +
                                                    ' - ' +
                                                    _unitConstruct.building,
                                                item: unit,
                                                child: ListTile(
                                                  title: Text(
                                                    _unitConstruct.bldgType +
                                                        ' - ' +
                                                        _unitConstruct.building,
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                  ),
                                                )))
                                        .toList(),

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

                                    searchInputDecoration: normalTextFieldStyle(
                                            _unitConstruct.bldgType +
                                                ' - ' +
                                                _unitConstruct.building,
                                            "")
                                        .copyWith(
                                            suffixIcon: const Icon(
                                                Icons.arrow_drop_down)),
                                    ////agency suggestion tap
                                    focusNode: focus,
                                    suggestionState: Suggestion.expand,
                                    onSuggestionTap: (unit) {
                                      setState(() {});
                                      focus.unfocus();
                                    },
                                  ),
                                ),
                              ),
                              const SizedBox(height: 10),
                              Row(
                                children: [
                                  Expanded(
                                    flex: 1,
                                    child: FormBuilderTextField(
                                      name: 'unitValue',
                                      decoration: normalTextFieldStyle(
                                          "Unit Value", ""),
                                      keyboardType: TextInputType.phone,
                                      validator:
                                          FormBuilderValidators.compose([]),
                                    ),
                                  ),
                                  const SizedBox(width: 10),
                                  Expanded(
                                    flex: 1,
                                    child: FormBuilderTextField(
                                      name: 'buccValue',
                                      decoration:
                                          normalTextFieldStyle("BUCC", ""),
                                      keyboardType: TextInputType.phone,
                                      validator:
                                          FormBuilderValidators.compose([]),
                                      onChanged: (value) {
                                        // setState(() {
                                        //   _areaValue = double.parse(value!);
                                        // });
                                      },
                                    ),
                                  ),
                                  const SizedBox(
                                    height: 40,
                                    width: 40,
                                    child: Center(
                                      child: Text(
                                        '%',
                                        style: TextStyle(
                                            fontSize: 18,
                                            fontWeight: FontWeight.bold),
                                      ),
                                    ),
                                  )
                                ],
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Row(
                                children: [
                                  Expanded(
                                    flex: 1,
                                    child: FormBuilderTextField(
                                      name: 'areaValue',
                                      decoration:
                                          normalTextFieldStyle("Area", ""),
                                      keyboardType: TextInputType.phone,
                                      validator:
                                          FormBuilderValidators.compose([]),
                                      onChanged: (value) {
                                        setState(() {
                                          _areaValue = double.parse(value!);
                                        });
                                      },
                                    ),
                                  ),
                                ],
                              ),
                              Visibility(
                                visible: !_withoutBUCC,
                                child: Column(
                                  children: [
                                    const SizedBox(height: 10),
                                    const Text('Building is not painted?'),
                                    const SizedBox(height: 5),
                                    Container(
                                      child: Row(
                                        children: [
                                          Checkbox(
                                            value: isPainted,
                                            onChanged: (bool? value) {
                                              setState(() {
                                                isPainted = value!;
                                                if (value == false) {
                                                  _notPaintedUnitVal = 0;
                                                } else {
                                                  _notPaintedUnitVal = 10;
                                                }
                                              });
                                            },
                                          ),
                                          const SizedBox(width: 10),
                                          Container(
                                            height: 40.0,
                                            width: 100,
                                            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(' - ' +
                                                    _notPaintedUnitVal
                                                        .toString() +
                                                    '%')),
                                          ),
                                        ],
                                      ),
                                    ),
                                    const SizedBox(height: 10),
                                    const Text('Uses second hand materials?'),
                                    const SizedBox(height: 5),
                                    Container(
                                      child: Row(
                                        children: [
                                          Checkbox(
                                            value: isSecondHand,
                                            onChanged: (bool? value) {
                                              setState(() {
                                                isSecondHand = value!;
                                                if (isSecondHand == false) {
                                                  _secondHandUnitVal = 0;
                                                  formKey.currentState!
                                                      .patchValue({
                                                    'secondHandMat': '0'
                                                  });
                                                } else {
                                                  _secondHandUnitVal = 5;
                                                  formKey.currentState!
                                                      .patchValue({
                                                    'secondHandMat': '5'
                                                  });
                                                }
                                              });
                                            },
                                          ),
                                          const SizedBox(width: 10),
                                          Row(
                                            children: [
                                              SizedBox(
                                                height: 40,
                                                width: 100,
                                                child: FormBuilderTextField(
                                                  enabled: isSecondHand,
                                                  name: 'secondHandMat',
                                                  keyboardType:
                                                      TextInputType.phone,
                                                  textAlign: TextAlign.center,
                                                  decoration:
                                                      normalTextFieldStyle(
                                                          "Unit Value", ""),
                                                  validator:
                                                      FormBuilderValidators
                                                          .compose([]),
                                                  onChanged: (value) {
                                                    // Check if the value is not null before parsing to double
                                                    if (value != null &&
                                                        value.isNotEmpty) {
                                                      setState(() {
                                                        _secondHandUnitVal =
                                                            int.parse(value);
                                                      });
                                                    } else {
                                                      // Handle the case when the value is empty or null
                                                      // For example, set _secondHandUnitVal to a default value or show an error message.
                                                    }
                                                  },
                                                ),
                                              ),
                                              const SizedBox(
                                                height: 40,
                                                width: 40,
                                                child: Center(
                                                  child: Text(
                                                    '%',
                                                    style: TextStyle(
                                                        fontSize: 18,
                                                        fontWeight:
                                                            FontWeight.bold),
                                                  ),
                                                ),
                                              )
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              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(
                                            _unitValue,
                                            _unitBase,
                                            _areaValue,
                                            _depValue,
                                            _withoutBUCC,
                                            _className,
                                            isPainted,
                                            isSecondHand,
                                            _notPaintedUnitVal,
                                            _secondHandUnitVal)))),
                              ),
                              const SizedBox(height: 40),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  Container(
                                    width: 120,
                                    height: 60,
                                    padding: const EdgeInsets.all(8.0),
                                    child: ElevatedButton(
                                      onPressed: () async {
                                        try {
                                          final tempID = await SharedPreferences
                                              .getInstance();

                                          context.read<AdditionalItemsOfflineBloc>().add(
                                              AddAdditionalItems(
                                                  id: 1,
                                                  bldgapprDetailsId:
                                                      tempID.getInt('tempid')!,
                                                  classId: _classId,
                                                  assessedById: widget
                                                      .offlineProfile.id
                                                      .toString(),
                                                  assessedByName: widget
                                                      .offlineProfile
                                                      .firstName!,
                                                  dateCreated: formatter,
                                                  dateModified: 'None',
                                                  className: _className,
                                                  structType: _structureType,
                                                  unitValue: _withoutBUCC == true
                                                      ? 100
                                                      : _unitValue * 100,
                                                  baseUnitValue: _unitBase,
                                                  area: _areaValue,
                                                  marketValue:
                                                      _calculateMarketValue(
                                                          _unitValue,
                                                          _unitBase,
                                                          _areaValue,
                                                          _withoutBUCC),
                                                  depreciationRate: _depValue,
                                                  adjustedMarketVal:
                                                      _totalMarketValue(
                                                          _unitValue,
                                                          _unitBase,
                                                          _areaValue,
                                                          _depValue,
                                                          _withoutBUCC,
                                                          _className,
                                                          isPainted,
                                                          isSecondHand,
                                                          _notPaintedUnitVal,
                                                          _secondHandUnitVal),
                                                  actualUse: 'Test',
                                                  amtDepreciation:
                                                      _amountofDepreciation(
                                                    _unitValue,
                                                    _unitBase,
                                                    _areaValue,
                                                    _depValue,
                                                  ),
                                                  painted: true,
                                                  secondhand: true,
                                                  paintedUnitval: '1',
                                                  secondhandUnitval: '1',
                                                  genCode: "5th"));
                                        } catch (e) {
                                          Fluttertoast.showToast(
                                            msg:
                                                "Slow internet connection, please try again!",
                                          );
                                        }
                                      },
                                      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<AdditionalItemsOfflineBloc>()
                                            .add(const LoadAdditionalItems());
                                      },
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: Colors.black,
                                      ),
                                      child: const Text("Cancel"),
                                    ),
                                  ),
                                ],
                              )
                            ],
                          ),
                        )); // Use your actual widget
                  }
                  return Container();
                },
              );
            }
            return Container();
          },
        );
      }
      // if (state is Add) {
      //   return SomethingWentWrong(
      //     message: onError,
      //     onpressed: () {
      //       context.read<AdditionalItemBloc>().add(LoadAdditionalItems());
      //     },
      //   );
      // }
      return Container();
    });
  }
}
