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/supp_engineer_work_orders.dart';
import 'package:test_sa/models/service_request/supplier_details.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.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/views/pages/user/requests/add_supplier_engineer_bottom_sheet.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/item_views/info_header_widget.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.only(left: 16, right: 16, top: 8, bottom: 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.headingTextColor(context),
              // buttonColor: context.isDark ? AppColor.neutral60 : AppColor.white10,
              buttonColor: AppColor.addItemButtonColor(context),
              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;
  final String? createdDate;

  const ExternalDetailItem({
    Key? key,
    required this.model,
    required this.onRemove,
    required this.index,
    this.createdDate,
  }) : 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: [
                  InfoHeader16Widget((widget.index == 0 ? "1 /4 . External Details" : "")),
                // (widget.index == 0 ? "1 /4 . External Details" : "").heading5(context).custom(color: AppColor.textStyleColor(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.fieldBgColor(context),
              showAsBottomSheet: true,
              showShadow: false,
              showCancel: true,
              onSelect: (supplier) {
                setState(() {
                  widget.model.supplier = supplier;
                  widget.model.suppPerson = null;
                });
              },
            ),
            8.height,
            Row(
              children: [
                SingleItemDropDownMenu<SuppPersons, NullableLoadingProvider>(
                  context: context,
                  title: context.translation.supplierEngineer,
                  enabled: widget.model.supplier != null,
                  backgroundColor: AppColor.fieldBgColor(context),
                  initialValue: widget.model.suppPerson,
                  staticData: widget.model.supplier?.suppPersons,
                  showAsBottomSheet: true,
                  showShadow: false,
                  onSelect: (suppPerson) {
                    if (suppPerson != null) {
                      widget.model.suppPerson = suppPerson;
                    }
                  },
                ).expanded,
                8.width,
                Container(
                  height: 56.toScreenHeight,
                  width: 60.toScreenWidth,
                  decoration: BoxDecoration(
                    color: AppColor.fieldBgColor(context),
                    borderRadius: BorderRadius.circular(10),
                    //boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
                  ),
                  child: Icon(Icons.add, color: context.isDark ? null : AppColor.neutral60),
                ).onPress(() async {
                  if (widget.model.supplier == null) {
                    "Please select supplier".showToast;
                    return;
                  }
                  SuppEngineerWorkOrders? suppEngineer = (await showModalBottomSheet(
                    context: context,
                    useSafeArea: true,
                    isScrollControlled: true,
                    backgroundColor: Colors.transparent,
                    builder: (context) => AddSupplierEngineerBottomSheet(widget.model.supplier!.id!.toInt()),
                  )) as SuppEngineerWorkOrders?;
                  if (suppEngineer == null) return;
                  widget.model.supplier?.suppPersons ??= [];
                  widget.model.supplier?.suppPersons!.add(SuppPersons.fromJson(suppEngineer.toJson()));
                  // requestDetailProvider.activityMaintenanceHelperModel?.supplier?.suppPersons?.add(SuppPersons.fromJson(suppEngineer.toJson()));
                  widget.model.suppPerson = SuppPersons.fromJson(suppEngineer.toJson());
                  setState(() {});
                }),
              ],
            ),
            8.height,
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                ADatePicker(
                  label: context.translation.startTime,
                  hideShadow: true,
                  backgroundColor: AppColor.fieldBgColor(context),
                  date: widget.model.startDateTime,
                  formatDateWithTime: true,
                  from: DateTime.tryParse(_ppmProvider?.planPreventiveVisit?.createdDate ?? ''),
                  onDatePicker: (selectedDate) {
                    showThemedTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    ).then((selectedTime) {
                      if (selectedTime != null) {
                        DateTime selectedDateTime = DateTime(selectedDate.year, selectedDate.month, selectedDate.day, selectedTime.hour, selectedTime.minute);
                        if (DateTime.tryParse(_ppmProvider?.planPreventiveVisit?.createdDate ?? '') != null &&
                            selectedDateTime.isBefore(DateTime.tryParse(_ppmProvider?.planPreventiveVisit?.createdDate ?? '')!)) {
                          "Start time is before the request time.".showToast;
                          selectedTime = null;
                          return;
                        }
                        if (selectedDateTime.isAfter(DateTime.now())) {
                          "Start time is after than current time".showToast;
                          selectedTime = null;
                          return;
                        }
                        setState(() {
                          widget.model.startDateTime = selectedDateTime;
                        });
                        widget.model.endDateTime = null;
                        controller?.clear();
                        CMRequestUtils.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.fieldBgColor(context),
                  date: widget.model.endDateTime,
                  enable: widget.model.startDateTime != null,
                  formatDateWithTime: true,
                  from: DateTime.tryParse(_ppmProvider?.planPreventiveVisit?.createdDate ?? ''),
                  onDatePicker: (selectedDate) {
                    showThemedTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    ).then((selectedTime) {
                      if (selectedTime != null) {
                        selectedDate = selectedDate.add(Duration(hours: selectedTime.hour, minutes: selectedTime.minute));
                        bool isBeforeCurrentTime = selectedDate.isBefore(DateTime.now());
                        bool isAfterStartTime = selectedDate.isAfter(widget.model.startDateTime!);
                        if (!isBeforeCurrentTime) {
                          "Please select a time before the current time.".showToast;
                          return;
                        }
                        if (!isAfterStartTime) {
                          "End Date time must be greater then start date".showToast;
                          return;
                        }

                        setState(() {
                          widget.model.endDateTime = selectedDate;
                        });
                        CMRequestUtils.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.fieldBgColor(context),
              controller: controller,
              textAlign: TextAlign.center,
              enable: false,
              showShadow: false,
              style: Theme.of(context).textTheme.titleMedium,
            ),
            8.height,
          ],
        ),
      ),
    );
  }
}
