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/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/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.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;
  final bool isClosed;
  final bool isHouseKeeper;
  final DateTime? timerStartTime;

  const RecurrentTaskInfoWidget({super.key, required this.model, this.isClosed = false, this.isHouseKeeper = false, this.timerStartTime});

  @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,
            InfoHeader16Widget(widget.model!.title!),
            InfoTextWidget(label: context.translation.taskNo, value: widget.model!.taskNo!, copyValue: true),
            InfoTextWidget(label: 'Plan Name:'.addTranslation, value: widget.model?.planRecurrent?.planName),
            InfoTextWidget(label: context.translation.site, value: widget.model!.site!.siteName!),
            if (widget.isHouseKeeper) ...[
              '${context.translation.department}:  ${widget.model!.department?.name ?? "-"}'.bodyText2(context).custom(color: AppColor.neutral120),
              '${context.translation.floor}:  ${widget.model!.floor?.name ?? "-"}'.bodyText2(context).custom(color: AppColor.neutral120),
              '${context.translation.room}:  ${widget.model!.room?.name ?? "-"}'.bodyText2(context).custom(color: AppColor.neutral120),
            ],
            InfoTextWidget(label: context.translation.assignedEmployee, value: widget.model!.engineer?.userName ?? ""),
            InfoTextWidget(label: context.translation.scheduledDate, value: widget.model!.scheduleDate!.toServiceRequestDetailsFormat),
          ],
        ).toShadowContainer(context),
        12.height,
        widget.model!.planRecurrentMedicalTaskRooms!.isEmpty
            ? Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (!widget.isHouseKeeper) ...[
                    buildingInfoWidget(label: context.translation.department, value: widget.model!.department?.name?.cleanupWhitespace.capitalizeFirstOfEach, context: context)
                        .ignorePointer(widget.isClosed),
                    8.height,
                    buildingInfoWidget(label: context.translation.floor, value: widget.model!.floor?.name?.cleanupWhitespace.capitalizeFirstOfEach, context: context).ignorePointer(widget.isClosed),
                    8.height,
                    buildingInfoWidget(label: context.translation.room, value: widget.model!.room?.name?.cleanupWhitespace.capitalizeFirstOfEach, context: context).ignorePointer(widget.isClosed),
                    8.height,
                  ],
                  _timerWidget(context, totalWorkingHours),
                  if (!widget.isHouseKeeper) ...[
                    8.height,
                    _commentWidget(context: context, model: widget.model).ignorePointer(widget.isClosed),
                  ],
                ],
                // ],
              ).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) {
    // For housekeeper: show read-only timer counter with history
    if (widget.isHouseKeeper) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (!widget.isClosed) ...[
            _HousekeeperTimerWidget(
              startTime: widget.timerStartTime,
              isClosed: widget.isClosed,
            ),
            12.height,
          ],
          if (totalWorkingHours > 0.0)
            WorkingTimeTile(
              timerList: timerList,
              totalWorkingTime: 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;
      },
    );
  }
}

// Read-only timer widget for housekeeper
class _HousekeeperTimerWidget extends StatefulWidget {
  final DateTime? startTime;
  final bool isClosed;

  const _HousekeeperTimerWidget({this.startTime, this.isClosed = false});

  @override
  State<_HousekeeperTimerWidget> createState() => _HousekeeperTimerWidgetState();
}

class _HousekeeperTimerWidgetState extends State<_HousekeeperTimerWidget> {
  String _elapsedTime = "0:00:00";

  @override
  void initState() {
    super.initState();
    if (widget.startTime != null && !widget.isClosed) {
      _startTimer();
    } else if (widget.startTime != null && widget.isClosed) {
      // If closed, calculate the final time
      _updateElapsedTime();
    }
  }

  void _updateElapsedTime() {
    if (widget.startTime != null) {
      final duration = DateTime.now().difference(widget.startTime!);
      final hours = duration.inHours;
      final minutes = duration.inMinutes % 60;
      final seconds = duration.inSeconds % 60;
      _elapsedTime = "$hours:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}";
    }
  }

  void _startTimer() {
    Future.delayed(const Duration(seconds: 1), () {
      if (mounted && widget.startTime != null && !widget.isClosed) {
        setState(() {
          _updateElapsedTime();
        });
        _startTimer();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (widget.startTime == null && !widget.isClosed) {
      return SizedBox.shrink();
    }

    return Container(
      height: 56.toScreenHeight,
      padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth),
      decoration: BoxDecoration(
        color: AppColor.fieldBgColor(context),
        borderRadius: BorderRadius.circular(10),
        // boxShadow: [
        //   BoxShadow(
        //     color: Colors.black.withOpacity(0.05),
        //     blurRadius: 10,
        //   )
        // ],
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                context.translation.timer.tinyFont(context),
                _elapsedTime.bodyText(context).custom(
                      color: context.isDark ? AppColor.neutral30 : AppColor.neutral50,
                    ),
              ],
            ),
          ),
          // No play/pause icon for housekeeper - timer runs automatically
        ],
      ),
    );
  }
}

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);
}
