import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.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/passo/bulding/property_appraisal/property_appraisal_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_assessment/property_assessment_bloc.dart';
import 'package:unit2/bloc/passo/memoranda/memoranda_bloc.dart';

import 'package:unit2/bloc/passo/signatories/signatories_bloc.dart';
import 'package:unit2/model/passo/memoranda.dart';
import 'package:unit2/model/passo/property_appraisal.dart';
import 'package:unit2/model/passo/property_assessment.dart';
import 'package:unit2/model/passo/signatories.dart';
import 'package:unit2/screens/passo/Building/add_building.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:unit2/theme-data.dart/form-style.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/error_state.dart';
import 'package:unit2/widgets/passo/custom_formBuilder_fields.dart';

class PropertyAssessmentPage extends StatefulWidget {
  Function function;

  PropertyAssessmentPage(this.function);

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

class _PropertyAssessmentPage extends State<PropertyAssessmentPage> {
  double assessment_level = 0;
  bool isTaxable = false;
  bool isExempt = false;
  String _memoranda = '';
  final focus = FocusNode();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: true,
        body: ProgressHUD(
            padding: const EdgeInsets.all(24),
            backgroundColor: Colors.black87,
            indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
            child: BlocConsumer<SignatoriesBloc, SignatoriesState>(
              listener: (context, state) {
                // TODO: implement listener
              },
              builder: (context, state) {
                if (state is SignatoriesLoaded) {
                  final signatories = state.signatories;
                  return BlocConsumer<MemorandaBloc, MemorandaState>(
                    listener: (context, state) {
                      // TODO: implement listener
                    },
                    builder: (context, state) {
                      if (state is MemorandaLoaded) {
                        final memoranda = state.memorada;
                        return ListView(
                          children: [
                            Align(
                              alignment: Alignment.center,
                              child: Container(
                                margin: const EdgeInsets.fromLTRB(0, 20, 0, 20),
                                child: const Text(
                                  'PROPERTY ASSESSMENT cont..',
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18,
                                  ),
                                  textAlign: TextAlign.left,
                                ),
                              ),
                            ),
                            Expanded(
                              flex: 3,
                              child: SingleChildScrollView(
                                padding:
                                    EdgeInsets.only(left: 20.0, right: 20.0),
                                scrollDirection: Axis.vertical,
                                child: Column(children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceAround,
                                    children: [
                                      Row(
                                        children: [
                                          const Text('Taxable'),
                                          Checkbox(
                                            checkColor: Colors.white,
                                            value: isTaxable,
                                            onChanged: (bool? value) {
                                              setState(() {
                                                isTaxable = value!;
                                              });
                                            },
                                          )
                                        ],
                                      ),
                                      Row(
                                        children: [
                                          const Text('Exempt'),
                                          Checkbox(
                                            checkColor: Colors.white,
                                            value: isExempt,
                                            onChanged: (bool? value) {
                                              setState(() {
                                                isExempt = value!;
                                              });
                                            },
                                          )
                                        ],
                                      ),
                                    ],
                                  ),
                                  Column(
                                    children: [
                                      const SizedBox(
                                        height: 20,
                                      ),
                                      const Text(
                                        'EFFECTIVITY OF ASSESSMENT / REASSESSMENT :',
                                        style: TextStyle(
                                            fontWeight: FontWeight.bold),
                                      ),
                                      const SizedBox(
                                        height: 20,
                                      ),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceAround,
                                        children: [
                                          const Text('Qtr.'),
                                          SizedBox(
                                            width: 70,
                                            height: 25,
                                            child: FormBuilderTextField(
                                              name: 'qtr',
                                              validator:
                                                  FormBuilderValidators.compose(
                                                      []),
                                            ),
                                          ),
                                          const SizedBox(
                                            width: 20,
                                          ),
                                          const Text('Yr.'),
                                          SizedBox(
                                            width: 70,
                                            height: 25,
                                            child: FormBuilderTextField(
                                              name: 'yr',
                                              validator:
                                                  FormBuilderValidators.compose(
                                                      []),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 30,
                                  ),
                                  Align(
                                    alignment: Alignment.centerLeft,
                                    child: Text(
                                      'APPRAISED/ASSESSED BY:',
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold),
                                      textAlign: TextAlign.start,
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceAround,
                                    children: [
                                      Column(
                                        children: [
                                          SizedBox(
                                            width: 200,
                                            child: FormBuilderDropdown<
                                                    Signatories>(
                                                name: 'appraised_by',
                                                autofocus: false,
                                                items: signatories
                                                    .map((signatories) =>
                                                        DropdownMenuItem(
                                                          value: signatories,
                                                          child: Text(
                                                              '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'),
                                                        ))
                                                    .toList()),
                                          ),
                                          Text('Name'),
                                        ],
                                      ),
                                      const SizedBox(
                                        width: 15,
                                      ),
                                      Column(
                                        children: [
                                          SizedBox(
                                            width: 100,
                                            child: FormBuilderDateTimePicker(
                                              name: 'app_date',
                                              initialEntryMode:
                                                  DatePickerEntryMode
                                                      .calendarOnly,
                                              initialValue: DateTime.now(),
                                              inputType: InputType.date,

                                              initialTime: const TimeOfDay(
                                                  hour: 8, minute: 0),
                                              // locale: const Locale.fromSubtags(languageCode: 'fr'),
                                            ),
                                          ),
                                          Text('Date'),
                                        ],
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 30,
                                  ),
                                  const Align(
                                      alignment: Alignment.centerLeft,
                                      child: Text(
                                        'RECOMMENDING APPROVAL:',
                                        style: TextStyle(
                                            fontWeight: FontWeight.bold),
                                      )),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceAround,
                                    children: [
                                      Column(
                                        children: [
                                          SizedBox(
                                            width: 200,
                                            child: FormBuilderDropdown<
                                                    Signatories>(
                                                name: 'rec_approval',
                                                autofocus: false,
                                                items: signatories
                                                    .map((signatories) =>
                                                        DropdownMenuItem(
                                                          value: signatories,
                                                          child: Text(
                                                              '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'),
                                                        ))
                                                    .toList()),
                                          ),
                                          Text('Name'),
                                        ],
                                      ),
                                      const SizedBox(
                                        width: 15,
                                      ),
                                      Column(
                                        children: [
                                          SizedBox(
                                            width: 100,
                                            child: FormBuilderDateTimePicker(
                                              name: 'rec_date',
                                              initialEntryMode:
                                                  DatePickerEntryMode
                                                      .calendarOnly,
                                              initialValue: DateTime.now(),
                                              inputType: InputType.date,

                                              initialTime: const TimeOfDay(
                                                  hour: 8, minute: 0),
                                              // locale: const Locale.fromSubtags(languageCode: 'fr'),
                                            ),
                                          ),
                                          Text('Date'),
                                        ],
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 30,
                                  ),
                                  const Align(
                                      alignment: Alignment.centerLeft,
                                      child: Text(
                                        'APPROVED BY:',
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                        ),
                                      )),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Column(
                                        children: [
                                          SizedBox(
                                            width: 200,
                                            child: FormBuilderDropdown<
                                                    Signatories>(
                                                name: 'apprvd_by',
                                                autofocus: false,
                                                items: signatories
                                                    .map((signatories) =>
                                                        DropdownMenuItem(
                                                          value: signatories,
                                                          child: Text(
                                                              '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'),
                                                        ))
                                                    .toList()),
                                          ),
                                          Text('Name'),
                                        ],
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 50,
                                  ),
                                  const Align(
                                      alignment: Alignment.centerLeft,
                                      child: Text(
                                        'MEMORANDA: ',
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                        ),
                                      )),
                                  SizedBox(
                                    height: 30,
                                  ),
                                  SizedBox(
                                      width: 500,
                                      height: 100,
                                      child: SearchField(
                                        itemHeight: 70,
                                        suggestions: memoranda
                                            .map((Memoranda memoranda) =>
                                                SearchFieldListItem(
                                                  '${memoranda.memoranda}',
                                                  item:
                                                      memoranda, // Change: Use individual Memoranda object
                                                  child: ListTile(
                                                    title: Text(
                                                      '${memoranda.memoranda}',
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                                ))
                                            .toList(),
                                        validator:
                                            FormBuilderValidators.required(
                                                errorText:
                                                    "This field is required"),
                                        // searchInputDecoration:
                                        //     normalTextFieldStyle(
                                        //             "Memoranda", "")
                                        //         .copyWith(
                                        //   suffixIcon: const Icon(
                                        //       Icons.arrow_drop_down),
                                        // ),
                                        // focusNode: focus,
                                        suggestionState: Suggestion.expand,
                                        onSuggestionTap: (memoranda) {
                                          setState(() {
                                            _memoranda =
                                                memoranda.item!.memoranda!;
                                          });
                                          focus.unfocus();
                                        },
                                      )),
                                  SizedBox(
                                    height: 30,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('Sworn Statement No. :'),
                                      SizedBox(
                                        width: 150,
                                        height: 20,
                                        child: FormBuilderTextField(
                                          name: 'sworn_statement',
                                          decoration: InputDecoration(),
                                          validator:
                                              FormBuilderValidators.compose([]),
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 30,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('Date Received:'),
                                      SizedBox(
                                        width: 150,
                                        height: 20,
                                        child: FormBuilderDateTimePicker(
                                          name: 'date_received',
                                          initialEntryMode:
                                              DatePickerEntryMode.calendarOnly,
                                          initialValue: DateTime.now(),
                                          inputType: InputType.date,

                                          initialTime: const TimeOfDay(
                                              hour: 8, minute: 0),
                                          // locale: const Locale.fromSubtags(languageCode: 'fr'),
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 30,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                          'Date of Entry in the Rec. of Ass. :'),
                                      SizedBox(
                                        width: 100,
                                        height: 20,
                                        child: FormBuilderDateTimePicker(
                                          name: 'date_of_entry',
                                          initialEntryMode:
                                              DatePickerEntryMode.calendarOnly,
                                          initialValue: DateTime.now(),
                                          inputType: InputType.date,

                                          initialTime: const TimeOfDay(
                                              hour: 8, minute: 0),
                                          // locale: const Locale.fromSubtags(languageCode: 'fr'),
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 30,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('By:'),
                                      SizedBox(
                                        width: 150,
                                        height: 20,
                                        child: FormBuilderTextField(
                                          name: 'by',
                                          decoration: InputDecoration(),
                                          validator:
                                              FormBuilderValidators.compose([]),
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 30,
                                  ),
                                  ElevatedButton(
                                    onPressed: () async {
                                      final tempID =
                                          await SharedPreferences.getInstance();
                                      print(tempID.getInt('tempid')! - 1);
                                      final List<PropertyAssessment>
                                          propertyAssessments = [];

                                      PropertyAssessment ass =
                                          PropertyAssessment(
                                        id: 1,
                                        bldgapprDetailsId:
                                            tempID.getInt('tempid')! - 1,
                                        actualUse: formKey.currentState!
                                                .value['actual_use'] ??
                                            '', // Replace null with an empty string
                                        marketValue: '0.00',
                                        assessmentLevel: '0.00',
                                        assessedValue: '0.00',
                                        taxable: isTaxable,
                                        exempt: isExempt,
                                        qtr: int.parse(formKey
                                                .currentState!.value['qtr'] ??
                                            '0'), // Replace null with '0'
                                        yr: int.parse(
                                            formKey.currentState!.value['yr'] ??
                                                '0'), // Replace null with '0'
                                        appraisedbyName: (formKey
                                                    .currentState!
                                                    .value['appraised_by']
                                                    ?.firstname ??
                                                '') +
                                            ' ' +
                                            (formKey
                                                    .currentState!
                                                    .value['appraised_by']
                                                    ?.middlename ??
                                                '') +
                                            ' ' +
                                            (formKey
                                                    .currentState!
                                                    .value['appraised_by']
                                                    ?.lastname ??
                                                ''),
                                        appraisedbyDate: formKey.currentState!
                                                    .value['app_date']
                                                as DateTime? ??
                                            DateTime
                                                .now(), // Replace null with current date
                                        recommendapprName: (formKey
                                                    .currentState!
                                                    .value['rec_approval']
                                                    ?.firstname ??
                                                '') +
                                            ' ' +
                                            (formKey
                                                    .currentState!
                                                    .value['rec_approval']
                                                    ?.middlename ??
                                                '') +
                                            ' ' +
                                            (formKey
                                                    .currentState!
                                                    .value['rec_approval']
                                                    ?.lastname ??
                                                ''),
                                        recommendapprDate: formKey.currentState!
                                                    .value['rec_date']
                                                as DateTime? ??
                                            DateTime
                                                .now(), // Replace null with current date
                                        approvedbyName: (formKey
                                                    .currentState!
                                                    .value['apprvd_by']
                                                    ?.firstname ??
                                                '') +
                                            ' ' +
                                            (formKey
                                                    .currentState!
                                                    .value['apprvd_by']
                                                    ?.middlename ??
                                                '') +
                                            ' ' +
                                            (formKey
                                                    .currentState!
                                                    .value['apprvd_by']
                                                    ?.lastname ??
                                                ''),
                                        memoranda: _memoranda,
                                        swornstatementNo: formKey.currentState!
                                                .value['sworn_statement'] ??
                                            '', // Replace null with an empty string
                                        dateReceived: formKey.currentState!
                                                    .value['date_received']
                                                as DateTime? ??
                                            DateTime
                                                .now(), // Replace null with current date
                                        entryDateAssessment: formKey
                                                    .currentState!
                                                    .value['date_of_entry']
                                                as DateTime? ??
                                            DateTime
                                                .now(), // Replace null with current date
                                        entryDateBy: formKey
                                                .currentState!.value['by'] ??
                                            '', // Replace null with an empty string
                                      );

                                      propertyAssessments.add(ass);

                                      context.read<PropertyAssessmentBloc>()
                                        ..add(UpdatePropertyAssessment(
                                            assessment:
                                                propertyAssessments[0]));
                                      widget.function();
                                    },
                                    style: ElevatedButton.styleFrom(
                                        backgroundColor: primary,
                                        foregroundColor: Colors.red),
                                    child: SizedBox(
                                      width: 200,
                                      height: 50,
                                      child: Align(
                                        alignment: Alignment.center,
                                        child: Text(
                                          'Save',
                                          style: TextStyle(
                                            color: Colors.white,
                                          ),
                                          textAlign: TextAlign.center,
                                        ),
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    height: 30,
                                  ),
                                ]),
                              ),
                            )
                          ],
                        );
                      }
                      return Container();
                    },
                  );
                }
                return Container();
              },
            )));
  }
}
