import 'dart:developer';

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/cm_detail_provider.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/new_views/common_widgets/working_time_tile.dart';
import 'package:test_sa/providers/service_request_providers/last_situation_provider.dart';
import 'package:test_sa/views/widgets/timer/app_timer.dart';
import 'package:test_sa/views/widgets/total_working_time_detail_bottomsheet.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 {
  CMDetailProvider? _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});
  List<TimerHistoryModel> timerList = [];
  double totalWorkingHours = 0;

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

  void calculateWorkingTime() {
    final helperModel = _requestDetailProvider?.activityMaintenanceHelperModel;
    final timers = helperModel?.activityMaintenanceTimers ?? [];
    totalWorkingHours = timers.fold<double>(0.0, (sum, item) {
      if (item.startTime == null || item.endTime == null) return sum;
      try {
        final start = DateTime.parse(item.startTime!);
        final end = DateTime.parse(item.endTime!);
        final diffInHours = end.difference(start).inSeconds / 3600.0; // convert to hours
        return sum + diffInHours;
      } catch (_) {
        return sum;
      }
    });
    timerList = timers.map((e) {
      return TimerHistoryModel(
        id: e.id,
        startTime: e.startTime,
        endTime: e.endTime,
        workingHours: e.workingHours,
      );
    }).toList();
  }

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

  @override
  Widget build(BuildContext context) {
    return Consumer<CMDetailProvider>(builder: (context, requestDetailProvider, child) {
      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, 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,
                    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;
                      },
                    ),
                    8.height,
                    if (totalWorkingHours > 0.0) ...[
                      WorkingTimeTile(
                        timerList: timerList,
                        totalWorkingTime: totalWorkingHours,
                      ),
                      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,
                      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;
                  });
                },
              ),
            ],
          ),
        ),
      );
    });
  }

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