import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/presentation/styles/kw_box_decorations.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_app_bar.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/features/profile/wages_forms/domain/bloc/wages_form_bloc.dart';
import 'package:krow/features/profile/wages_forms/domain/sign_image_service.dart';
import 'package:krow/features/profile/wages_forms/presentation/widgets/sign_notice_widget.dart';
import 'package:syncfusion_flutter_signaturepad/signaturepad.dart';

@RoutePage()
class FormSignScreen extends StatefulWidget {
  const FormSignScreen({super.key, required this.title});

  final String title;

  @override
  State<FormSignScreen> createState() => _FormSignScreenState();
}

class _FormSignScreenState extends State<FormSignScreen> {
  final GlobalKey<SfSignaturePadState> _signaturePadKey = GlobalKey();
  final _signNotifier = ValueNotifier<bool>(false);
  Timer? _signTrackingTimer;

  void _startSignTracking() {
    _signNotifier.value = false;
    _signTrackingTimer?.cancel();
    _signTrackingTimer = Timer.periodic(const Duration(milliseconds: 300), (_) {
      _signNotifier.value =
          _signaturePadKey.currentState?.toPathList().isNotEmpty ?? false;

      if (_signNotifier.value) _signTrackingTimer?.cancel();
    });
  }

  void _handleOnSubmit() {
    final wagesBloc = context.read<WagesFormBloc>();
    SignImageService()
        .getSignPngBytes(_signaturePadKey.currentState!)
        .then((imageData) {
      wagesBloc.add(AddUserSignImage(imageData: imageData));
    });

    context.router.maybePop();
  }

  @override
  void initState() {
    super.initState();

    _startSignTracking();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: KwAppBar(
        titleText: widget.title,
        showNotification: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Sign the document below:',
              style: AppTextStyles.bodySmallRegBlackGrey,
            ),
            const Gap(24),
            Expanded(
              child: Stack(
                alignment: AlignmentDirectional.topEnd,
                children: [
                  DecoratedBox(
                    decoration: KwBoxDecorations.primaryLight8,
                    child: SfSignaturePad(
                      key: _signaturePadKey,
                    ),
                  ),
                  ListenableBuilder(
                    listenable: _signNotifier,
                    builder: (context, _) {
                      return _signNotifier.value
                          ? IconButton(
                              onPressed: () {
                                _signaturePadKey.currentState?.clear();
                                _startSignTracking();
                              },
                              icon: const Icon(
                                Icons.close,
                                color: AppColors.bgColorDark,
                                size: 24,
                              ),
                            )
                          : const SizedBox.shrink();
                    },
                  ),
                  Align(
                    alignment: Alignment.bottomCenter,
                    child: ListenableBuilder(
                      listenable: _signNotifier,
                      builder: (context, _) {
                        return _signNotifier.value
                            ? const SizedBox.shrink()
                            : const Padding(
                                padding: EdgeInsets.all(12),
                                child: SignNoticeWidget(),
                              );
                      },
                    ),
                  )
                ],
              ),
            ),
            const Gap(28),
          ],
        ),
      ),
      bottomNavigationBar: SafeArea(
        top: false,
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: ListenableBuilder(
            listenable: _signNotifier,
            builder: (context, _) {
              return KwButton.primary(
                label: 'Submit and Back to Form',
                disabled: !_signNotifier.value,
                onPressed: _handleOnSubmit,
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _signTrackingTimer?.cancel();
    super.dispose();
  }
}
