import 'dart:convert';
import 'dart:ui';
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:searchfield/searchfield.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/building/general_description/general_description_bloc.dart';
import 'package:unit2/model/offline/offline_profile.dart';
import 'package:unit2/screens/offline/passo/building/add/add_building.dart';

import '../../../../../model/passo/general_description.dart';
import '../../../../../model/passo/unit_construct.dart';
import '../../../../../theme-data.dart/form-style.dart';
import '../../../../../widgets/passo/custom_button.dart';
import '../../../../../widgets/passo/custom_formBuilder_fields.dart';
import 'package:intl/intl.dart';

class GeneralDescriptionOfflinePage extends StatefulWidget {
  final VoidCallback onPutGeneralDescription;
  final VoidCallback gendescPrevBtn;
  final OfflineProfile offlineProfile;

  final String bldgKind;
  final String bldgType;
  final String unitValue;

  final Function(String) updatedUnitValue;
  final Function(String) updatedBldgKind;
  final Function(String) updatedBldgType;

  GeneralDescriptionOfflinePage(
      this.onPutGeneralDescription,
      this.gendescPrevBtn,
      this.offlineProfile,
      this.bldgKind,
      this.bldgType,
      this.unitValue,
      this.updatedUnitValue,
      this.updatedBldgKind,
      this.updatedBldgType);

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

class _GeneralDescriptionOfflinePage
    extends State<GeneralDescriptionOfflinePage> {
  final focus = FocusNode();

  final actual_use = [
    "Residential",
    "Agricultural",
    "Commercial",
    "Industrial",
    "Mineral",
    "Timberland",
  ];

  final DateTime now;
  final String formatter;

  _GeneralDescriptionOfflinePage()
      : now = DateTime.now(),
        formatter = DateFormat.yMMMMd('en_US').format(DateTime.now());

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<UnitConstructionAdminBloc, UnitConstructionAdminState>(
      listener: (context, state) {
        // TODO: implement listener
      },
      builder: (context, state) {
        if (state is UnitConstructLoaded) {
          return SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Column(
                children: [
                  Container(
                    margin: const EdgeInsets.only(
                        left: 0, top: 20, right: 0, bottom: 10),
                    child: const Text('GENERAL DESCRIPTION',
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 18),
                        textAlign: TextAlign.left),
                  ),
                  Container(
                    margin: const EdgeInsets.only(
                        left: 0, top: 10, right: 0, bottom: 0),
                    child: SizedBox(
                      height: 45,
                      child: SearchField(
                        itemHeight: 70,
                        suggestions: state.unit
                            .map((UnitConstruct unit) => SearchFieldListItem(
                                '${unit.bldgType} - ${unit.building}',
                                item: unit,
                                child: ListTile(
                                  title: Text(
                                    '${unit.bldgType} - ${unit.building!.toUpperCase()}',
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                )))
                            .toList(),

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

                        searchInputDecoration:
                            normalTextFieldStyle(widget.bldgKind, "").copyWith(
                                suffixIcon: const Icon(Icons.arrow_drop_down)),
                        ////agency suggestion tap
                        focusNode: focus,
                        suggestionState: Suggestion.expand,
                        onSuggestionTap: (unit) async {
                          setState(() {
                            widget.updatedBldgKind(
                                '${unit.item!.bldgType} - ${unit.item!.building}');
                            widget.updatedBldgType(
                                '${unit.item!.bldgType} - ${unit.item!.building}');
                            widget.updatedUnitValue(unit.item!.unitValue);

                            offlineBldgKey.currentState!
                                .patchValue({'bldg_type': unit.item});
                          });

                          // Save the selected UnitConstruct to SharedPreferences
                          SharedPreferences prefs =
                              await SharedPreferences.getInstance();
                          String jsonString = jsonEncode(unit.item!.toJson());
                          await prefs.setString(
                              'selected_bldg_type', jsonString);

                          // Unfocus the current focus node
                          focus.unfocus();
                        },
                      ),
                    ),
                  ),
                  customDropDownField(
                      "Actual Use", "", 'actual_use', actual_use),
                  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: customTextField("Bldg. Permit No.", "",
                              'bldg_permit', TextInputType.number),
                        ),
                        const SizedBox(width: 10.0),
                        Expanded(
                            // optional flex property if flex is 1 because the default flex is 1
                            flex: 1,
                            child: customDatTimePicker(
                                "Date Issued", "", 'date_issued'))
                      ]),
                  Container(
                    margin: const EdgeInsets.only(
                        left: 0, top: 20, right: 0, bottom: 10),
                    child: const Text('Condominium Certificate of Title (CCT)',
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 15),
                        textAlign: TextAlign.start),
                  ),
                  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: customDatTimePicker(
                              "Certificate of Completion Issued ON",
                              "",
                              'coc_issued'),
                        ),
                        const SizedBox(width: 10.0),
                        Expanded(
                            // optional flex property if flex is 1 because the default flex is 1
                            flex: 1,
                            child: customDatTimePicker(
                                "Certificate of Occupancy Issued ON",
                                "",
                                'coo_issued'))
                      ]),
                  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: customDatTimePicker(
                              "Date Constructed /Completed",
                              "",
                              'date_cnstructed'),
                        ),
                        const SizedBox(width: 10.0),
                        Expanded(
                            // optional flex property if flex is 1 because the default flex is 1
                            flex: 1,
                            child: customDatTimePicker(
                                "Date Occupied", "", 'date_occupied'))
                      ]),
                  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: customTextField("Bldg. Age", "", 'bldg_age',
                              TextInputType.number),
                        ),
                        const SizedBox(width: 10.0),
                        Expanded(
                            // optional flex property if flex is 1 because the default flex is 1
                            flex: 1,
                            child: customTextField("No. of storeys", "",
                                'no_of_storeys', TextInputType.number))
                      ]),
                  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: customTextField("Area of 1st Floor", "",
                              'area_of_1stFl', TextInputType.number),
                        ),
                        const SizedBox(width: 10.0),
                        Expanded(
                            // optional flex property if flex is 1 because the default flex is 1
                            flex: 1,
                            child: customTextField("Area of 2nd Floor", "",
                                'area_of_2ndFl', TextInputType.number))
                      ]),
                  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Expanded(
                            flex: 1,
                            child: customTextField("Area of 3rd Floor", "",
                                'area_of_3rdFl', TextInputType.number)),
                        const SizedBox(width: 10.0),
                        Expanded(
                            // optional flex property if flex is 1 because the default flex is 1
                            flex: 1,
                            child: customTextField("Area of 4th Floor", "",
                                'area_of_4thFl', TextInputType.number))
                      ]),
                  customTextField(
                      "Total Area", "", 'total_area', TextInputType.number),
                  SizedBox(
                    height: 50,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      CustomButton(
                        icon: const Icon(Icons.chevron_left_rounded,
                            color: Colors.white),
                        onPressed: () {
                          {
                            widget.gendescPrevBtn();
                          }
                          ;
                        },
                      ),
                      CustomButton(
                        icon: const Icon(Icons.chevron_right_rounded,
                            color: Colors.white),
                        onPressed: () async {
                          {
                            final tempID =
                                await SharedPreferences.getInstance();

                            context.read<GeneralDescriptionBloc>().add(AddGendesc(
                                id: 1,
                                bldgapprDetailsId: tempID.getInt('tempid')!,
                                assessedById:
                                    widget.offlineProfile.id.toString(),
                                assessedByName:
                                    widget.offlineProfile.firstName!,
                                dateCreated: formatter,
                                dateModified: 'None',
                                bldgKind: widget.bldgKind ?? "",
                                strucType: widget.bldgType ?? "",
                                bldgPermit:
                                    offlineBldgKey.currentState?.value['bldg_permit'] ??
                                        " ",
                                dateIssued: offlineBldgKey
                                        .currentState!.value['date_issued']
                                        .toString() ??
                                    " ",
                                cct: 'None',
                                certCompletionIssued: offlineBldgKey
                                        .currentState!.value['coc_issued']
                                        .toString() ??
                                    " ",
                                certOccupancyIssued: offlineBldgKey
                                        .currentState!.value['coo_issued']
                                        .toString() ??
                                    " ",
                                dateCompleted: offlineBldgKey.currentState!.value['date_cnstructed'].toString() ?? "",
                                dateOccupied: offlineBldgKey.currentState!.value['date_occupied'].toString() ?? "",
                                bldgAge: offlineBldgKey.currentState!.value['bldg_age'] ?? "0",
                                noStoreys: offlineBldgKey.currentState!.value['no_of_storeys'] ?? "0",
                                area1Stfloor: offlineBldgKey.currentState!.value['area_of_1stFl'] ?? "0",
                                area2Ndfloor: offlineBldgKey.currentState!.value['area_of_2ndFl'] ?? "0",
                                area3Rdfloor: offlineBldgKey.currentState!.value['area_of_3rdFl'] ?? "0",
                                area4Thfloor: offlineBldgKey.currentState!.value['area_of_4thFl'] ?? "0",
                                totalFloorArea: offlineBldgKey.currentState?.value['total_area'] ?? "0",
                                floorSketch: null,
                                actualUse: offlineBldgKey.currentState?.value['actual_use'] ?? "",
                                unitValue: widget.unitValue ?? "",
                                genCode: '5th'));
                            widget.onPutGeneralDescription();
                          }
                          ;
                        },
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        }
        return Container();
      },
    );
  }
}
