import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/modal_outlet_bottom.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/core/router/app_route.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/enums/message_activity_type.dart';
import 'package:niogu_app/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:sizer/sizer.dart';

class PopupNotification extends ConsumerWidget {
  final bool isOwner;
  final List<String> messages;
  final MessageActivityType type;
  const PopupNotification({
    super.key,
    required this.isOwner,
    required this.messages,
    this.type = MessageActivityType.lock_activity,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final bool isTablet = 100.w >= 600;
    return PopScope(
      canPop: false,
      child: Container(
        color: Colors.black.withOpacity(0.5),
        child: Center(
          child: Material(
            color: Colors.transparent,
            child: Container(
              width: 85.w,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(5.w),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.2),
                    blurRadius: 20,
                    offset: const Offset(0, 10),
                  ),
                ],
              ),
              constraints: BoxConstraints(maxWidth: 85.w),
              child: type == MessageActivityType.lock_activity
                  ? _buildLockActivityMessage(context, isTablet)
                  : _buildOnlineOrderMessage(context, ref, isTablet),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildLockActivityMessage(BuildContext context, bool isTablet) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(vertical: 3.h),
          decoration: BoxDecoration(
            color: AppColor.primaryColor,
            borderRadius: BorderRadius.vertical(top: Radius.circular(5.w)),
          ),
          child: Column(
            children: [
              Icon(Icons.lock_person_rounded, color: Colors.white, size: 12.w),
              SizedBox(height: 1.5.h),
              Text(
                "Pemberhentian Aktivitas",
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: AppFontSize.medium.sp,
                ),
              ),
            ],
          ),
        ),

        Padding(
          padding: EdgeInsets.fromLTRB(6.w, 4.h, 6.w, 3.h),
          child: Text(
            messages[0],
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: (AppFontSize.medium - 1.25).sp,
              color: Colors.grey[800],
              height: 1.5,
            ),
          ),
        ),

        Padding(
          padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 3.h),
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () => SystemNavigator.pop(),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColor.primaryColor,
                  minimumSize: Size(double.infinity, 6.5.h),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(3.w),
                  ),
                ),
                child: Text(
                  "Tutup Aplikasi",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: AppFontSize.medium.sp,
                  ),
                ),
              ),

              if (isOwner) ...[
                SizedBox(height: 2.h),
                OutlinedButton.icon(
                  onPressed: () => showModalBottomSheet(
                    context: context,
                    useRootNavigator: true,
                    isScrollControlled: true,
                    constraints: const BoxConstraints(
                      maxWidth: double.infinity,
                    ),
                    builder: (context) => const ModalOutletBottom(),
                  ),
                  icon: Icon(Icons.swap_horiz, size: 7.w),
                  label: Text(
                    "Pindah ke Outlet Lain",
                    style: TextStyle(fontSize: AppFontSize.medium.sp),
                  ),
                  style: OutlinedButton.styleFrom(
                    foregroundColor: AppColor.primaryColor,
                    minimumSize: Size(double.infinity, 6.5.h),
                    side: BorderSide(
                      color: AppColor.primaryColor,
                      width: 0.35.w,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(3.w),
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      ],
    );
  }

  Future<void> _updateAlreadyRead(
    BuildContext context,
    WidgetRef ref,
    bool isProcessed,
  ) async {
    final router = GoRouter.of(context);
    try {
      await ref
          .read(onlineStoreControllerProvider.notifier)
          .updateAlreadyReadOrderOnline(messages[0]);

      if (!context.mounted) return;

      if (!isProcessed) {
        ref.read(messageActivityStateProvider.notifier).state = null;
        return;
      }

      final onlineOrderDetail = await ref
          .read(onlineStoreRepositoryProvider)
          .fetchOnlineOrderDetailById(messages[0]);

      await Future.delayed(const Duration(milliseconds: 800), () {
        router.pushNamed(
          AppRoute.onlineStoreOrderDetilScreen,
          extra: onlineOrderDetail,
        );
      });
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
    }
  }

  Widget _buildOnlineOrderMessage(
    BuildContext context,
    WidgetRef ref,
    bool isTablet,
  ) {
    final onlineStoreControllerState = ref.watch(onlineStoreControllerProvider);
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(vertical: 3.h),
          decoration: BoxDecoration(
            color: AppColor.primaryColor,
            borderRadius: BorderRadius.vertical(top: Radius.circular(5.w)),
          ),
          child: Column(
            children: [
              Icon(
                Icons.shopping_bag_outlined,
                color: Colors.white,
                size: 15.w,
              ),
              SizedBox(height: 2.h),
              Text(
                "Pesanan Baru Masuk!",
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: AppFontSize.medium.sp,
                ),
              ),
            ],
          ),
        ),

        Padding(
          padding: EdgeInsets.fromLTRB(6.w, 4.h, 6.w, 3.h),
          child: Column(
            children: [
              Text(
                "Pesanan #${messages[1]} dari ${messages[2]} telah diterima.",
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: (AppFontSize.medium - 1.25).sp,
                  color: Colors.grey[700],
                  height: 1.5,
                ),
              ),

              SizedBox(height: 1.h),

              Text(
                "Total Tagihan: ${messages[3]}",
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: (AppFontSize.medium - 1.25).sp,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ),

        Padding(
          padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 3.h),
          child: Column(
            children: [
              ElevatedButton(
                onPressed: onlineStoreControllerState.isLoading
                    ? null
                    : () async => await _updateAlreadyRead(context, ref, true),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColor.primaryColor,
                  minimumSize: Size(double.infinity, 6.5.h),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(3.w),
                  ),
                ),
                child: Text(
                  "Proses Pesanan",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: AppFontSize.medium.sp,
                  ),
                ),
              ),
              SizedBox(height: 2.h),
              OutlinedButton.icon(
                onPressed: onlineStoreControllerState.isLoading
                    ? null
                    : () async => await _updateAlreadyRead(context, ref, false),
                label: Text(
                  "Nanti Saja",
                  style: TextStyle(fontSize: AppFontSize.medium.sp),
                ),
                style: OutlinedButton.styleFrom(
                  foregroundColor: AppColor.primaryColor,
                  minimumSize: Size(double.infinity, 6.5.h),
                  side: BorderSide(color: AppColor.primaryColor, width: 0.35.w),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(3.w),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
