import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/features/shifts/domain/shift_entity.dart';

Timer? shiftListTimer;

class ShiftOngoingCounterWidget extends StatefulWidget {
  final ShiftEntity viewModel;

  const ShiftOngoingCounterWidget({super.key, required this.viewModel});

  @override
  State<ShiftOngoingCounterWidget> createState() =>
      _ShiftOngoingCounterWidgetState();
}

class _ShiftOngoingCounterWidgetState extends State<ShiftOngoingCounterWidget> {
  @override
  void initState() {
    super.initState();
    shiftListTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var duration =
        DateTime.now().difference(widget.viewModel.clockIn ?? DateTime.now());
    var hours = duration.inHours.remainder(24).abs().toString().padLeft(2, '0');
    var minutes =
        duration.inMinutes.remainder(60).abs().toString().padLeft(2, '0');
    var seconds =
        duration.inSeconds.remainder(60).abs().toString().padLeft(2, '0');

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          height: 80,
          margin: const EdgeInsets.only(top: 24, left: 24, right: 24),
          decoration: BoxDecoration(
            color: AppColors.tintGreen,
            border: Border.all(color: AppColors.tintDarkGreen),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              _buildTimeText('hours'.tr(), hours),
              _divider(),
              _buildTimeText('minutes'.tr(), minutes),
              _divider(),
              _buildTimeText('seconds'.tr(), seconds),
            ],
          ),
        ),
      ],
    );
  }

  Widget _divider() {
    return SizedBox(
      width: 24,
      child: Center(
        child: Container(
          height: 24,
          width: 1,
          color: AppColors.tintDarkGreen,
        ),
      ),
    );
  }

  Widget _buildTimeText(String label, String time) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(time,
            style: AppTextStyles.headingH3
                .copyWith(color: AppColors.statusSuccess)),
        const Gap(6),
        Text(
          label,
          style: AppTextStyles.bodySmallReg
              .copyWith(color: AppColors.statusSuccess),
        ),
      ],
    );
  }
}
