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:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart';
import 'package:unit2/model/passo/property_info.dart';
import 'package:unit2/screens/passo/Building/add_building.dart';
import 'package:unit2/widgets/passo/custom_button.dart';
import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart';

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

class PropertyInfoPage extends StatefulWidget {
  final VoidCallback handleButtonPress;
  const PropertyInfoPage(this.handleButtonPress, {super.key});

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

class _PropertyInfoPage extends State<PropertyInfoPage> {
  int tempId = 0;
  final transaction_codes = ['New', 'Revision'];

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(
                    left: 0, top: 20, right: 0, bottom: 10),
                child: const Text('PROPERTY OWNER INFO',
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
                    textAlign: TextAlign.left),
              ),
              const SizedBox(height: 15),
              customDropDownField("Transaction Code", "", "transaction_code",
                  transaction_codes),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Expanded(
                      // optional flex property if flex is 1 because the default flex is 1
                      flex: 1,
                      child: customTextField("ARP No. / TD No.", "", 'arp_td')),
                  const SizedBox(width: 10.0),
                  Expanded(
                      // optional flex property if flex is 1 because the default flex is 1
                      flex: 1,
                      child: customTextField("Pin", "", 'pin')),
                ],
              ),
              customTextField("Owner", "", 'owner'),
              customTextField("Address", "", 'address'),
              Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: customTextField("Tel No.", "", 'tel_no'),
                    ),
                    const SizedBox(width: 10.0),
                    Expanded(
                        // optional flex property if flex is 1 because the default flex is 1
                        flex: 1,
                        child: customTextField("TIN", "", 'tin'))
                  ]),
              Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: customTextField(
                          "Administrator / Benificial User", "", 'benificiary'),
                    ),
                    const SizedBox(width: 10.0),
                    Expanded(
                        // optional flex property if flex is 1 because the default flex is 1
                        flex: 1,
                        child: customTextField("TIN", "", 'benificiary_tin'))
                  ]),
              Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <
                  Widget>[
                Expanded(
                  flex: 1,
                  child: customTextField("Address", "", 'benificiary_address'),
                ),
                const SizedBox(width: 10.0),
                Expanded(
                    // optional flex property if flex is 1 because the default flex is 1
                    flex: 1,
                    child: customTextField("Tel No.", "", 'benificiary_telno'))
              ]),
              const SizedBox(height: 25),
              CustomButton(
                icon: const Icon(Icons.chevron_right, color: Colors.white),
                onPressed: () async {
                  try {
                    var property_info = PropertyInfo(
                        id: 1,
                        transCode: formKey
                            .currentState!.value['transaction_code']
                            .toString(),
                        tdn: formKey.currentState!.value['arp_td'],
                        pin: formKey.currentState!.value['pin'],
                        owner: formKey.currentState!.value['owner'],
                        address: formKey.currentState!.value['address'],
                        telno: formKey.currentState!.value['tel_no'],
                        tin: formKey.currentState!.value['tin'],
                        adminUser: formKey.currentState!.value['benificiary'],
                        adminAddress:
                            formKey.currentState!.value['benificiary_address'],
                        adminTin:
                            formKey.currentState!.value['benificiary_tin'],
                        adminTelno:
                            formKey.currentState!.value['benificiary_telno'],
                        assessedById: '1',
                        assessedByName: 'Cyril',
                        faasType: "BUILDING",
                        dateModified: DateTime.now(),
                        dateCreated: DateTime.now());

                    // Dispatch the event to add the property_info
                    context.read<PropertyInfoBloc>().add(
                          AddPropertyInfo(property_info: property_info),
                        );
                    widget.handleButtonPress();
                  } catch (e) {
                    Fluttertoast.showToast(
                        msg: "Slow internet connection, please try again!");
                  }

                  // Wait for the event to complete and get the result
                  // bool failed = await _waitForAddPropertyInfoToComplete();

                  // if (failed) {
                  //   // Proceed to the next step or perform an action
                  //   Fluttertoast.showToast(
                  //       msg: "Slow internet connection, please try again!");
                  // } else {
                  //   // Stay or show an error message
                  //   widget.handleButtonPress();
                  // }
                },
              )
            ]),
      ),
    );
  }

  Future<bool> _waitForAddPropertyInfoToComplete() async {
    // Wait for the state change indicating completion
    final propertyInfoState = context.read<PropertyInfoBloc>().state;

    if (propertyInfoState is PropertyInfoErrorState) {
      // Check if the add operation was unsuccessful
      return true; // You'll need to define this in your state class
    }

    // Return false if the state didn't change as expected
    return false;
  }
}
