import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:kasy_kit/components/kasy_app_bar.dart';
import 'package:kasy_kit/components/kasy_button.dart';
import 'package:kasy_kit/components/kasy_text_area.dart';
import 'package:kasy_kit/components/kasy_text_field.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/core/toast/toast_service.dart';
import 'package:kasy_kit/core/widgets/kasy_scroll_behavior.dart';
import 'package:kasy_kit/features/notifications/api/notifications_api.dart';
import 'package:kasy_kit/features/settings/ui/components/admin/send_push_notifier.dart';
import 'package:kasy_kit/features/settings/ui/widgets/settings_tile.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

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

  @override
  ConsumerState<SendPushNotificationPage> createState() =>
      _SendPushNotificationPageState();
}

class _SendPushNotificationPageState
    extends ConsumerState<SendPushNotificationPage> {
  final _titleCtrl = TextEditingController();
  final _bodyCtrl = TextEditingController();
  final _imageCtrl = TextEditingController();
  final _routeCtrl = TextEditingController();
  final _emailCtrl = TextEditingController();

  // Explicit FocusNodes for all fields keeps the keyboard open when switching.
  final _emailFocus = FocusNode();
  final _titleFocus = FocusNode();
  final _bodyFocus = FocusNode();
  final _imageFocus = FocusNode();
  final _routeFocus = FocusNode();

  bool _sendToAll = false;
  final List<String> _emails = [];

  @override
  void dispose() {
    _titleCtrl.dispose();
    _bodyCtrl.dispose();
    _imageCtrl.dispose();
    _routeCtrl.dispose();
    _emailCtrl.dispose();
    _emailFocus.dispose();
    _titleFocus.dispose();
    _bodyFocus.dispose();
    _imageFocus.dispose();
    _routeFocus.dispose();
    super.dispose();
  }

  void _addEmail() {
    final email = _emailCtrl.text.trim();
    if (email.isEmpty || _emails.contains(email)) return;
    setState(() {
      _emails.add(email);
      _emailCtrl.clear();
    });
    _emailFocus.requestFocus();
  }

  void _removeEmail(String email) {
    setState(() => _emails.remove(email));
  }

  bool get _canSend {
    if (_titleCtrl.text.trim().isEmpty) return false;
    if (_bodyCtrl.text.trim().isEmpty) return false;
    if (!_sendToAll && _emails.isEmpty) return false;
    return true;
  }

  void _onSendAttempt() {
    final tr = t.settings.admin;
    final String msg;
    if (!_sendToAll && _emails.isEmpty) {
      msg = tr.send_push_no_emails;
    } else {
      msg = tr.send_push_required;
    }
    ref.read(toastProvider).error(title: tr.send_push_title, text: msg);
  }

  Future<void> _send() async {
    await ref.read(sendPushProvider.notifier).send(
          title: _titleCtrl.text.trim(),
          body: _bodyCtrl.text.trim(),
          imageUrl: _imageCtrl.text.trim().isEmpty
              ? null
              : _imageCtrl.text.trim(),
          emails: List.from(_emails),
          sendToAll: _sendToAll,
          route: _routeCtrl.text.trim().isEmpty
              ? null
              : _routeCtrl.text.trim(),
        );
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(sendPushProvider);
    final tr = t.settings.admin;

    ref.listen<AsyncValue<void>>(sendPushProvider, (prev, next) {
      if (next is AsyncError) {
        final err = next.error;
        final msg = err is UsersNotFoundError
            ? tr.send_push_user_not_found(email: err.toString())
            : err.toString();
        ref.read(toastProvider).error(title: tr.send_push_title, text: msg);
        ref.read(sendPushProvider.notifier).reset();
      } else if (prev is AsyncLoading && next is AsyncData) {
        ref
            .read(toastProvider)
            .success(title: tr.send_push_title, text: tr.send_push_success);
        context.pop();
      }
    });

    final Widget submitButton = _canSend
        ? KasyButton(
            label: tr.send_push_send_button,
            expand: true,
            isLoading: state is AsyncLoading,
            onPressed: _send,
          )
        : GestureDetector(
            onTap: _onSendAttempt,
            child: KasyButton(
              label: tr.send_push_send_button,
              expand: true,
              onPressed: null,
            ),
          );

    return Scaffold(
      // resizeToAvoidBottomInset: true (default) — button rises with keyboard.
      body: Stack(
        fit: StackFit.expand,
        children: [
          Positioned.fill(
            child: ScrollConfiguration(
              behavior: const KasyKitScrollBehavior(),
              child: CustomScrollView(
                // Drag down to dismiss keyboard — the professional standard.
                keyboardDismissBehavior:
                    ScrollViewKeyboardDismissBehavior.onDrag,
                slivers: kasyOverlayPaddedSlivers(
                  context,
                  contentPadding: EdgeInsets.fromLTRB(
                    KasySpacing.pageHorizontalGutter,
                    KasySpacing.belowChromeContentGap,
                    KasySpacing.pageHorizontalGutter,
                    MediaQuery.paddingOf(context).bottom +
                        52.0 +
                        KasySpacing.md * 2,
                  ),
                  slivers: [
                    SliverToBoxAdapter(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          SettingsSwitchTile(
                            icon: KasyIcons.notificationActive,
                            title: tr.send_push_to_all,
                            value: _sendToAll,
                            onChanged: (v) => setState(() => _sendToAll = v),
                          ),
                          const SettingsDivider(),
                          const SizedBox(height: KasySpacing.lg),
                          if (!_sendToAll) ...[
                            _EmailsSection(
                              emails: _emails,
                              controller: _emailCtrl,
                              focusNode: _emailFocus,
                              onAdd: _addEmail,
                              onRemove: _removeEmail,
                              label: tr.send_push_email_label,
                              hint: tr.send_push_email_hint,
                            ),
                            const SizedBox(height: KasySpacing.lg),
                          ],
                          KasyTextField(
                            label: tr.send_push_title_label,
                            hint: tr.send_push_title_hint,
                            controller: _titleCtrl,
                            focusNode: _titleFocus,
                            maxLength: 64,
                            showRequiredIndicator: true,
                            textInputAction: TextInputAction.next,
                            onChanged: (_) => setState(() {}),
                            onEditingComplete: () => _bodyFocus.requestFocus(),
                          ),
                          const SizedBox(height: KasySpacing.md),
                          KasyTextArea(
                            label: tr.send_push_body_label,
                            hint: tr.send_push_body_hint,
                            controller: _bodyCtrl,
                            focusNode: _bodyFocus,
                            maxLength: 250,
                            showRequiredIndicator: true,
                            minLines: 3,
                            maxLines: 5,
                            onChanged: (_) => setState(() {}),
                          ),
                          const SizedBox(height: KasySpacing.md),
                          KasyTextField(
                            label: tr.send_push_image_label,
                            hint: tr.send_push_image_hint,
                            controller: _imageCtrl,
                            focusNode: _imageFocus,
                            textInputAction: TextInputAction.next,
                            onEditingComplete: () => _routeFocus.requestFocus(),
                          ),
                          const SizedBox(height: KasySpacing.md),
                          KasyTextField(
                            label: tr.send_push_route_label,
                            hint: tr.send_push_route_hint,
                            controller: _routeCtrl,
                            focusNode: _routeFocus,
                            textInputAction: TextInputAction.done,
                            onEditingComplete: () => _routeFocus.unfocus(),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: KasyAppBar(
              title: tr.send_push_title,
              onBack: () => context.pop(),
            ),
          ),
          Positioned(
            left: KasySpacing.pageHorizontalGutter,
            right: KasySpacing.pageHorizontalGutter,
            bottom: MediaQuery.paddingOf(context).bottom + KasySpacing.sm,
            child: submitButton,
          ),
        ],
      ),
    );
  }
}

class _EmailsSection extends StatelessWidget {
  final List<String> emails;
  final TextEditingController controller;
  final FocusNode focusNode;
  final VoidCallback onAdd;
  final void Function(String) onRemove;
  final String label;
  final String hint;

  const _EmailsSection({
    required this.emails,
    required this.controller,
    required this.focusNode,
    required this.onAdd,
    required this.onRemove,
    required this.label,
    required this.hint,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(
              child: KasyTextField(
                label: label,
                hint: hint,
                controller: controller,
                focusNode: focusNode,
                showRequiredIndicator: true,
                // "next" keeps keyboard open when pressing the action key.
                textInputAction: TextInputAction.next,
                onEditingComplete: onAdd,
              ),
            ),
            const SizedBox(width: 8),
            Padding(
              padding: const EdgeInsets.only(bottom: 2),
              child: KasyButton.iconOnly(
                icon: Icons.add,
                onPressed: onAdd,
                size: KasyButtonSize.small,
                variant: KasyButtonVariant.soft,
              ),
            ),
          ],
        ),
        if (emails.isNotEmpty) ...[
          const SizedBox(height: KasySpacing.sm),
          Wrap(
            spacing: 6,
            runSpacing: 6,
            children: emails
                .map(
                  (email) => _EmailChip(
                    email: email,
                    onRemove: () => onRemove(email),
                  ),
                )
                .toList(),
          ),
        ],
      ],
    );
  }
}

class _EmailChip extends StatelessWidget {
  final String email;
  final VoidCallback onRemove;

  const _EmailChip({required this.email, required this.onRemove});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      decoration: BoxDecoration(
        color: context.colors.primary.withValues(alpha: 0.10),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            email,
            style: context.textTheme.bodySmall?.copyWith(
              color: context.colors.primary,
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(width: 4),
          GestureDetector(
            onTap: onRemove,
            child: Icon(
              Icons.close,
              size: 13,
              color: context.colors.primary.withValues(alpha: 0.7),
            ),
          ),
        ],
      ),
    );
  }
}
