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/models/new_models/work_order_detail_model.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/service_request_latest/request_detail_provider.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!;
    RequestDetailProvider requestDetailProvider = Provider.of<RequestDetailProvider>(context, listen: false);
    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<RequestDetailProvider>(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.arrow_drop_up_outlined : Icons.arrow_drop_down),
              ],
            ),
          ).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) {
                        print('on select called...${employee?.toJson()}');
                        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,
                          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,
                                );
                                requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.startDate = selectedDateTime;
                                requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                                assignWorkingHours(requestDetailProvider: requestDetailProvider);
                              }
                            });
                          },
                        ).expanded,
                        8.width,
                        ADatePicker(
                          label: context.translation.endTime,
                          hideShadow: true,
                          backgroundColor: AppColor.neutral100,
                          date: requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.endDate,
                          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?.modelAssistantEmployees?.startDate != null &&
                                    selectedDateTime.isBefore(requestDetailProvider.activityMaintenanceHelperModel!.modelAssistantEmployees!.startDate!)) {
                                  "End Date time must be greater then start date".showToast;
                                  return;
                                }
                                requestDetailProvider.activityMaintenanceHelperModel?.modelAssistantEmployees?.endDate = selectedDateTime;
                                requestDetailProvider.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                                assignWorkingHours(requestDetailProvider: requestDetailProvider);
                              }
                            });
                          },
                        ).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;
    }
  }
}
