// ignore_for_file: deprecated_member_use

import 'dart:math';
import 'dart:ui';

import 'package:didvan/config/design_config.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/constants/assets.dart';
import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/providers/user.dart';
import 'package:didvan/views/mentions/mentions_state.dart';
import 'package:didvan/views/mentions/widgets/mention.dart';
import 'package:didvan/views/widgets/animated_visibility.dart';
import 'package:didvan/views/widgets/didvan/icon_button.dart';
import 'package:didvan/views/widgets/didvan/scaffold.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/shimmer_placeholder.dart';
import 'package:didvan/views/widgets/state_handlers/empty_state.dart';
import 'package:didvan/views/widgets/state_handlers/sliver_state_handler.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/user_mention.dart';

class Mentions extends StatefulWidget {
  final Map<String, dynamic> pageData;

  const Mentions({
    Key? key,
    required this.pageData,
  }) : super(key: key);

  @override
  State<Mentions> createState() => _MentionsState();
}

class _MentionsState extends State<Mentions> {
  final _focusNode = FocusNode();
  final _focusNodeMention = FocusNode();
  double _bottomPadding = 0;

  @override
  void initState() {
    final state = context.read<MentionsState>();
    state.itemId = widget.pageData['id'];
    state.type = widget.pageData['type'];

    Future.delayed(
      Duration.zero,
      () => state.getComments(),
    );

    super.initState();
  }

  bool get _isPage => widget.pageData['isPage'] != false;

  void _onChange(MentionsState state, String value) {
    state.getUsersMention(context.read<UserProvider>().user.id);
    state.update();
  }

  @override
  Widget build(BuildContext context) {
    final mentionsState = context.watch<MentionsState>();

    final bottomViewInset = MediaQuery.of(context).viewInsets.bottom;
    if (bottomViewInset == 0) {
      if (_bottomPadding != 0) {
        FocusScope.of(context).unfocus();
        _bottomPadding = 0;
      }
    }
    _bottomPadding = bottomViewInset;
    return WillPopScope(
      onWillPop: () async {
        if (mentionsState.showUsersForMentionsLayout) {
          mentionsState.showUsersForMentionsLayout = false;
          mentionsState.searchUsers.text = '';

          mentionsState.update();
          return false;
        }
        return true;
      },
      child: Material(
        child: Stack(
          children: [
            DidvanScaffold(
              hidePlayer: true,
              physics: const BouncingScrollPhysics(),
              backgroundColor: Theme.of(context).colorScheme.surface,
              appBarData: _isPage
                  ? AppBarData(
                      hasBack: true,
                      title: 'فراخوانی‌ها',
                      subtitle: widget.pageData['title'],
                    )
                  : null,
              padding: const EdgeInsets.only(left: 16, right: 16, bottom: 92),
              showSliversFirst: false,
              slivers: [
                Consumer<MentionsState>(
                  builder: (context, state, child) =>
                      SliverStateHandler<MentionsState>(
                    onRetry: state.getComments,
                    state: state,
                    itemPadding: const EdgeInsets.symmetric(vertical: 16),
                    childCount: state.comments.length,
                    placeholder: const _MentionPlaceholder(),
                    centerEmptyState: _isPage,
                    enableEmptyState: state.comments.isEmpty,
                    emptyState: EmptyState(
                        asset: Assets.emptyChat,
                        title: 'دوستان خود را فراخوانی کنید'),
                    builder: (context, state, index) => Mention(
                      key: ValueKey(
                        state.comments[index].id.toString() +
                            state.comments[index].text,
                      ),
                      focusNode: _focusNode,
                      comment: state.comments[index],
                    ),
                  ),
                ),
              ],
            ),
            AnimatedVisibility(
              duration: DesignConfig.lowAnimationDuration,
              isVisible: mentionsState.showUsersForMentionsLayout,
              child: BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0),
                child: Container(
                  decoration: BoxDecoration(
                      color: Theme.of(context)
                          .colorScheme
                          .focused
                          .withOpacity(0.5)),
                  child: DidvanScaffold(
                    hidePlayer: true,
                    appBarData: null,
                    padding: const EdgeInsets.only(
                        left: 16, right: 16, top: 16, bottom: 92),
                    backgroundColor: Colors.white.withOpacity(0.0),
                    showSliversFirst: false,
                    slivers: [
                      Consumer<MentionsState>(
                        builder: (context, state, child) =>
                            SliverStateHandler<MentionsState>(
                          onRetry: () {
                            state.getUsersMention(
                                context.read<UserProvider>().user.id);
                          },
                          state: state,
                          childCount: state.users.length,
                          placeholder: const _UsersPlaceholder(),
                          centerEmptyState: _isPage,
                          enableEmptyState: state.users.isEmpty,
                          emptyState: EmptyState(
                            asset: Assets.emptyBookmark,
                            title: 'لیست افراد خالی است',
                          ),
                          builder: (context, state, index) {
                            return UserMention(
                              user: state.users[index],
                              index: index,
                            );
                          },
                        ),
                      ),
                    ],
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: TextField(
                              controller: mentionsState.searchUsers,
                              focusNode: _focusNodeMention,
                              keyboardType: TextInputType.multiline,
                              textInputAction: TextInputAction.send,
                              style: Theme.of(context).textTheme.bodyMedium,
                              onEditingComplete: () {},
                              onChanged: (val) => _onChange(mentionsState, val),
                              decoration: InputDecoration(
                                icon: const Icon(DidvanIcons.search_regular),
                                border: InputBorder.none,
                                hintText: 'نام فرد مورد نظر را بنویسید...',
                                hintStyle: Theme.of(context)
                                    .textTheme
                                    .bodySmall!
                                    .copyWith(
                                        color: Theme.of(context)
                                            .colorScheme
                                            .disabledText),
                              ),
                            ),
                          ),
                          DidvanIconButton(
                              icon: DidvanIcons.close_regular,
                              onPressed: () {
                                mentionsState.showUsersForMentionsLayout =
                                    false;
                                mentionsState.searchUsers.text = '';

                                mentionsState.update();
                              }),
                        ],
                      ),
                      const SizedBox(
                        height: 4,
                      ),
                      Divider(
                        height: 1,
                        color: Theme.of(context).colorScheme.splash,
                      ),
                      const SizedBox(
                        height: 12,
                      )
                    ],
                  ),
                ),
              ),
            ),
            Positioned(
              left: 0,
              right: 0,
              bottom: MediaQuery.of(context).viewInsets.bottom,
              child: _MessageBox(
                focusNode: _focusNode,
                focusNodeMention: _focusNodeMention,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _MessageBox extends StatefulWidget {
  final FocusNode focusNode;
  final FocusNode focusNodeMention;

  const _MessageBox(
      {Key? key, required this.focusNode, required this.focusNodeMention})
      : super(key: key);

  @override
  State<_MessageBox> createState() => _MessageBoxState();
}

class _MessageBoxState extends State<_MessageBox> {
  @override
  Widget build(BuildContext context) {
    final state = context.watch<MentionsState>();
    return Column(
      children: [
        AnimatedVisibility(
          duration: DesignConfig.lowAnimationDuration,
          isVisible: state.showReplyBox,
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.secondCTA,
                  borderRadius: const BorderRadius.only(
                      topRight: Radius.circular(16),
                      topLeft: Radius.circular(16)),
                  boxShadow: [
                    BoxShadow(
                      color:
                          Theme.of(context).colorScheme.title.withOpacity(0.2),
                      offset: const Offset(
                        5.0,
                        5.0,
                      ),
                      blurRadius: 10.0,
                      spreadRadius: 2.0,
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    if (state.replyingTo != null)
                      DidvanText(
                        'پاسخ به ${state.replyingTo!.fullName}:',
                        color: Theme.of(context).colorScheme.primary,
                        style: Theme.of(context).textTheme.bodySmall,
                      ),
                    const Spacer(),
                    DidvanIconButton(
                      gestureSize: 24,
                      color: Theme.of(context).colorScheme.primary,
                      icon: DidvanIcons.close_regular,
                      onPressed: () {
                        state.commentId = null;
                        state.replyingTo = null;
                        state.showReplyBox = false;
                        state.update();
                      },
                    ),
                  ],
                ),
              ),
              Container(
                color: Theme.of(context).colorScheme.secondCTA,
                padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
                child: Divider(
                  height: 2,
                  color: Theme.of(context).colorScheme.border,
                ),
              )
            ],
          ),
        ),
        AnimatedVisibility(
          duration: DesignConfig.lowAnimationDuration,
          isVisible: state.mentionedUsers.isNotEmpty,
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.secondCTA,
                    borderRadius: !state.showReplyBox
                        ? const BorderRadius.only(
                            topLeft: Radius.circular(16),
                            topRight: Radius.circular(16))
                        : null),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          color: Theme.of(context).colorScheme.primary,
                          width: 2,
                          height: 40,
                        ),
                        const SizedBox(
                          width: 8,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            DidvanText(
                              "اشاره به",
                              color: Theme.of(context).colorScheme.text,
                              style: Theme.of(context).textTheme.labelSmall,
                            ),
                            DidvanText(
                              state.mentionedUsers
                                      .sublist(0,
                                          min(state.mentionedUsers.length, 2))
                                      .map((user) => user.name)
                                      .join("، ") +
                                  (state.mentionedUsers.length > 2
                                      ? " و ${state.mentionedUsers.length - 2} مورد دیگر"
                                      : ""),
                              color: Theme.of(context).colorScheme.text,
                              style: Theme.of(context).textTheme.bodySmall,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ],
                        )
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        DidvanIconButton(
                          gestureSize: 24,
                          color: Theme.of(context).colorScheme.primary,
                          icon: DidvanIcons.close_regular,
                          onPressed: () {
                            state.mentionedUsers = [];
                            state.update();
                          },
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
        Container(
          decoration: BoxDecoration(
            color: Theme.of(context).colorScheme.surface,
            border: Border(
              top: BorderSide(
                color: Theme.of(context).colorScheme.border,
              ),
            ),
          ),
          child: Row(
            children: [
              state.mentionedUsers.isEmpty
                  ? DidvanIconButton(
                      onPressed: () {
                        state.showUsersForMentionsLayout = true;
                        widget.focusNodeMention.requestFocus();
                        state.update();
                      },
                      icon: DidvanIcons.mention_icon,
                      size: 24,
                      color: Theme.of(context).colorScheme.focusedBorder,
                    )
                  : DidvanIconButton(
                      onPressed: () => _onSend(state),
                      icon: DidvanIcons.send_solid,
                      size: 24,
                      color: Theme.of(context).colorScheme.focusedBorder,
                    ),
              Expanded(
                child: TextField(
                  focusNode: widget.focusNode,
                  controller: state.textFieldController,
                  keyboardType: TextInputType.multiline,
                  textInputAction: TextInputAction.send,
                  style: Theme.of(context).textTheme.bodyMedium,
                  onTap: () {
                    if (state.mentionedUsers.isEmpty) {
                      state.showUsersForMentionsLayout = true;
                      widget.focusNodeMention.requestFocus();
                      state.update();
                    }
                  },
                  onEditingComplete: () {},
                  onSubmitted: (value) => _onSend(state),
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    hintMaxLines: 2,
                    hintText: state.mentionedUsers.isEmpty
                        ? 'همکاران خود را فراخوانی کنید'
                        : 'پیام خود را ارسال کنید',
                    hintStyle: Theme.of(context).textTheme.bodySmall!.copyWith(
                        color: Theme.of(context).colorScheme.disabledText),
                  ),
                ),
              ),
              if (!state.showUsersForMentionsLayout &&
                  state.mentionedUsers.isNotEmpty)
                DidvanIconButton(
                  onPressed: () {
                    state.showUsersForMentionsLayout = true;
                    widget.focusNodeMention.requestFocus();
                    state.update();
                  },
                  icon: DidvanIcons.mention_icon,
                  size: 24,
                  color: Theme.of(context).colorScheme.focusedBorder,
                ),
            ],
          ),
        ),
      ],
    );
  }

  void _onSend(MentionsState state) {
    if (state.textFieldController.text.replaceAll(' ', '').isNotEmpty &&
        state.mentionedUsers.isNotEmpty) {
      state.addMention();
    }
  }
}

class _MentionPlaceholder extends StatelessWidget {
  const _MentionPlaceholder({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ShimmerPlaceholder(
          height: 24,
          width: 24,
          borderRadius: DesignConfig.highBorderRadius,
        ),
        SizedBox(width: 16),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  ShimmerPlaceholder(
                    height: 20,
                    width: 100,
                  ),
                  ShimmerPlaceholder(
                    height: 14,
                    width: 100,
                  ),
                ],
              ),
              SizedBox(height: 12),
              ShimmerPlaceholder(
                height: 16,
                width: double.infinity,
              ),
              SizedBox(height: 8),
              ShimmerPlaceholder(
                height: 16,
                width: 200,
              ),
              SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ShimmerPlaceholder(
                    height: 24,
                    width: 48,
                  ),
                  SizedBox(width: 8),
                  ShimmerPlaceholder(
                    height: 24,
                    width: 48,
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class _UsersPlaceholder extends StatelessWidget {
  const _UsersPlaceholder({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ShimmerPlaceholder(
          height: 40,
          width: 40,
          borderRadius: DesignConfig.highBorderRadius,
        ),
        SizedBox(width: 16),
        Expanded(
          child: ShimmerPlaceholder(
            borderRadius: DesignConfig.highBorderRadius,
            height: 40,
          ),
        ),
      ],
    );
  }
}
