import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_data_model.dart';
import 'package:test_sa/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart';
import 'package:test_sa/modules/internal_audit_module/pages/system_internal_audit/update_system_internal_audit_page.dart';
import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.dart';
import 'package:test_sa/modules/loan_module/models/loan_attachment_model.dart';
import 'package:test_sa/modules/loan_module/models/loan_request_model.dart';
import 'package:test_sa/modules/loan_module/provider/loan_provider.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/common_widgets/multiple_item_drop_down_menu.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/date_and_time/time_picker.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';

import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';

class UpdateMedicalGasInspectionPage extends StatefulWidget {
  final int inspectionId;

  UpdateMedicalGasInspectionPage({Key? key, required this.inspectionId}) : super(key: key);

  @override
  _UpdateMedicalGasInspectionPageState createState() {
    return _UpdateMedicalGasInspectionPageState();
  }
}

class _UpdateMedicalGasInspectionPageState extends State<UpdateMedicalGasInspectionPage> {
  List<GenericAttachmentModel> _attachments = [];

  bool pressureTestAcknowledgement = false;
  bool leakTestAcknowledgement = false;

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

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: DefaultAppBar(
          title: "Upload Delivery Note",
          onWillPopScope: () {
            _onUpdate(context);
          },
        ),
        body: SafeArea(
          child: FutureBuilder<LoanRequestModel?>(
              future: Provider.of<LoanProvider>(context, listen: false).getLoanById(0),
              builder: (BuildContext context, AsyncSnapshot<LoanRequestModel?> snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(color: AppColor.loadingColor(context)).center;

                // if (snapshot.data == null) return const NoDataFound().center;
                //
                // List<LoanAttachmentModel> allAttachments = snapshot.data!.loanAttachments!;

                return Column(
                  children: [
                    ListView(
                      padding: const EdgeInsets.all(16),
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // Row(
                            //   crossAxisAlignment: CrossAxisAlignment.start,
                            //   children: [
                            //     StatusLabel(
                            //       label: snapshot.data!.loanStatusName!,
                            //       textColor: AppColor.getRequestStatusTextColorByName(context, snapshot.data!.loanStatusName!),
                            //       backgroundColor: AppColor.getRequestStatusColorByName(context, snapshot.data!.loanStatusName!),
                            //     ),
                            //     1.width.expanded,
                            //     Text(
                            //       snapshot.data!.createdDate?.toServiceRequestCardFormat ?? "-",
                            //       textAlign: TextAlign.end,
                            //       style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral50),
                            //     ),
                            //   ],
                            // ),

                            MultipleItemDropDownMenu<Lookup, NullableLoadingProvider>(
                              context: context,
                              showAsBottomSheet: true,
                              backgroundColor: AppColor.neutral100,
                              showShadow: false,
                              showCancel: true,
                              requestById: context.userProvider.user?.clientId,
                              title: 'Delivered Items'.addTranslation,
                              // initialValue: _equipmentinternalAuditModel.findings,
                              onSelect: (value) {
                                // if ((value ?? []).isNotEmpty) {
                                //   Lookup? noFindingElement;
                                //   try {
                                //     noFindingElement = value!.singleWhere((element) => element.value == noFindingValue);
                                //   } catch (ex) {}
                                //   if (noFindingElement != null) {
                                //     value!.removeWhere((element) => element.value != noFindingElement!.value);
                                //   }
                                // }
                                // _equipmentinternalAuditModel.findings = value ?? [];
                              },
                            ),
                            16.height,
                            ADatePicker(
                              label: "EDD",
                              hideShadow: true,
                              backgroundColor: AppColor.fieldBgColor(context),
                              // initialDate: DateTime.tryParse(updateAssetModel?.edd ?? ""),
                              from: DateTime.now().subtract(const Duration(days: 365 * 3)),
                              to: DateTime.now(),
                              // date: DateTime.now(),
                              formatDateWithTime: true,
                              onDatePicker: (selectedDate) {
                                showThemedTimePicker(
                                  context: context,
                                  initialTime: TimeOfDay.now(),
                                ).then((selectedTime) {
                                  // Handle the selected date and time here.
                                  if (selectedTime != null) {
                                    DateTime? selectedDateTime = DateTime(
                                      selectedDate.year,
                                      selectedDate.month,
                                      selectedDate.day,
                                      selectedTime.hour,
                                      selectedTime.minute,
                                    );
                                    // if (updateAssetModel?.edd != null &&
                                    //     selectedDateTime.isBefore(DateTime.parse(updateAssetModel!.edd!))) {
                                    //   "Return To Service Date time must be greater then previous date".showToast;
                                    //   return;
                                    // }
                                  }
                                });
                              },
                            ),
                            16.height,
                            SingleItemDropDownMenu<Lookup, NullableLoadingProvider>(
                              context: context,
                              title: "PO Number",
                              validator: (value) {
                                if (value == null) return "Mandatory";
                                return null;
                              },
                              enabled: false,
                              staticData: [],
                              initialValue: null,
                              showShadow: false,
                              backgroundColor: AppColor.fieldBgColor(context),
                              showAsBottomSheet: true,
                              onSelect: (value) {},
                            ),
                            16.height,
                            AppTextFormField(
                              initialValue: "",
                              labelText: "Delivery Notes",
                              validator: (value) {
                                if ((value ?? "").isEmpty) return "Mandatory";
                                return null;
                              },
                              backgroundColor: AppColor.fieldBgColor(context),
                              labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                              floatingLabelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                              showShadow: false,
                              textInputType: TextInputType.multiline,
                              makeMultiLinesNull: true,
                              onChange: (value) {
                                // trafRequest?.purposeAnswer = value;
                              },
                            ),

                            16.height,
                            AttachmentPicker(
                              label: 'Upload Attachment',
                              attachment: _attachments,
                              buttonColor: AppColor.primary10,
                              showAsListView: true,
                              onlyImages: false,
                              buttonIcon: 'attachment_icon'.toSvgAsset(color: AppColor.primary10),
                            ),
                            16.height,
                            Row(
                              children: [
                                Checkbox(
                                    value: pressureTestAcknowledgement,
                                    visualDensity: const VisualDensity(horizontal: -4.0, vertical: -4.0),
                                    activeColor: AppColor.blueStatus(context),
                                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                    onChanged: (value) {
                                      setState(() {
                                        pressureTestAcknowledgement = value!;
                                      });
                                    }),
                                12.width,
                                "I Acknowledge that the received medical gases cylinders have been tested for pressure."
                                    .addTranslation
                                    .bodyText(context)
                                    .custom(color: context.isDark ? AppColor.primary50 : AppColor.neutral120)
                                    .expanded,
                              ],
                            ),
                            8.height,
                            Row(
                              // mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Checkbox(
                                    value: leakTestAcknowledgement,
                                    visualDensity: const VisualDensity(horizontal: -4.0, vertical: -4.0),
                                    activeColor: AppColor.blueStatus(context),
                                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                    onChanged: (value) {
                                      setState(() {
                                        leakTestAcknowledgement = value!;
                                      });
                                    }),
                                12.width,
                                "I Acknowledge that the received medical gases cylinders have been inspected for leak test."
                                    .addTranslation
                                    .bodyText(context)
                                    .custom(color: context.isDark ? AppColor.primary50 : AppColor.neutral120)
                                    .expanded,
                              ],
                            ),
                          ],
                        ).toShadowContainer(context, padding: 12),
                      ],
                    ).expanded,
                    if (context.userProvider.isEngineer)
                      FooterActionButton.footerContainer(
                        context: context,
                        child: AppFilledButton(
                            buttonColor: AppColor.primary10,
                            label: "Update",
                            onPressed: () async {
                              //    Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateEquipmentInternalAuditPage(model: model)));
                            }),
                      ),
                  ],
                );
              }),
        )).handlePopScope(
        cxt: context,
        onSave: () {
          _onUpdate(context);
        });
  }

  void _onUpdate(BuildContext context) async {}

  Widget labelValueText(BuildContext context, String label, String? value) {
    if (value == null || value.isEmpty) return const SizedBox.shrink();

    return Padding(
      padding: const EdgeInsets.only(bottom: 4),
      child: Text(
        '$label: $value',
        style: AppTextStyles.bodyText.copyWith(
          color: context.isDark ? AppColor.neutral30 : AppColor.neutral120,
        ),
      ),
    );
  }

  Widget checklistWidget(BuildContext context, {required String value}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Checkbox(
          value: true,
          activeColor: AppColor.neutral120,
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          visualDensity: const VisualDensity(horizontal: -4, vertical: -3),
          onChanged: (value) {},
        ),
        value.bodyText(context),
      ],
    );
  }
}
