import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/status_drop_down/report/service_report_repair_location_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_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/modules/cm_module/service_request_detail_provider.dart';
import 'package:test_sa/modules/cm_module/utilities/service_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/forms/maintenance_request/components/assistant_employee_list.dart';
import 'package:test_sa/new_views/app_style/app_color.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/service_request_providers/last_situation_provider.dart';
import 'package:test_sa/views/widgets/timer/app_timer.dart';

class InternalMaintenanceRequest extends StatefulWidget {
  static const String id = "/add-internal-activity";

  const InternalMaintenanceRequest({Key? key}) : super(key: key);

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

class _InternalMaintenanceRequestState extends State<InternalMaintenanceRequest> with TickerProviderStateMixin {
  ServiceRequestDetailProvider? _requestDetailProvider;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _workingHoursController = TextEditingController();
  final TextEditingController _travellingHoursController = TextEditingController();
  Lookup statusLookup = Lookup.fromJson({"id": 5619, "name": "New", "value": 1});

  @override
  void initState() {
    _requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _travellingHoursController.text =
          _requestDetailProvider?.activityMaintenanceHelperModel?.travelHours != null ? _requestDetailProvider!.activityMaintenanceHelperModel!.travelHours.toString() : '';
    });
    // _isLoading = true;
  }

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

  @override
  Widget build(BuildContext context) {
    return Consumer<ServiceRequestDetailProvider>(builder: (context, requestDetailProvider, child) {
      double totalWorkingHours = _requestDetailProvider?.activityMaintenanceHelperModel?.activityMaintenanceTimers
              ?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endTime!).difference(DateTime.parse(item.startTime!)).inSeconds) ??
          0;

      bool enableTimer = (requestDetailProvider.lastVisitedRequestActivityId == -1 || requestDetailProvider.activityMaintenanceHelperModel?.id == 0)
          ? true
          : requestDetailProvider.activityMaintenanceHelperModel?.id == requestDetailProvider.lastVisitedRequestActivityId;

      return SingleChildScrollView(
        child: IgnorePointer(
          ignoring: _requestDetailProvider!.isReadOnlyRequest,
          child: Column(
            children: [
              Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // SingleItemDropDownMenu<Lookup, ActivityStatusProvider>(
                    //   context: context,
                    //   height: 56.toScreenHeight,
                    //   title: context.translation.activityStatus,
                    //   showShadow: false,
                    //   backgroundColor: AppColor.neutral100,
                    //   initialValue: requestDetailProvider.activityMaintenanceHelperModel?.activityStatus,
                    //   onSelect: (status) {
                    //     print('status i got is ${status?.toJson()}');
                    //     requestDetailProvider.activityMaintenanceHelperModel?.activityStatus = status;
                    //   },
                    // ),
                    // 8.height,
                    SingleItemDropDownMenu<Lookup, LastSituationProvider>(
                      context: context,
                      height: 56.toScreenHeight,
                      title: context.translation.activityStatus,
                      showShadow: false,
                      // backgroundColor: AppColor.neutral100,
                      backgroundColor: AppColor.fieldBgColor(context),
                      showAsBottomSheet: true,
                      initialValue: requestDetailProvider.activityMaintenanceHelperModel?.activityStatus,
                      onSelect: (status) {
                        if (status != null) {
                          requestDetailProvider.activityMaintenanceHelperModel?.activityStatus = status;
                          setState(() {});
                        }
                      },
                    ),
                    8.height,
                    // AppTimerPicker(
                    //   label: context.translation.timer,
                    //   timer: requestDetailProvider.activityMaintenanceHelperModel?.activityTimePicker,
                    //   enabled: enableTimer,
                    //   // timerList: requestDetailProvider.activityMaintenanceHelperModel?.timerModelList ?? [],
                    //   onPick: (time) {
                    //     requestDetailProvider.activityMaintenanceHelperModel?.activityTimePicker = time;
                    //   },
                    // ),
                    // 8.height,
                    AppTimer(
                      label: context.translation.timer,
                      timer: requestDetailProvider.activityMaintenanceHelperModel?.activityMaintenanceTimerModel,
                      enabled: enableTimer,
                      pickerTimer: requestDetailProvider.activityMaintenanceHelperModel?.activityTimePicker,
                      pickerFromDate: requestDetailProvider.currentWorkOrder?.data?.requestedDate,
                      onPick: (time) {
                        requestDetailProvider.activityMaintenanceHelperModel?.activityTimePicker = time;
                      },
                      timerProgress: (isRunning) {},
                      onChange: (timer) async {
                        requestDetailProvider.activityMaintenanceHelperModel?.activityMaintenanceTimerModel = timer;
                        if (timer.startAt != null && timer.endAt != null) {
                          requestDetailProvider.activityMaintenanceHelperModel?.timerModelList = requestDetailProvider.activityMaintenanceHelperModel?.timerModelList ?? [];
                          requestDetailProvider.activityMaintenanceHelperModel?.timerModelList!.add(timer);
                        }
                        return true;
                      },
                    ),
                    // Row(
                    //   mainAxisSize: MainAxisSize.min,
                    //   children: [
                    //     ADatePicker(
                    //       label: context.translation.startTime,
                    //       hideShadow: true,
                    //       backgroundColor: AppColor.neutral100,
                    //       date: requestDetailProvider.activityMaintenanceHelperModel?.startTime,
                    //       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,
                    //             );
                    //             requestDetailProvider.activityMaintenanceHelperModel?.startTime = selectedDateTime;
                    //             requestDetailProvider.activityMaintenanceHelperModel?.endTime = null;
                    //             requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                    //             _workingHoursController.clear();
                    //             ServiceRequestUtils.calculateAndAssignWorkingHours(
                    //               startTime: requestDetailProvider.activityMaintenanceHelperModel!.startTime,
                    //               endTime: requestDetailProvider.activityMaintenanceHelperModel!.endTime,
                    //               workingHoursController: _workingHoursController,
                    //               updateModel: (hours) {
                    //                 requestDetailProvider.activityMaintenanceHelperModel?.workingHour = hours;
                    //               },
                    //             );
                    //           }
                    //         });
                    //       },
                    //     ).expanded,
                    //     8.width,
                    //     ADatePicker(
                    //       label: context.translation.endTime,
                    //       hideShadow: true,
                    //       backgroundColor: AppColor.neutral100,
                    //       date: requestDetailProvider.activityMaintenanceHelperModel?.endTime,
                    //       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 (requestDetailProvider.activityMaintenanceHelperModel!.startTime != null &&
                    //                 selectedDateTime.isBefore(requestDetailProvider.activityMaintenanceHelperModel!.startTime!)) {
                    //               "End Date time must be greater then start date".showToast;
                    //               return;
                    //             }
                    //             requestDetailProvider.activityMaintenanceHelperModel?.endTime = selectedDateTime;
                    //             requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                    //             ServiceRequestUtils.calculateAndAssignWorkingHours(
                    //               startTime: requestDetailProvider.activityMaintenanceHelperModel!.startTime,
                    //               endTime: requestDetailProvider.activityMaintenanceHelperModel!.endTime,
                    //               workingHoursController: _workingHoursController,
                    //               updateModel: (hours) {
                    //                 requestDetailProvider.activityMaintenanceHelperModel?.workingHour = hours;
                    //               },
                    //             );
                    //           }
                    //         });
                    //       },
                    //     ).expanded,
                    //   ],
                    // ),
                    8.height,
                    if (totalWorkingHours > 0.0) ...[
                      Container(
                        height: 56.toScreenHeight,
                        padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth),
                        alignment: Alignment.centerLeft,
                        decoration: BoxDecoration(
                          color:  AppColor.fieldBgColor(context),
                          borderRadius: BorderRadius.circular(10),
                          boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10)],
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Total Working Time",
                              style: Theme.of(context).textTheme.bodySmall?.copyWith(color: context.isDark ? null : AppColor.neutral20, fontWeight: FontWeight.w500),
                            ),
                            Text(
                              " ${ServiceRequestUtils.formatTimerDuration(totalWorkingHours.round())}",
                              style: Theme.of(context).textTheme.bodyMedium,
                            ),
                          ],
                        ),
                      ),
                      8.height,
                    ],
                    // if (totalWorkingHours > 0.0) ...[
                    // 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: requestDetailProvider.activityMaintenanceHelperModel?.workingHour != null ? requestDetailProvider.activityMaintenanceHelperModel?.workingHour.toString() : '',
                    //   textAlign: TextAlign.center,
                    //   labelStyle: AppTextStyles.textFieldLabelStyle,
                    //   enable: false,
                    //   showShadow: false,
                    //   style: Theme.of(context).textTheme.titleMedium,
                    // ),
                    // 8.height,
                    // ],
                    AppTextFormField(
                      labelText: context.translation.travelingHours,
                      controller: _travellingHoursController,
                         backgroundColor:AppColor.fieldBgColor(context),
                      showShadow: false,
                      labelStyle: AppTextStyles.textFieldLabelStyle,
                      suffixIcon: "clock".toSvgAsset(width: 20, color: context.isDark ? AppColor.neutral10 : null).paddingOnly(end: 16),
                      initialValue: requestDetailProvider.activityMaintenanceHelperModel?.travelHours?.toString(),
                      textInputType: const TextInputType.numberWithOptions(decimal: true),
                      onChange: (value) {
                        requestDetailProvider.activityMaintenanceHelperModel?.travelHours = num.parse(value); // int.tryParse(value);
                      },
                      // contentPadding: EdgeInsets.symmetric(vertical: 18.toScreenHeight, horizontal: 16.toScreenWidth),
                      onSaved: (value) {
                        requestDetailProvider.activityMaintenanceHelperModel?.travelHours = value as num?;
                      },
                    ),
                    16.height,
                    repairLocationWidget(context, requestDetailProvider),
                    16.height,
                    AppTextFormField(
                      labelText: context.translation.assignedEmployee,
                      backgroundColor: AppColor.fieldBgColor(context),
                      initialValue: requestDetailProvider.activityMaintenanceHelperModel?.assignedEmployee?.userName,
                      textAlign: TextAlign.center,
                      labelStyle: AppTextStyles.textFieldLabelStyle,
                      showShadow: false,
                      enable: false,
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    8.height,
                    AppTextFormField(
                      initialValue: requestDetailProvider.activityMaintenanceHelperModel?.technicalComment,
                      labelText: context.translation.technicalComment,
                         backgroundColor:AppColor.fieldBgColor(context),
                      showShadow: false,
                      labelStyle: AppTextStyles.textFieldLabelStyle,
                      alignLabelWithHint: true,
                      textInputType: TextInputType.multiline,
                      onChange: (value) {
                        requestDetailProvider.activityMaintenanceHelperModel?.technicalComment = value;
                      },
                      onSaved: (value) {
                        requestDetailProvider.activityMaintenanceHelperModel?.technicalComment = value;
                      },
                    ),
                  ],
                ),
              ).toShadowContainer(context).paddingOnly(start: 13, end: 14, top: 12),
              ServiceRequestAssistantEmployeeList(
                assetId: requestDetailProvider.currentWorkOrder?.data?.asset?.id,
                assistantEmployeeList: requestDetailProvider.activityMaintenanceHelperModel?.assistantEmployList,
                onListChanged: (updatedList) {
                  setState(() {
                    requestDetailProvider.activityMaintenanceHelperModel?.assistantEmployList = updatedList;
                  });
                },
              ),
              // const AssistantEmployeeCard().toShadowContainer(context, paddingObject: const EdgeInsets.symmetric(horizontal: 16)).paddingOnly(start: 13, end: 14, top: 12),
              100.height,
            ],
          ),
        ),
      );
    });
  }

  Widget repairLocationWidget(BuildContext context, ServiceRequestDetailProvider requestDetailProvider) {
    return Consumer<ServiceReportRepairLocationProvider>(builder: (cxt, snapshot, _) {
      try {
        requestDetailProvider.activityMaintenanceHelperModel?.repairLocation ??= snapshot.reasons?.first;
      } catch (ex) {
        print("snapshot.items:${snapshot.reasons?.length}");
      }

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          context.translation.repairLocation.bodyText(context).custom(color: AppColor.textColor(context)),
          8.height,
          Wrap(
            runSpacing: 8,
            spacing: 8,
            children: [
              for (var element in snapshot.reasons ?? [])
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      width: 24,
                      height: 24,
                      child: Radio(
                          value: element,
                          activeColor: Colors.red,
                          fillColor: WidgetStateColor.resolveWith((states) {
                            if (states.contains(WidgetState.selected)) return AppColor.primary10;
                            return AppColor.neutral130;
                          }),
                          groupValue: requestDetailProvider.activityMaintenanceHelperModel?.repairLocation,
                          onChanged: (state) {
                            setState(() {
                              requestDetailProvider.activityMaintenanceHelperModel?.repairLocation = element;
                            });
                          }),
                    ),
                    8.width,
                    Text(element.name ?? '', style: AppTextStyles.tinyFont.copyWith(color: AppColor.neutral120)),
                  ],
                )
            ],
          ).toShimmer(isShow: snapshot.isLoading,context: context),
        ],
      );
    });
  }
}
