import 'package:didvan/config/design_config.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/message_data/news_attachment.dart';
import 'package:didvan/models/message_data/radar_attachment.dart';
import 'package:didvan/models/view/action_sheet_data.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/views/widgets/bookmark_button.dart';
import 'package:didvan/views/widgets/menu_item.dart';
import 'package:didvan/views/widgets/didvan/chip.dart';
import 'package:didvan/views/widgets/didvan/divider.dart';
import 'package:didvan/views/widgets/didvan/icon_button.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/item_title.dart';
import 'package:flutter/material.dart';

class FloatingNavigationBar extends StatefulWidget {
  final ScrollController scrollController;
  final dynamic item;
  final bool hasUnmarkConfirmation;
  final void Function(int count) onCommentsChanged;
  final bool isRadar;
  final bool openComments;
  final void Function(bool value) onMarkChanged;

  const FloatingNavigationBar({
    Key? key,
    required this.scrollController,
    required this.onCommentsChanged,
    required this.onMarkChanged,
    required this.isRadar,
    required this.item,
    this.hasUnmarkConfirmation = false,
    required this.openComments,
  }) : super(key: key);

  @override
  State<FloatingNavigationBar> createState() => _FloatingNavigationBarState();
}

class _FloatingNavigationBarState extends State<FloatingNavigationBar> {
  bool _isScrolled = false;
  int _comments = 0;

  @override
  void didUpdateWidget(covariant FloatingNavigationBar oldWidget) {
    _comments = widget.item.comments;

    if (widget.openComments) {
      Future.delayed(
        const Duration(seconds: 1),
        () => Navigator.of(context).pushNamed(
          Routes.mentions,
          arguments: {
            'id': widget.item.id,
            'type': widget.isRadar ? 'radar' : 'news',
            'title': widget.item.title,
          },
        ),
      );
    }

    _isScrolled = false;
    _handleScroll();
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    _handleScroll();
    _isScrolled = false;
    _comments = widget.item.comments;

    if (widget.openComments) {
      Future.delayed(
        const Duration(seconds: 1),
        () => Navigator.of(context).pushNamed(
          Routes.mentions,
          arguments: {
            'id': widget.item.id,
            'type': widget.isRadar ? 'radar' : 'news',
            'title': widget.item.title,
          },
        ),
      );
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final Color foregroundColor = DesignConfig.isDark
        ? Theme.of(context).colorScheme.focusedBorder
        : Theme.of(context).colorScheme.focused;
    return Container(
      margin: const EdgeInsets.only(left: 32, right: 32, bottom: 20),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      width: double.infinity,
      height: 48,
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.navigation,
        borderRadius: BorderRadius.circular(24),
        border: DesignConfig.isDark
            ? Border.all(
                color: Theme.of(context).colorScheme.cardBorder,
              )
            : null,
      ),
      child: Theme(
        data: Theme.of(context).copyWith(
          iconTheme: IconThemeData(
            color: foregroundColor,
          ),
        ),
        child: Row(
          children: [
            AnimatedRotation(
              duration: DesignConfig.lowAnimationDuration,
              turns: _isScrolled ? -0.25 : 0,
              child: DidvanIconButton(
                onPressed: () {
                  if (_isScrolled) {
                    widget.scrollController.animateTo(
                      0,
                      duration: DesignConfig.lowAnimationDuration,
                      curve: Curves.easeIn,
                    );
                    return;
                  }
                  Navigator.of(context).pop();
                },
                icon: DidvanIcons.back_regular,
              ),
            ),
            const Spacer(),
            SizedBox(
              width: 60,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  DidvanIconButton(
                    gestureSize: 32,
                    onPressed: () => Navigator.of(context).pushNamed(
                      Routes.mentions,
                      arguments: {
                        'id': widget.item.id,
                        'type': widget.isRadar ? 'radar' : 'news',
                        'title': widget.item.title,
                      },
                    ),
                    icon: 'lib/assets/icons/fluent_mention-32-regular.svg',
                    isSvg: true,
                    size: 25,
                  ),
                ],
              ),
            ),
            BookmarkButton(
              itemId: widget.item.id,
              type: widget.isRadar ? 'radar' : 'news',
              color: DesignConfig.isDark
                  ? Theme.of(context).colorScheme.focusedBorder
                  : Theme.of(context).colorScheme.focused,
              askForConfirmation: widget.hasUnmarkConfirmation,
              value: widget.item.marked,
              onMarkChanged: (value) {
                widget.onMarkChanged(value);
                if (widget.hasUnmarkConfirmation && !value) {
                  Navigator.of(context).pop();
                }
              },
              gestureSize: 22,
              svgIconOn: 'lib/assets/icons/bookmark_fill.svg',
              svgIconOff: 'lib/assets/icons/archive-tick.svg',
            ),
            SizedBox(
              width: 60,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  if (_comments != 0)
                    DidvanText(
                      _comments.toString(),
                      color: foregroundColor,
                    ),
                  DidvanIconButton(
                    gestureSize: 32,
                    onPressed: () => Navigator.of(context).pushNamed(
                      Routes.comments,
                      arguments: {
                        'id': widget.item.id,
                        'type': widget.isRadar ? 'radar' : 'news',
                        'title': widget.item.title,
                        'onCommentsChanged': widget.onCommentsChanged,
                      },
                    ),
                    icon: 'lib/assets/icons/message-text.svg',
                    isSvg: true,
                    size: 25,
                  ),
                ],
              ),
            ),
            DidvanIconButton(
              gestureSize: 32,
              onPressed:
                  widget.isRadar ? _showRadarMoreOptions : _showNewsMoreOptions,
              icon: DidvanIcons.menu_regular,
            ),
          ],
        ),
      ),
    );
  }

  void _handleScroll() {
    widget.scrollController.addListener(() {
      final position = widget.scrollController.position.pixels;
      final size = MediaQuery.of(context).size.height * 0.3;
      if (position > size && _isScrolled == false) {
        setState(() {
          _isScrolled = true;
        });
      }
      if (position < size && _isScrolled == true) {
        setState(() {
          _isScrolled = false;
        });
      }
    });
  }

  void _showRadarMoreOptions() {
    final categories = widget.item.categories!;
    ActionSheetUtils(context).showBottomSheet(
      data: ActionSheetData(
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const ItemTitle(
              title: 'ارتباط با سردبیر',
              icon: DidvanIcons.profile_regular,
            ),
            const SizedBox(height: 16),
            for (var i = 0; i < categories.length; i++) ...[
              Padding(
                padding: const EdgeInsets.only(right: 20),
                child: MenuOption(
                  titleWidget: DidvanChip(label: categories[i].label),
                  onTap: () {
                    Navigator.of(context).pop();
                    Navigator.of(context).pushNamed(
                      Routes.direct,
                      arguments: {
                        'radarAttachment': RadarAttachment(
                          id: widget.item.id,
                          title: widget.item.title,
                          description: widget.item.contents.first.text,
                          timeToRead: widget.item.timeToRead,
                          image: widget.item.image,
                          forManagers: widget.item.forManagers,
                          categories: widget.item.categories,
                          createdAt: widget.item.createdAt,
                        ),
                        'type': categories[i].label,
                      },
                    );
                  },
                ),
              ),
              if (i != categories.length - 1)
                const Padding(
                  padding: EdgeInsets.only(right: 20),
                  child: DidvanDivider(verticalPadding: 8),
                ),
            ],
            const DidvanDivider(),
            MenuOption(
              title: 'گزارش اشکال',
              onTap: () {
                Navigator.of(context).pop();
                Navigator.of(context).pushNamed(
                  Routes.direct,
                  arguments: {
                    'radarAttachment': RadarAttachment(
                      id: widget.item.id,
                      title: widget.item.title,
                      description: widget.item.contents.first.text,
                      timeToRead: widget.item.timeToRead,
                      image: widget.item.image,
                      forManagers: widget.item.forManagers,
                      categories: widget.item.categories,
                      createdAt: widget.item.createdAt,
                    ),
                    'type': 'پشتیبانی'
                  },
                );
              },
              icon: DidvanIcons.description_regular,
            ),
            if (widget.isRadar) ...[
              const DidvanDivider(),
              MenuOption(
                title: 'می‌خواهم بیشتر بدانم',
                icon: DidvanIcons.info_circle_regular,
                onTap: () {
                  Navigator.of(context).pop();
                  Navigator.of(context).pushNamed(
                    Routes.direct,
                    arguments: {
                      'radarAttachment': RadarAttachment(
                        id: widget.item.id,
                        title: widget.item.title,
                        description: widget.item.contents.first.text,
                        timeToRead: widget.item.timeToRead,
                        image: widget.item.image,
                        forManagers: widget.item.forManagers,
                        categories: widget.item.categories,
                        createdAt: widget.item.createdAt,
                      ),
                      'type': 'می‌خواهم بیشتر بدانم'
                    },
                  );
                },
              ),
            ],
          ],
        ),
        title: 'موارد بیشتر',
        withoutButtonMode: true,
      ),
    );
  }

  void _showNewsMoreOptions() {
    ActionSheetUtils(context).showBottomSheet(
      data: ActionSheetData(
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            MenuOption(
              title: 'گزارش اشکال',
              onTap: () {
                Navigator.of(context).pop();
                Navigator.of(context).pushNamed(
                  Routes.direct,
                  arguments: {
                    'newsAttachment': NewsAttachment(
                      id: widget.item.id,
                      title: widget.item.title,
                      description: widget.item.contents.first.text,
                      image: widget.item.image,
                      createdAt: widget.item.createdAt,
                    ),
                    'type': 'پشتیبانی'
                  },
                );
              },
              icon: DidvanIcons.description_regular,
            ),
          ],
        ),
        title: 'موارد بیشتر',
        withoutButtonMode: true,
      ),
    );
  }
}
