import 'package:flutter/material.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/helper/utils.dart';
import 'package:test_sa/models/new_models/work_order_detail_model.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/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/status/report/service_report_assistant_employee_menu.dart';

class AssistantEmployeeCard extends StatefulWidget {
  const AssistantEmployeeCard({super.key});

  @override
  State<AssistantEmployeeCard> createState() => _AssistantEmployeeCardState();
}

class _AssistantEmployeeCardState extends State<AssistantEmployeeCard> {
  bool status = false;
  final TextEditingController _workingHoursController = TextEditingController(text: '');
  bool isCurrentUserIsAssistantEmp = false;
  bool isExpanded = false;

  @override
  void initState() {
    // TODO: implement initState
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInitialData();
    });
    super.initState();
  }

  Future<void> getInitialData() async {
    final user = Provider.of<UserProvider>(context, listen: false).user!;
    ServiceRequestDetailProvider requestDetailProvider = Provider.of<ServiceRequestDetailProvider>(context, listen: false);
    if (requestDetailProvider.isReadOnlyRequest) {
      isExpanded = true;
      setState(() {});
    }
    isCurrentUserIsAssistantEmp = (user.userID != requestDetailProvider.currentWorkOrder?.data?.assignedEmployee?.userId);

    // if (isCurrentUserIsAssistantEmp) {
    //   // _subWorkOrders.assistantEmployees = [widget.workOrder.assistantEmployees?.first?.copyWith(id: 0)];
    // }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _workingHoursController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<ServiceRequestDetailProvider>(builder: (context, requestDetailProvider, child) {
      return Column(
        children: [
          SizedBox(
            height: 56.toScreenHeight,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                context.translation.assistantEmployee.bodyText(context).custom(color: AppColor.black20),
                Icon(isExpanded ? Icons.keyboard_arrow_up_rounded : Icons.keyboard_arrow_down_rounded),
              ],
            ),
          ).onPress(() {
            setState(() {
              isExpanded = !isExpanded;
            });
          }),
          isExpanded
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    ServiceReportAssistantEmployeeMenu(
                      title: context.translation.select,
                      backgroundColor: AppColor.neutral100,
                      assetId: requestDetailProvider.currentWorkOrder!.data!.asset!.id!,
                      initialValue: (requestDetailProvider.activityMaintenanceHelperModel?.assistantEmployees?.isNotEmpty ?? false)
                          ? requestDetailProvider.activityMaintenanceHelperModel?.assistantEmployees?.first
                          : null,
                      //TODO add check...
                      // enable: !isCurrentUserIsAssistantEmp,
                      onSelect: (employee) {
                        if (employee == null) {
                          requestDetailProvider.activityMaintenanceHelperModel?.assistantEmployees = [];
                        } else {
                          requestDetailProvider.activityMaintenanceHelperModel?.assistantEmployees = [employee.copyWith(id: 0)];
                          requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.user = AssignedEmployee(userId: employee.user?.id, userName: employee.user?.name);
                        }
                      },
                    ),
                    8.height,
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        ADatePicker(
                          label: context.translation.startTime,
                          hideShadow: true,
                          backgroundColor: AppColor.neutral100,
                          from: requestDetailProvider.currentWorkOrder?.data?.requestedDate,
                          date: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.startDate,
                          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.currentWorkOrder?.data?.requestedDate != null && selectedDateTime.isBefore(requestDetailProvider.currentWorkOrder!.data!.requestedDate!)) {
                                  "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;
                                }

                                requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.startDate = selectedDateTime;
                                requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                                ServiceRequestUtils.calculateAndAssignWorkingHours(
                                    startTime: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.startDate,
                                    endTime: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.endDate,
                                    workingHoursController: _workingHoursController,
                                    updateModel: (hours) {
                                      requestDetailProvider.activityMaintenanceHelperModel!.modelAssistantEmployees!.workingHours = hours;
                                    });
                              }
                            });
                          },
                        ).expanded,
                        8.width,
                        ADatePicker(
                          label: context.translation.endTime,
                          hideShadow: true,
                          from: requestDetailProvider.currentWorkOrder?.data?.requestedDate,
                          backgroundColor: AppColor.neutral100,
                          enable: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.startDate != null,
                          date: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.endDate,
                          formatDateWithTime: true,
                          to: DateTime.now(),
                          onDatePicker: (selectedDate) {
                            showTimePicker(
                              context: context,
                              initialTime: TimeOfDay.now(),
                            ).then((selectedTime) {
                              // Handle the selected date and time here.

                              if (selectedTime != null) {
                                selectedDate = selectedDate.add(Duration(hours: selectedTime.hour, minutes: selectedTime.minute));
                                bool isBeforeCurrentTime = selectedDate.isBefore(DateTime.now());
                                bool isAfterStartTime = selectedDate.isAfter(requestDetailProvider.activityMaintenanceHelperModel!.modelAssistantEmployees!.startDate!);
                                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;
                                }

                                requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.endDate = selectedDate;
                                requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                                ServiceRequestUtils.calculateAndAssignWorkingHours(
                                    startTime: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.startDate,
                                    endTime: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.endDate,
                                    workingHoursController: _workingHoursController,
                                    updateModel: (hours) {
                                      requestDetailProvider.activityMaintenanceHelperModel!.modelAssistantEmployees!.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: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.workingHours != null
                          ? requestDetailProvider.activityMaintenanceHelperModel!.modelAssistantEmployees!.workingHours.toString()
                          : '',
                      textAlign: TextAlign.center,
                      labelStyle: AppTextStyles.textFieldLabelStyle,
                      enable: false,
                      showShadow: false,
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    8.height,
                    AppTextFormField(
                      initialValue: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.technicalComment,
                      labelText: context.translation.technicalComment,
                      backgroundColor: AppColor.neutral100,
                      showShadow: false,
                      labelStyle: AppTextStyles.textFieldLabelStyle,
                      alignLabelWithHint: true,
                      textInputType: TextInputType.multiline,
                      onChange: (value) {
                        requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.technicalComment = value;
                      },
                      onSaved: (value) {
                        requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.technicalComment = value;
                      },
                    ),
                    8.height,
                  ],
                )
              : const SizedBox(),
        ],
      );
    });
  }

// //TODO move this to some common place....@waseem
//   double calculateWorkingHours(DateTime? startTime, DateTime? endTime) {
//     if (startTime != null && endTime != null) {
//       Duration difference = endTime.difference(startTime);
//       int hours = difference.inHours;
//       int minutes = difference.inMinutes % 60;
//       return hours.toDouble();
//     } else {
//       return -1;
//     }
//   }
//
//   assignWorkingHours({required RequestDetailProvider requestDetailProvider}) {
//     double hours = calculateWorkingHours(
//         requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.startDate, requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.endDate);
//     if (hours != -1) {
//       _workingHoursController.text = hours.toString();
//       requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.workingHours = hours;
//     }
//   }
}
