// import 'package:flutter/material.dart';
// import 'package:fluttertoast/fluttertoast.dart';
// import 'package:provider/provider.dart';
// import 'package:test_sa/controllers/providers/api/user_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/lookup.dart';
// import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.dart';
// import 'package:test_sa/models/ppm/ppm_calibration_tools.dart';
// import 'package:test_sa/models/service_request/supplier_details.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/single_item_drop_down_menu.dart';
// import 'package:test_sa/providers/loading_list_notifier.dart';
// import 'package:test_sa/providers/ppm_service_provider.dart';
// import 'package:test_sa/providers/work_order/vendor_provider.dart';
// import 'package:test_sa/service_request_latest/utilities/service_request_utils.dart';
// import 'package:test_sa/views/widgets/pentry/calibration_tool_asset_picker.dart';
//
// import '../../../../../new_views/app_style/app_color.dart';
// import '../../../../widgets/date_and_time/date_picker.dart';
//
// class PpmExternalDetailsForm extends StatefulWidget {
//   final List<PreventiveVisitSuppliers>? models;
//
//   const PpmExternalDetailsForm({Key? key, this.models = const <PreventiveVisitSuppliers>[]}) : super(key: key);
//
//   @override
//   State<PpmExternalDetailsForm> createState() => _PpmExternalDetailsFormState();
// }
//
// class _PpmExternalDetailsFormState extends State<PpmExternalDetailsForm> {
//   final TextEditingController _workingHoursController = TextEditingController();
//
//   @override
//   Widget build(BuildContext context) {
//     return ListView.builder(
//       itemCount: widget.models!.length + 1,
//       padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 16),
//       itemBuilder: (context, index) {
//         if (index == widget.models!.length) {
//           return AppFilledButton(
//             label: "Add More External Details".addTranslation,
//             maxWidth: true,
//             textColor: AppColor.black10,
//             buttonColor: context.isDark ? AppColor.neutral60 : AppColor.white10,
//             icon: Icon(Icons.add_circle, color: AppColor.blueStatus(context)),
//             showIcon: true,
//             onPressed: () async {
//               // if (widget.models?.isNotEmpty ?? false) {
//               //   if (widget.models!.last.assetId == null) {
//               //     await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.assetNumber}");
//               //     return;
//               //   }
//               //   if (widget.models!.last.calibrationDateOfTesters == null) {
//               //     await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.date}");
//               //     return;
//               //   }
//               // }
//               // widget.models!.add(PpmCalibrationTools(id: 0));
//               // setState(() {});
//             },
//           );
//         }
//         final model = widget.models![index];
//         // _workingHoursController.text = model.workingHours != null ? model.workingHours.toString() : '';
//         return Container(
//           padding: const EdgeInsets.all(16),
//           margin: EdgeInsets.only(bottom: 16.toScreenHeight),
//           decoration: BoxDecoration(
//             color: AppColor.background(context),
//             borderRadius: BorderRadius.circular(20),
//             boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 14)],
//           ),
//           child: Column(
//             crossAxisAlignment: CrossAxisAlignment.start,
//             children: [
//               Row(
//                 mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                 children: [
//                   (index == 0 ? "1 /4 . External Details" : "").heading5(context),
//                   "trash".toSvgAsset(height: 20, width: 15).onPress(() {
//                     widget.models!.remove(model);
//
//                     setState(() {});
//                   }),
//                 ],
//               ),
//               16.height,
//               SingleItemDropDownMenu<SupplierDetails, VendorProvider>(
//                 context: context,
//                 title: context.translation.supplier,
//                 initialValue: model.supplier,
//                 backgroundColor: AppColor.neutral100,
//                 showAsBottomSheet: true,
//                 onSelect: (supplier) {
//                   if (supplier != null) {
//                     model.supplier = supplier;
//                     print('supplier dtails is ${supplier.toJson()}');
//                     setState(() {});
//                   }
//                 },
//               ),
//               8.height,
//               SingleItemDropDownMenu<SuppPersons, NullableLoadingProvider>(
//                 context: context,
//                 title: context.translation.supplierEngineer,
//                 enabled: model.suppPerson != null,
//                 backgroundColor: AppColor.neutral100,
//                 initialValue: model.suppPerson,
//                 staticData: model.supplier?.suppPersons,
//                 showAsBottomSheet: true,
//                 onSelect: (suppPerson) {
//                   if (suppPerson != null) {
//                     model.suppPerson = suppPerson;
//                     print('supply person is ${model.suppPerson?.toJson()}');
//                   }
//                 },
//               ),
//               8.height,
//               AppTextFormField(
//                 labelText: "Telephone",
//                 initialValue: model.supplier?.telephones != null && model.supplier!.telephones!.isNotEmpty ? (model.supplier?.telephones?[0].telephone ?? "").toString() : '',
//                 textAlign: TextAlign.center,
//                 backgroundColor: AppColor.neutral100,
//                 style: Theme.of(context).textTheme.titleMedium,
//                 textInputType: TextInputType.number,
//                 onChange: (value) {
//                   model.supplier?.telephones?[0].telephone = value;
//                 },
//               ),
//               8.height,
//               Row(
//                 mainAxisSize: MainAxisSize.min,
//                 children: [
//                   ADatePicker(
//                     label: context.translation.startTime,
//                     hideShadow: true,
//                     backgroundColor: AppColor.neutral100,
//                     date: model.startDateTime,
//                     formatDateWithTime: true,
//                     onDatePicker: (selectedDate) {
//                       showTimePicker(
//                         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,
//                           );
//                           setState(() {
//                             model.startDateTime = selectedDateTime;
//                           });
//                           model.endDateTime = null;
//                           _workingHoursController.clear();
//                           ServiceRequestUtils.calculateAndAssignWorkingHours(
//                             startTime: model.startDateTime,
//                             endTime: model.endDateTime,
//                             workingHoursController: _workingHoursController,
//                             updateModel: (hours) {
//                               model.workingHours = hours;
//                             },
//                           );
//                         }
//                       });
//                     },
//                   ).expanded,
//                   8.width,
//                   ADatePicker(
//                     label: context.translation.endTime,
//                     hideShadow: true,
//                     backgroundColor: AppColor.neutral100,
//                     date: model.endDateTime,
//                     formatDateWithTime: true,
//                     onDatePicker: (selectedDate) {
//                       showTimePicker(
//                         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 (model.startDateTime != null && selectedDateTime.isBefore(model.startDateTime!)) {
//                             "End Date time must be greater then start date".showToast;
//                             return;
//                           }
//                           model.endDateTime = selectedDateTime;
//                           setState(() {});
//                           ServiceRequestUtils.calculateAndAssignWorkingHours(
//                             startTime: model.startDateTime,
//                             endTime: model.endDateTime,
//                             workingHoursController: _workingHoursController,
//                             updateModel: (hours) {
//                               model.workingHours = hours;
//                             },
//                           );
//                         }
//                       });
//                     },
//                   ).expanded,
//                 ],
//               ),
//               8.height,
//               AppTextFormField(
//                 labelText: context.translation.workingHours,
//                 backgroundColor: AppColor.neutral80,
//                 controller: _workingHoursController,
//                 suffixIcon: "clock".toSvgAsset(width: 20, color: context.isDark ? AppColor.neutral10 : null).paddingOnly(end: 16),
//                 // initialValue: model.workingHours != null ? model.workingHours.toString() : '',
//                 textAlign: TextAlign.center,
//                 labelStyle: AppTextStyles.textFieldLabelStyle,
//                 enable: false,
//                 showShadow: false,
//                 style: Theme.of(context).textTheme.titleMedium,
//               ),
//               8.height,
//             ],
//           ),
//         );
//       },
//     );
//   }
// }

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/ppm_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/plan_preventive_visit/plan_preventive_visit_model.dart';
import 'package:test_sa/models/service_request/supplier_details.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/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/providers/work_order/vendor_provider.dart';
import 'package:test_sa/service_request_latest/utilities/service_request_utils.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';

class PpmExternalDetailsForm extends StatefulWidget {
  final List<PreventiveVisitSuppliers>? models;

  const PpmExternalDetailsForm({Key? key, this.models = const <PreventiveVisitSuppliers>[]}) : super(key: key);

  @override
  State<PpmExternalDetailsForm> createState() => _PpmExternalDetailsFormState();
}

class _PpmExternalDetailsFormState extends State<PpmExternalDetailsForm> {
  bool isLoading = false;

//TODO add loader when adding or deleting item..

  void _addNewEntry() {
    setState(() {
      // isLoading = true;
      widget.models!.add(PreventiveVisitSuppliers(id: 0));
      // Future.delayed(Duration(seconds: 1)).whenComplete(() {
      //   setState(() {
      //     isLoading = false;
      //   });
      // });
    });
  }

  void _removeEntry(int index) {
    setState(() {
      isLoading = true;
      widget.models!.removeAt(index);
      // isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    final ppmProvider = Provider.of<PpmProvider>(context, listen: false);
    return ListView.builder(
      itemCount: widget.models!.length + 1,
      padding: const EdgeInsets.all(16),
      itemBuilder: (context, index) {
        if (index == widget.models!.length) {
          return Visibility(
            visible: !ppmProvider.isReadOnly,
            child: AppFilledButton(
              label: "Add More External Details".addTranslation,
              maxWidth: true,
              textColor: AppColor.black10,
              buttonColor: context.isDark ? AppColor.neutral60 : AppColor.white10,
              icon: Icon(Icons.add_circle, color: AppColor.blueStatus(context)),
              showIcon: true,
              onPressed: _addNewEntry,
            ),
          );
        }
        // return !isLoading
        //     ?
        return ExternalDetailItem(
          model: widget.models![index],
          index: index,
          onRemove: () => _removeEntry(index),
        );
        // : const ALoading();
      },
    );
  }
}

class ExternalDetailItem extends StatefulWidget {
  final PreventiveVisitSuppliers model;
  final VoidCallback onRemove;
  final int index;

  const ExternalDetailItem({
    Key? key,
    required this.model,
    required this.onRemove,
    required this.index,
  }) : super(key: key);

  @override
  State<ExternalDetailItem> createState() => _ExternalDetailItemState();
}

class _ExternalDetailItemState extends State<ExternalDetailItem> {
  TextEditingController? controller;
  PpmProvider? _ppmProvider;

  @override
  void initState() {
    controller = TextEditingController(text: widget.model.workingHours != null ? widget.model.workingHours.toString() : '');
    _ppmProvider= Provider.of<PpmProvider>(context,listen:false);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      margin: EdgeInsets.only(bottom: 16.toScreenHeight),
      decoration: BoxDecoration(
        color: AppColor.background(context),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 14)],
      ),
      child: IgnorePointer(
        ignoring: _ppmProvider!.isReadOnly,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                (widget.index == 0 ? "1 /4 . External Details" : "").heading5(context),
                Container(
                  height: 32,
                  width: 32,
                  padding: const EdgeInsets.all(6),
                  child: "trash".toSvgAsset(height: 20, width: 20),
                ).onPress(() {
                  widget.onRemove();
                }),
              ],
            ),
            16.height,
            SingleItemDropDownMenu<SupplierDetails, VendorProvider>(
              context: context,
              title: context.translation.supplier,
              initialValue: widget.model.supplier,
              backgroundColor: AppColor.neutral100,
              showAsBottomSheet: true,
              showShadow: false,
              onSelect: (supplier) {
                if (supplier != null) {
                  setState(() {
                    widget.model.supplier = supplier;
                  });
                }
              },
            ),
            8.height,
            SingleItemDropDownMenu<SuppPersons, NullableLoadingProvider>(
              context: context,
              title: context.translation.supplierEngineer,
              enabled: widget.model.supplier != null,
              backgroundColor: AppColor.neutral100,
              initialValue: widget.model.suppPerson,
              staticData: widget.model.supplier?.suppPersons,
              showAsBottomSheet: true,
              showShadow: false,
              onSelect: (suppPerson) {
                if (suppPerson != null) {
                  widget.model.suppPerson = suppPerson;
                }
              },
            ),
            8.height,
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                ADatePicker(
                  label: context.translation.startTime,
                  hideShadow: true,
                  backgroundColor: AppColor.neutral100,
                  date: widget.model.startDateTime,
                  formatDateWithTime: true,
                  onDatePicker: (selectedDate) {
                    showTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    ).then((selectedTime) {
                      if (selectedTime != null) {
                        DateTime selectedDateTime = DateTime(
                          selectedDate.year,
                          selectedDate.month,
                          selectedDate.day,
                          selectedTime.hour,
                          selectedTime.minute,
                        );
                        setState(() {
                          widget.model.startDateTime = selectedDateTime;
                        });
                        widget.model.endDateTime = null;
                        controller?.clear();
                        ServiceRequestUtils.calculateAndAssignWorkingHours(
                          startTime: widget.model.startDateTime,
                          endTime: widget.model.endDateTime,
                          workingHoursController: controller!,
                          updateModel: (hours) {
                            widget.model.workingHours = hours;
                          },
                        );
                      }
                    });
                  },
                ).expanded,
                8.width,
                ADatePicker(
                  label: context.translation.endTime,
                  hideShadow: true,
                  backgroundColor: AppColor.neutral100,
                  date: widget.model.endDateTime,
                  formatDateWithTime: true,
                  onDatePicker: (selectedDate) {
                    showTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    ).then((selectedTime) {
                      if (selectedTime != null) {
                        DateTime selectedDateTime = DateTime(
                          selectedDate.year,
                          selectedDate.month,
                          selectedDate.day,
                          selectedTime.hour,
                          selectedTime.minute,
                        );
                        if (widget.model.startDateTime != null && selectedDateTime.isBefore(widget.model.startDateTime!)) {
                          "End Date time must be greater than start date".showToast;
                          return;
                        }
                        setState(() {
                          widget.model.endDateTime = selectedDateTime;
                        });
                        ServiceRequestUtils.calculateAndAssignWorkingHours(
                          startTime: widget.model.startDateTime,
                          endTime: widget.model.endDateTime,
                          workingHoursController: controller!,
                          updateModel: (hours) {
                            widget.model.workingHours = hours;
                          },
                        );
                      }
                    });
                  },
                ).expanded,
              ],
            ),
            8.height,
            AppTextFormField(
              labelText: context.translation.workingHours,
              backgroundColor: AppColor.neutral80,
              controller: controller,
              textAlign: TextAlign.center,
              enable: false,
              showShadow: false,
              style: Theme.of(context).textTheme.titleMedium,
            ),
            8.height,
          ],
        ),
      ),
    );
  }
}
