import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../../widgets/alert/data_alert_model.dart';
import '../../widgets/back_button.dart';
import '../../widgets/custom_empty_widget.dart';
import '../../widgets/custom_navigation_bar.dart';
import '../../widgets/image_loader.dart';
import 'models/notification_item_model.dart';
import 'notification_viewmodel.dart';

class NotificationScreen extends BaseScreen {
  const NotificationScreen({super.key});

  @override
  State<NotificationScreen> createState() => _NotificationScreenState();
}

class _NotificationScreenState extends BaseState<NotificationScreen> with BasicState {
  final _scrollController = ScrollController();
  final _viewModel = Get.put(NotificationViewModel());
  final LayerLink _layerLink = LayerLink();
  final GlobalKey _infoKey = GlobalKey();
  OverlayEntry? _popupEntry;
  bool _isPopupShown = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 100) {
        _viewModel.fetchNotifications(refresh: false);
      }
    });
    _viewModel.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(content: message);
      }
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(
        title: "Thông báo",
        rightButtons: [
          CompositedTransformTarget(
            link: _layerLink,
            child: IconButton(
              key: _infoKey,
              icon: const Icon(Icons.settings, color: Colors.black54),
              onPressed: _toggleSetting,
            ),
          ),
        ],
      ),
      body: Obx(() {
        final items = _viewModel.notifications;
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildNotificationCategory(),
            const Divider(height: 1),
            if (items.isEmpty)
              const Expanded(
                child: EmptyWidget(),
              )
            else
              Expanded(
                child: Container(
                  color: Colors.grey.shade100,
                  child: RefreshIndicator(
                    onRefresh: () async {
                      _viewModel.fetchNotifications(refresh: true);
                    },
                    child: ListView.builder(
                      controller: _scrollController,
                      padding: const EdgeInsets.all(16),
                      itemCount: items.length,
                      itemBuilder: (_, index) {
                        final item = items[index];
                        return _buildNotificationItem(item);
                      },
                    ),
                  ),
                ),
              ),
          ],
        );
      }),
    );
  }

  void _toggleSetting() {
    if (_isPopupShown) {
      _hidePopup();
    } else {
      _showPopup();
    }
  }

  void _showPopup() {
    final overlay = Overlay.of(context);
    final renderBox = _infoKey.currentContext?.findRenderObject() as RenderBox?;
    final offset = renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
    final size = renderBox?.size ?? Size.zero;
    final double widthSize = 270;
    _popupEntry = OverlayEntry(
      builder: (context) => Stack(
        children: [
          Positioned.fill(
            child: GestureDetector(
              onTap: _hidePopup,
              behavior: HitTestBehavior.translucent,
              child: Container(color: Colors.transparent),
            ),
          ),
          Positioned(
            top: offset.dy + size.height + 8,
            left: MediaQuery.of(context).size.width - widthSize - 16,
            child: Material(
              borderRadius: BorderRadius.circular(16),
              elevation: 4,
              child: Container(
                width: widthSize,
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey.shade50,
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ListTile(
                      title: const Text('Đánh dấu tất cả đã đọc', style: TextStyle(fontWeight: FontWeight.w500)),
                      onTap: () {
                        _hidePopup();
                        _viewModel.notificationMarkAsSeen();
                      },
                    ),
                    const Divider(height: 1, color: Colors.grey),
                    ListTile(
                      title: const Text('Xoá tất cả', style: TextStyle(color: Colors.red, fontWeight: FontWeight.w500)),
                      onTap: () {
                        _hidePopup();
                        _confirmDeleteAllNotifications();
                      }
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
    overlay.insert(_popupEntry!);
    _isPopupShown = true;
  }

  _confirmDeleteAllNotifications() {
    final dataAlert = DataAlertModel(
      title: "Xoá tất cả",
      description: "Bạn có muốn xoá hết tất cả thông báo không? \nLưu ý: bạn sẽ không thể xem lại thông báo đã xoá",
      localHeaderImage: "assets/images/ic_pipi_03.png",
      buttons: [
        AlertButton(
          text: "Xoá",
          onPressed: () {
            Get.back();
            _viewModel.deleteAllNotifications();
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(text: "Huỷ", onPressed: () => Get.back(), bgColor: Colors.white, textColor: BaseColor.second500),
      ],
    );
    showAlert(data: dataAlert);
  }

  void _hidePopup() {
    _popupEntry?.remove();
    _popupEntry = null;
    _isPopupShown = false;
  }

  Widget _buildNotificationCategory() {
    final categories = _viewModel.categories;
    return SizedBox(
      height: 60,
      child: Center(
        child: ListView.separated(
          scrollDirection: Axis.horizontal,
          padding: const EdgeInsets.symmetric(horizontal: 12),
          itemCount: categories.length,
          separatorBuilder: (_, __) => const SizedBox(width: 12),
          itemBuilder: (_, index) {
            final cat = categories[index];
            final selected = cat.isSelected ?? false;
            return GestureDetector(
              onTap: () => _viewModel.selectCategory(index),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Stack(
                    clipBehavior: Clip.none,
                    children: [
                      Row(
                        children: [
                          const SizedBox(width: 4),
                          Text(
                            " ${cat.nameVi ?? ''} ",
                            style: TextStyle(
                              color: selected ? Colors.red : Colors.black87,
                              fontSize: 16,
                              fontWeight: selected ? FontWeight.bold : FontWeight.normal,
                            ),
                          ),
                          const SizedBox(width: 4),
                        ],
                      ),
                      if ((cat.totalUnread ?? 0) > 0)
                        Positioned(
                          top: -6,
                          right: 0,
                          child: Container(
                            width: 6,
                            height: 6,
                            decoration: const BoxDecoration(shape: BoxShape.circle, color: Colors.red),
                          ),
                        ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    height: 2,
                    width: selected ? 32 : 0,
                    color: Colors.red,
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildNotificationItem(NotificationItemModel item) {
    return Dismissible(
      key: ValueKey(item.notificationId ?? item.createTime),
      direction: DismissDirection.endToStart,
      background: Container(
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.symmetric(horizontal: 20),
        color: Colors.red,
        child: const Icon(Icons.delete, color: Colors.white),
      ),
      onDismissed: (direction) {
        _viewModel.handleRemoveNotification(item);
        // _viewModel.notifications.remove(item);
      },
      child: GestureDetector(
        onTap: () {
          _viewModel.handleClickNotification(item);
          // item.directionalScreen?.begin();
          setState(() {
            item.seenAt = DateTime.now().toString();
          });
        },
        child: Container(
          margin: const EdgeInsets.only(bottom: 12),
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
              color: item.hasSeen ? Colors.white : Colors.pink.shade50,
              borderRadius: BorderRadius.circular(12)
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: loadNetworkImage(
                      url: item.workingSite?.avatar ?? "",
                      fit: BoxFit.cover,
                      width: 40,
                      height: 40,
                      placeholderAsset: 'assets/images/ic_logo.png',
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(item.title ?? '', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15)),
                        const SizedBox(height: 8),
                        Text(item.body ?? '', style: const TextStyle(fontSize: 14)),
                        const SizedBox(height: 8),
                        Text(item.createTime ?? '', style: const TextStyle(fontSize: 13, color: Colors.black54)),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
