import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:kasy_kit/components/components.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/core/widgets/kasy_scroll_behavior.dart';
import 'package:kasy_kit/features/feedbacks/providers/feedback_page_notifier.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

Future<void> showAddFeatureBottomSheet(BuildContext context) {
  return showModalBottomSheet<bool?>(
    context: context,
    isScrollControlled: true,
    builder: (context) => const FractionallySizedBox(
      heightFactor: .8,
      child: AddFeatureComponent(),
    ),
  ).then((res) {
    if (!context.mounted) return;
    final translations = Translations.of(context).feature_requests.add_feature;
    if (res == true) {
      showSuccessToast(
        context: context,
        title: translations.toast_success.title,
        text: translations.toast_success.description,
      );
    }
  });
}

class AddFeatureComponent extends ConsumerStatefulWidget {
  const AddFeatureComponent({super.key});

  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _AddFeatureComponentState();
}

class _AddFeatureComponentState extends ConsumerState<AddFeatureComponent> {
  String title = '';
  String description = '';
  bool locked = false;

  final titleFocusNode = FocusNode();
  final textFocusNode = FocusNode();

  bool get _titleFilled => title.trim().isNotEmpty;
  bool get _descriptionValid => description.length >= 40;
  bool get canSubmit => _titleFilled && _descriptionValid && !locked;

  void _onSubmitAttempt() {
    final tr = Translations.of(context).feature_requests.add_feature;
    if (!_titleFilled || description.trim().isEmpty) {
      ref.read(toastProvider).error(
            title: tr.error_title,
            text: tr.error_required,
          );
      return;
    }
    if (!_descriptionValid) {
      ref.read(toastProvider).error(
            title: tr.error_title,
            text: tr.error_too_short,
          );
      return;
    }
  }

  void _submit() {
    if (locked) return;
    FocusScope.of(context).unfocus();
    locked = true;
    final tr = Translations.of(context).feature_requests.add_feature;
    ref
        .read(feedbackPageProvider.notifier)
        .createFeatureSuggestion(
          title: title,
          description: description,
        )
        .then(
          (_) {
            locked = false;
            if (!mounted) return;
            context.pop(true);
          },
          onError: (_) {
            locked = false;
            ref.read(toastProvider).error(
                  title: tr.error_title,
                  text: tr.error_sending,
                );
          },
        );
  }

  @override
  Widget build(BuildContext context) {
    final translations = Translations.of(context).feature_requests.add_feature;

    final Widget submitButton = KasyButton(
      label: translations.save_button,
      expand: true,
      onPressed: canSubmit ? _submit : null,
    );

    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: [
          Positioned.fill(
            child: ScrollConfiguration(
              behavior: const KasyKitScrollBehavior(),
              child: CustomScrollView(
                slivers: kasyOverlayPaddedSlivers(
                  context,
                  contentPadding: EdgeInsets.fromLTRB(
                    KasySpacing.pageHorizontalGutter,
                    KasySpacing.belowChromeContentGap,
                    KasySpacing.pageHorizontalGutter,
                    MediaQuery.paddingOf(context).bottom + KasySpacing.xxxl,
                  ),
                  slivers: [
                    SliverToBoxAdapter(
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            const SizedBox(height: KasySpacing.md),
                            Text(
                              translations.description,
                              style: context.textTheme.bodyMedium?.copyWith(
                                color: context.colors.muted,
                                height: 1.5,
                              ),
                            ),
                            const SizedBox(height: KasySpacing.xl),
                            KasyTextField(
                              label: translations.title_label,
                              hint: translations.title_hint,
                              showRequiredIndicator: true,
                              variant: KasyTextFieldVariant.secondary,
                              onChanged: (value) =>
                                  setState(() => title = value),
                              focusNode: titleFocusNode,
                              textInputAction: TextInputAction.next,
                              onSubmitted: (_) {
                                titleFocusNode.unfocus();
                                textFocusNode.requestFocus();
                              },
                              maxLength: 40,
                            ),
                            const SizedBox(height: KasySpacing.md),
                            KasyTextField(
                              label: translations.description_label,
                              hint: translations.description_hint,
                              showRequiredIndicator: true,
                              variant: KasyTextFieldVariant.secondary,
                              minLines: 6,
                              maxLines: 6,
                              onChanged: (value) =>
                                  setState(() => description = value),
                              textInputAction: TextInputAction.done,
                              onSubmitted: (_) => textFocusNode.unfocus(),
                              maxLength: 1000,
                              focusNode: textFocusNode,
                            ),
                            const SizedBox(height: KasySpacing.xl),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ),
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: KasyAppBar(
              title: translations.title,
              onBack: () => context.pop(),
            ),
          ),
          Positioned(
            left: KasySpacing.pageHorizontalGutter,
            right: KasySpacing.pageHorizontalGutter,
            bottom: MediaQuery.paddingOf(context).bottom + KasySpacing.md,
            child: canSubmit
                ? submitButton
                : GestureDetector(
                    onTap: _onSubmitAttempt,
                    child: submitButton,
                  ),
          ),
        ],
      ),
    );
  }
}
