import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/all_requests_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/ppm/recurrent_wo.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/new_views/common_widgets/working_time_tile.dart';

import 'package:test_sa/views/widgets/requests/request_status.dart';
import 'package:test_sa/views/widgets/timer/app_timer.dart';
import 'package:test_sa/views/widgets/total_working_time_detail_bottomsheet.dart';

class RecurrentTaskInfoWidget extends StatefulWidget {
  final RecurrentWoData? model;

  RecurrentTaskInfoWidget({super.key, required this.model});

  @override
  State<RecurrentTaskInfoWidget> createState() => _RecurrentTaskInfoWidgetState();
}

class _RecurrentTaskInfoWidgetState extends State<RecurrentTaskInfoWidget> {
  @override
  void initState() {
    calculateWorkingTime();
    super.initState();
  }

  List<TimerHistoryModel> timerList = [];
  double totalWorkingHours = 0;

  void calculateWorkingTime() {
    final helperModel = widget.model;
    final timers = helperModel?.planRecurrentTaskTimers ?? [];
    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
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (widget.model?.status != null)
              StatusLabel(
                label: widget.model?.status?.name,
                textColor: AppColor.getRequestStatusTextColorByName(context, widget.model?.status?.name),
                backgroundColor: AppColor.getRequestStatusColorByName(context, widget.model?.status?.name),
              ),
            8.height,
            widget.model!.title!.bodyText(context).custom(color: AppColor.textColor(context)),
            2.height,
            '${context.translation.taskNo}:  ${widget.model!.taskNo!}'.bodyText2(context).custom(color: AppColor.neutral120),
            'Plan Name:  ${widget.model?.planRecurrent?.planName ?? "-"}'.bodyText2(context).custom(color: AppColor.neutral120),
            '${context.translation.site}:  ${widget.model!.site!.siteName!}'.bodyText2(context).custom(color: AppColor.neutral120),
            '${context.translation.assignedEmployee}:  ${widget.model!.engineer!.userName ?? ""}'.bodyText2(context).custom(color: AppColor.neutral120),
            '${context.translation.scheduledDate}:  ${widget.model!.scheduleDate!.toMonthYearFormat}'.bodyText2(context).custom(color: AppColor.neutral120),
          ],
        ).toShadowContainer(context),
        12.height,
        widget.model!.planRecurrentMedicalTaskRooms!.isEmpty
            ? Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  buildingInfoWidget(label: context.translation.department, value: widget.model!.department?.name?.cleanupWhitespace.capitalizeFirstOfEach, context: context),
                  8.height,
                  buildingInfoWidget(label: context.translation.floor, value: widget.model!.floor?.name?.cleanupWhitespace.capitalizeFirstOfEach, context: context),
                  8.height,
                  buildingInfoWidget(label: context.translation.room, value: widget.model!.room?.name?.cleanupWhitespace.capitalizeFirstOfEach, context: context),
                  8.height,
                  _timerWidget(context, totalWorkingHours),
                  8.height,
                  _commentWidget(context: context, model: widget.model)
                ],
                // ],
              ).toShadowContainer(context, padding: 12)
            : Column(
                children: [_timerWidget(context, totalWorkingHours), 8.height, _commentWidget(context: context, model: widget.model)],
              ).toShadowContainer(context, padding: 12),
      ],
    );
  }

  Widget _timerWidget(BuildContext context, double totalWorkingHours) {
    return Consumer<AllRequestsProvider>(builder: (context, snapshot, child) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AppTimer(
            label: context.translation.timer,
            timer: snapshot.recurrentWoData?.recurrentWoTimerModel,
            width: double.infinity,
            enabled: snapshot.recurrentWoData?.status?.value != 1,
            decoration: BoxDecoration(
              color: AppColor.fieldBgColor(context),
              borderRadius: BorderRadius.circular(10),
            ),
            pickerTimer: widget.model?.recurrentWoTimePicker,
            pickerFromDate: DateTime.tryParse(widget.model?.scheduleDate ?? ''),
            onPick: (time) {
              widget.model?.recurrentWoTimePicker = time;
            },
            timerProgress: (isRunning) {},
            onChange: (timer) async {
              snapshot.updateRecurrentWoTimer(timer: timer);
              return true;
            },
          ),
          if (totalWorkingHours > 0.0) ...[
            12.height,
            WorkingTimeTile(
              timerList: timerList,
              totalWorkingTime: totalWorkingHours,
            ),
          ],
        ],
      );
    });
  }

  Widget _commentWidget({RecurrentWoData? model, required BuildContext context}) {
    return AppTextFormField(
      initialValue: model?.comment,
      labelText: context.translation.comment,
      backgroundColor: AppColor.fieldBgColor(context),
      showShadow: false,
      hintStyle: TextStyle(color: context.isDark ? AppColor.white10 : AppColor.black10),
      labelStyle: TextStyle(color: context.isDark ? AppColor.white10 : AppColor.black10),
      alignLabelWithHint: true,
      textInputType: TextInputType.multiline,
      onChange: (value) {
        model?.comment = value;
      },
      onSaved: (value) {
        model?.comment = value;
      },
    );
  }
}

Widget buildingInfoWidget({required String label, required String? value, required BuildContext context}) {
  return Column(
    mainAxisAlignment: MainAxisAlignment.start,
    crossAxisAlignment: CrossAxisAlignment.start,
    mainAxisSize: MainAxisSize.min,
    children: [
      Text(
        label,
        style: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.neutral120),
      ),
      3.height,
      Text(
        value ?? '',
        style: AppTextStyles.bodyText2.copyWith(color: AppColor.textColor(context)),
      )
    ],
  ).toShadowContainer(context, backgroundColor: context.isDark ? AppColor.neutral60 : AppColor.neutral100, borderRadius: 10, paddingObject: EdgeInsets.all(12.toScreenHeight), showShadow: false);
}
