import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/all_requests_provider.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/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/medical_gas_inspection/models/delivery_notes_form_model.dart';
import 'package:test_sa/modules/medical_gas_inspection/models/medical_gas_data_model.dart';
import 'package:test_sa/modules/medical_gas_inspection/providers/medical_gas_inspection_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_lazy_loading.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/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/multi_image_picker.dart';

class UpdateDeliveryNotes extends StatefulWidget {
  final MedicalGasDataModel? dataModel;

  UpdateDeliveryNotes({Key? key, required this.dataModel}) : super(key: key);

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

class _UpdateDeliveryNotesState extends State<UpdateDeliveryNotes> {
  DeliveryNotesFormModel formModel = DeliveryNotesFormModel();
  late MedicalGasInspectionProvider medicalGasInspectionProvider;
  bool pressureTestAcknowledgement = false;
  bool leakTestAcknowledgement = false;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  List<GenericAttachmentModel> _attachments = [];

  @override
  void initState() {
    super.initState();
    medicalGasInspectionProvider = Provider.of<MedicalGasInspectionProvider>(context, listen: false);
    _populateFormData();
  }

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

  _populateFormData() {
    if (widget.dataModel != null) {
      MedicalGasDataModel dataModel = widget.dataModel!;
      formModel = DeliveryNotesFormModel(
          id: dataModel.id,
          deliveredItemList: dataModel.requestDetailDtos.where((item) => item.requestedQuantity! > 0).toList(),
          isInspectedGasLeak: dataModel.isInspectedGasLeak,
          isPressureChecked: dataModel.isPressureChecked,
          deliveredDate: dataModel.deliveredDate,
          // attachments: dataModel.deliveryNoteAttachmentDto,
          isSubmitted: dataModel.isSubmitted,
          deliveryNoteNumber: dataModel.deliveryNote);

      if (dataModel.deliveryNoteAttachmentDto.isNotEmpty) {
        _attachments.addAll(dataModel.deliveryNoteAttachmentDto.map((e) => GenericAttachmentModel(id: e.id, documentType: e.documentType, name: e.name)).toList());
      }
      //Need to Confirm this condition
      // selectedItemList = dataModel.requestDetailDtos.where((item) => item.deliveredQuantity != null && item.deliveredQuantity! > 0).toList();
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const DefaultAppBar(
          title: "Upload Delivery Note",
          // onWillPopScope: () {
          //   _update(context: context);
          // },
        ),
        body: Form(
          key: _formKey,
          child: Column(
            children: [
              ListView(
                padding: const EdgeInsets.all(16),
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ADatePicker(
                        label: "Delivered Date",
                        hideShadow: true,
                        backgroundColor: AppColor.fieldBgColor(context),
                        from: DateTime.now().subtract(const Duration(days: 365 * 3)),
                        date: formModel.deliveredDate,
                        formatDateWithTime: true,
                        onDatePicker: (selectedDate) {
                          showThemedTimePicker(
                            context: context,
                            initialTime: TimeOfDay.now(),
                          ).then((selectedTime) {
                            if (selectedTime != null) {
                              formModel.deliveredDate = DateTime(selectedDate.year, selectedDate.month, selectedDate.day, selectedTime.hour, selectedTime.minute);
                              setState(() {});
                            }
                          });
                        },
                      ),
                      16.height,
                      AppTextFormField(
                        initialValue: formModel.deliveryNoteNumber,
                        labelText: "Delivery Notes",
                        // validator: (value) {
                        //   if ((value ?? "").isEmpty) return "Delivery Notes Required";
                        //   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) {
                          formModel.deliveryNoteNumber = value;
                        },
                      ),
                      16.height,

                      //Older design code
                      // MultipleItemDropDownMenu<MedicalGasRequestDetailModel, NullableLoadingProvider>(
                      //   context: context,
                      //   showAsBottomSheet: true,
                      //   backgroundColor: AppColor.neutral100,
                      //   showShadow: false,
                      //   showCancel: true,
                      //   requestById: context.userProvider.user?.clientId,
                      //   title: 'Delivered Items'.addTranslation,
                      //   staticData: formModel.deliveredItemList,
                      //   initialValue: selectedItemList,
                      //   onSelect: (value) {
                      //     if ((value ?? []).isNotEmpty) {
                      //       WidgetsBinding.instance.addPostFrameCallback((_) {
                      //         if (!mounted) return;
                      //         setState(() {
                      //           selectedItemList = value ?? [];
                      //         });
                      //       });
                      //     }
                      //   },
                      // ),
                      // if (selectedItemList.isNotEmpty) ...[
                      //   8.height,
                      //   ListView.separated(
                      //     separatorBuilder: (_, __) => 12.height,
                      //     itemCount: selectedItemList.length,
                      //     shrinkWrap: true,
                      //     physics: const NeverScrollableScrollPhysics(),
                      //     itemBuilder: (context, index) {
                      //       MedicalGasRequestDetailModel model = selectedItemList[index];
                      //       return AppTextFormField(
                      //         labelText: '${model.name} (Req Qty =${model.requestedQuantity})',
                      //         hintText: 'Enter Delivered Quantity'.addTranslation,
                      //         backgroundColor: AppColor.fieldBgColor(context),
                      //         initialValue: model.deliveredQuantity != null ? model.deliveredQuantity?.toInt().toString() : '',
                      //         textAlign: TextAlign.center,
                      //         enable: true,
                      //         textInputType: TextInputType.number,
                      //         labelStyle: AppTextStyles.textFieldLabelStyle,
                      //         showShadow: false,
                      //         onChange: (value) {
                      //           if (value.isNotEmpty) {
                      //             model.deliveredQuantity = double.tryParse(value);
                      //           }
                      //         },
                      //         style: Theme.of(context).textTheme.titleMedium,
                      //       );
                      //     },
                      //   )
                      // ],
                      if (formModel.deliveredItemList.isNotEmpty) ...[
                        _ItemRowLayout(
                          left: 'Items'.addTranslation.bodyText(context).custom(color: AppColor.textColor(context)),
                          right: 'Delivered Qty'.addTranslation.bodyText(context).custom(color: AppColor.textColor(context)),
                        ),
                        8.height,
                        ListView.separated(
                          separatorBuilder: (_, __) => 12.height,
                          itemCount: formModel.deliveredItemList.length,
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemBuilder: (context, index) {
                            MedicalGasRequestDetailModel model = formModel.deliveredItemList[index];
                            return itemQuantityFieldWidget(index: index, model: model, context: context);
                          },
                        )
                      ],
                      16.height,

                      AttachmentPicker(
                        label: 'Upload Attachment',
                        attachment: _attachments,
                        showAsListView: true,
                        buttonColor: AppColor.primary10,
                        onlyImages: false,
                        buttonIcon: 'attachment_icon'.toSvgAsset(color: AppColor.primary10),
                      ),
                      16.height,
                      //should create a reusable widget.
                      Row(
                        children: [
                          Checkbox(
                              value: formModel.isPressureChecked,
                              visualDensity: const VisualDensity(horizontal: -4.0, vertical: -4.0),
                              activeColor: AppColor.blueStatus(context),
                              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              onChanged: (value) {
                                setState(() {
                                  formModel.isPressureChecked = 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: formModel.isInspectedGasLeak,
                              visualDensity: const VisualDensity(horizontal: -4.0, vertical: -4.0),
                              activeColor: AppColor.blueStatus(context),
                              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              onChanged: (value) {
                                setState(() {
                                  formModel.isInspectedGasLeak = 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,
              FooterActionButton.footerContainer(
                context: context,
                child: Row(
                  children: [
                    AppFilledButton(
                      buttonColor: AppColor.primary10,
                      label: 'Save'.addTranslation,
                      onPressed: () {
                        _update(context: context);
                      },
                      // buttonColor: AppColor.primary10,
                    ).expanded,
                    8.width,
                    AppFilledButton(
                      buttonColor: AppColor.primary10,
                      label: 'Submit'.addTranslation,
                      onPressed: () {
                        _update(context: context, isSubmitted: true);
                      },
                      // buttonColor: AppColor.primary10,
                    ).expanded,
                  ],
                ),
              ),
            ],
          ),
        ));
    // .handlePopScope(
    // cxt: context,
    // onSave: () {
    //   _update(context: context);
    // });
  }

  void _update({required BuildContext context, bool isSubmitted = false}) async {
    if (!_formKey.currentState!.validate()) return;
    if (formModel.deliveredDate == null) {
      'Delivered Date Required'.addTranslation.showToast;
      return;
    }
    if (formModel.deliveryNoteNumber == null) {
      'Delivery Notes Required'.addTranslation.showToast;
      return;
    }
    if (formModel.isPressureChecked == null || formModel.isPressureChecked == false) {
      'Please acknowledge cylinders are tested for pressure'.addTranslation.showToast;
      return;
    }
    if (formModel.isInspectedGasLeak == null || formModel.isInspectedGasLeak == false) {
      'Please acknowledge cylinders have been inspected for leak test'.addTranslation.showToast;
      return;
    }
    _formKey.currentState?.save();
    formModel.gasDeliveredQuantityDtos = [];
    formModel.isSubmitted = isSubmitted;
    for (var item in formModel.deliveredItemList) {
      formModel.gasDeliveredQuantityDtos.add(GasDeliveredQuantityModel(
        id: widget.dataModel != null ? item.id : 0,
        medicalGasAttributeId: item.medicalGasAttributeId ?? item.id,
        deliveredQuantity: item.deliveredQuantity,
      ));
    }
    formModel.attachments = [];
    try {
      for (var item in _attachments) {
        String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
        formModel.attachments.add(GenericAttachmentModel(id: item.id, name: fileName, documentType: item.documentType));
      }
    } catch (error) {
      print(error);
    }
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    await medicalGasInspectionProvider.updatedDeliveryNotes(model: formModel).then((status) async {
      Navigator.pop(context);
      if (status) {
        Navigator.pop(context, true);
        if (formModel.isSubmitted == true) {
          AllRequestsProvider allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
          allRequestsProvider.reset();
          await allRequestsProvider.getAllRequests(context, typeTransaction: 14);
        }
      }
    });
  }

  Widget itemQuantityFieldWidget({
    required int index,
    required MedicalGasRequestDetailModel model,
    required BuildContext context,
  }) {
    final border = OutlineInputBorder(
      borderRadius: BorderRadius.circular(4),
      borderSide: const BorderSide(color: AppColor.white70, width: 0),
    );

    return _ItemRowLayout(
      left: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          model.itemName!.bodyText2(context).custom(
                color: context.isDark ? Colors.white : AppColor.white936,
                fontWeight: FontWeight.w500,
              ),
          'Req Qty ${model.requestedQuantity?.toStringAsFixed(0)}'.bodyText2(context).custom(
                color: context.isDark ? Colors.white : AppColor.white936,
                fontWeight: FontWeight.w500,
              ),
        ],
      ),
      right: TextFormField(
        keyboardType: TextInputType.number,
        initialValue: model.deliveredQuantity != null ? model.deliveredQuantity?.toStringAsFixed(0) : '',
        validator: (value) {
          if (value == null || value.trim().isEmpty) {
            return "This field is required";
          }

          final intVal = int.tryParse(value);
          if (intVal == null) {
            return "Enter a valid number";
          }

          // if (intVal <= 0) {
          //   return "Value must be greater than 0";
          // }

          return null;
        },
        decoration: InputDecoration(
          isDense: true,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 5.toScreenWidth,
            vertical: 6, // keeps normal height ~30
          ),
          filled: true,
          fillColor: AppColor.dropDownBackground(context),
          // fillColor: AppColor.fieldBgColor(context),
          border: border,
          enabledBorder: border,
          focusedBorder: border,
          errorStyle: const TextStyle(
            height: 1.2, // controls extra height when error appears
            fontSize: 12,
          ),
        ),
        // decoration: InputDecoration(
        //   contentPadding: EdgeInsets.symmetric(horizontal: 5.toScreenWidth),
        //   filled: true,
        //   fillColor: AppColor.fieldBgColor(context),
        //   constraints: BoxConstraints(
        //     maxHeight: 40.toScreenHeight,
        //   ),
        //   border: border,
        //   enabledBorder: border,
        //   focusedBorder: border,
        // ),
        onChanged: (value) {
          model.deliveredQuantity = int.tryParse(value);
        },
      ),
    );
  }
}

class _ItemRowLayout extends StatelessWidget {
  final Widget left;
  final Widget right;

  const _ItemRowLayout({
    required this.left,
    required this.right,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(child: left), // Items column
        SizedBox(
          width: 100.toScreenWidth, // Delivered Qty column
          child: right,
        ),
      ],
    );
  }
}
