import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/service_requests_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/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/service_request/service_report.dart';
import 'package:test_sa/models/service_request/service_request.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/providers/service_request_providers/last_situation_provider.dart';
import 'package:test_sa/providers/work_order/activity_status_provider.dart';
import 'package:test_sa/service_request_latest/request_detail_provider.dart';
import 'package:test_sa/service_request_latest/views/forms/maintenance_request/components/assistant_employee_card.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';

import '../../../../../controllers/providers/api/status_drop_down/report/service_types_provider.dart';
import '../../../../../models/lookup.dart';
import '../../../../../new_views/common_widgets/app_text_form_field.dart';
import '../../../../../new_views/common_widgets/single_item_drop_down_menu.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 {
  ServiceRequest? _request;
  ServiceRequestsProvider? _serviceRequestsProvider;
  RequestDetailProvider? _requestDetailProvider;
  ServiceStatusProvider? _assetTypeProvider;
  ActivityStatusProvider? _activityStatusProvider;
  ServiceReport? _serviceReport;
  bool _isLoading = false;

  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() {
    _activityStatusProvider = Provider.of<ActivityStatusProvider>(context, listen: false);
    _requestDetailProvider = Provider.of<RequestDetailProvider>(context, listen: false);
    _requestDetailProvider?.activityMaintenanceHelperModel?.activityStatus = _requestDetailProvider?.activityMaintenanceHelperModel?.activityStatus ?? statusLookup;
    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();
  }

  void getRequestForWorkOrder() async {
    _isLoading = true;
    setState(() {});
    _serviceReport?.callRequest = await _serviceRequestsProvider?.getCallRequestForWorkOrder(callId: _request?.id ?? '0');
    await _assetTypeProvider?.getTypes();
    _serviceReport?.assignedEmployee = _serviceReport?.callRequest?.assignedEmployee;
    _serviceReport?.equipmentStatus = _serviceReport?.callRequest?.defectType;
    _serviceReport?.serviceType = Lookup(id: 65, name: "Interval", value: 1); // default value in service type as in web
    _isLoading = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<RequestDetailProvider>(builder: (context, requestDetailProvider, child) {
      return SingleChildScrollView(
        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.lastSituationStatus,
                    showShadow: false,
                    backgroundColor: AppColor.neutral100,
                    showAsBottomSheet: true,
                    initialValue: requestDetailProvider.activityMaintenanceHelperModel?.lastSituation,
                    onSelect: (status) {
                      if (status != null) {
                        requestDetailProvider.activityMaintenanceHelperModel?.lastSituation = status;
                        setState(() {});
                      }
                    },
                  ),
                  8.height,
                  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.updateActivityMaintenanceHelperModel(requestDetailProvider.activityMaintenanceHelperModel);
                              assignWorkingHours(requestDetailProvider: requestDetailProvider);
                            }
                          });
                        },
                      ).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);
                              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?.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.neutral100,
                    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: TextInputType.number,
                    onChange: (value) {
                      requestDetailProvider.activityMaintenanceHelperModel?.travelHours = int.tryParse(value);
                    },
                    // contentPadding: EdgeInsets.symmetric(vertical: 18.toScreenHeight, horizontal: 16.toScreenWidth),
                    onSaved: (value) {
                      requestDetailProvider.activityMaintenanceHelperModel?.travelHours = value as int?;
                    },
                  ),
                  16.height,
                  repairLocationWidget(context, requestDetailProvider),
                  16.height,
                  AppTextFormField(
                    labelText: context.translation.assignedEmployee,
                    backgroundColor: AppColor.neutral80,
                    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.neutral100,
                    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),
            const AssistantEmployeeCard().toShadowContainer(context, paddingObject: const EdgeInsets.symmetric(horizontal: 16)).paddingOnly(start: 13, end: 14, top: 12),
            100.height,
          ],
        ),
      );
    });
  }

  Widget repairLocationWidget(BuildContext context, RequestDetailProvider 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.black20),
          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),
        ],
      );
    });
  }

  int 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;
    } else {
      return -1;
    }
  }

  assignWorkingHours({required RequestDetailProvider requestDetailProvider}) {
    int hours = calculateWorkingHours(requestDetailProvider.activityMaintenanceHelperModel!.startTime, requestDetailProvider.activityMaintenanceHelperModel!.endTime);
    if (hours != -1) {
      _workingHoursController.text = hours.toString();
      requestDetailProvider.activityMaintenanceHelperModel!.workingHour = hours;
    }
  }
}
