import 'package:flutter/material.dart';

import '../screen/flash_sale/flash_sale_screen.dart'
    deferred as flash_sale show FlashSaleScreen;
import '../screen/data_network_service/data_network_service_screen.dart'
    deferred as data_network_service show DataNetworkServiceScreen;
import '../screen/webview/payment_web_view_screen.dart'
    deferred as payment_web_view show PaymentWebViewScreen;
import '../screen/achievement/achievement_list_screen.dart'
    deferred as achievement_list show AchievementListScreen;
import '../screen/affiliate/affiliate_tab_screen.dart'
    deferred as affiliate_tab show AffiliateTabScreen;
import '../screen/history_point/history_point_screen.dart'
    deferred as history_point show HistoryPointScreen;
import '../screen/bank_account_manager/bank_account_manager_screen.dart'
    deferred as bank_account_manager show BankAccountManagerScreen;
import '../screen/vplay_game_center/vplay_game_center_screen.dart'
    deferred as vplay_game_center show VplayGameCenterScreen;
import '../screen/health_book/health_book_screen.dart'
    deferred as health_book show HealthBookScreen;
import '../screen/invite_friend_campaign/invite_friend_campaign_screen.dart'
    deferred as invite_friend show InviteFriendCampaignScreen;
import '../screen/quiz_campaign/quiz_campaign_screen.dart'
    deferred as survey_question show SurveyQuestionScreen;
import '../screen/device_manager/device_manager_screen.dart'
    deferred as device_manager show DeviceManagerScreen;
import '../screen/order_menu/order_menu_screen.dart'
    deferred as order_menu show OrderMenuScreen;
import '../screen/location_address/location_address_screen.dart'
    deferred as location_address show LocationAddressScreen;
import '../screen/membership/membership_screen.dart'
    deferred as membership show MembershipScreen;
import '../screen/mobile_card/product_mobile_card_screen.dart'
    deferred as product_mobile_card show ProductMobileCardScreen;
import '../screen/history_point_cashback/history_point_cashback_screen.dart'
    deferred as history_point_cashback show HistoryPointCashBackScreen;
import '../screen/electric_payment/electric_payment_screen.dart'
    deferred as electric_payment show ElectricPaymentScreen;
import '../screen/electric_payment/electric_payment_history_screen.dart'
    deferred as electric_payment_history show ElectricPaymentHistoryScreen;
import '../screen/traffic_service/traffic_service_screen.dart'
    deferred as traffic_service show TrafficServiceScreen;
import '../screen/traffic_service/traffic_service_detail_screen.dart'
    deferred as traffic_service_detail show TrafficServiceDetailScreen;
import '../screen/campaign7day/campaign_7day_screen.dart'
    deferred as campaign_7day show Campaign7DayScreen;
import '../screen/daily_checkin/daily_checkin_screen.dart'
    deferred as daily_checkin show DailyCheckInScreen;
import '../screen/transaction/transactions_history_screen.dart'
    deferred as transactions_history show TransactionHistoryScreen;
import '../screen/news/news_list_screen.dart'
    deferred as news_list show NewsListScreen;
import '../screen/qr_code/qr_code_screen.dart'
    deferred as qr_code show QRCodeScreen;
import '../screen/affiliate_brand_detail/affiliate_brand_detail_screen.dart'
    deferred as affiliate_brand_detail show AffiliateBrandDetailScreen;
import '../screen/affiliate_brand_detail/affiliate_brand_list_screen.dart'
    deferred as affiliate_brand_list show AffiliateBrandListScreen;
import '../screen/affiliate_brand_detail/affiliate_category_grid_screen.dart'
    deferred as affiliate_category_grid show AffiliateCategoryGridScreen;
import '../screen/contacts/contacts_list_screen.dart'
    deferred as contacts_list show ContactsListScreen;
import '../screen/health_book/health_book_card_detail.dart'
    deferred as health_book_card_detail show HealthBookCardDetail;
import '../screen/interested_categories/interestied_categories_screen.dart'
    deferred as interest_categories show InterestCategoriesScreen;
import '../screen/support/support_screen.dart'
    deferred as support show SupportScreen;
import '../screen/topup/topup_screen.dart'
    deferred as topup show PhoneTopUpScreen;
import '../screen/transaction/history/transaction_history_detail_screen.dart'
    deferred as transaction_history_detail show TransactionHistoryDetailScreen;
import '../screen/transaction/transaction_detail_screen.dart'
    deferred as transaction_detail show TransactionDetailScreen;
import '../screen/voucher/detail/voucher_detail_screen.dart'
    deferred as voucher_detail show VoucherDetailScreen;
import '../screen/voucher/mobile_card/my_mobile_card_detail_widget.dart'
    deferred as mobile_card_detail show MyMobileCardDetailScreen;
import '../screen/voucher/mobile_card/my_mobile_card_list_widget.dart'
    deferred as mobile_card_list show MyMobileCardListScreen;
import '../screen/voucher/my_voucher/my_product_list_widget.dart'
    deferred as my_voucher_list show MyVoucherListScreen;

typedef DeferredScreenBuilder = Widget Function(BuildContext context);

/// Generic widget that handles loading a deferred library before rendering
/// the actual screen. This keeps the initial bundle smaller and only loads
/// heavy features when the user needs them.
class DeferredScreen extends StatefulWidget {
  const DeferredScreen({
    super.key,
    required this.loadLibrary,
    required this.builder,
    this.errorMessage,
  });

  final Future<void> Function() loadLibrary;
  final DeferredScreenBuilder builder;
  final String? errorMessage;

  @override
  State<DeferredScreen> createState() => DeferredScreenState();
}

class DeferredScreenState extends State<DeferredScreen> {
  late final Future<void> _loadFuture;

  @override
  void initState() {
    super.initState();
    _loadFuture = widget.loadLibrary();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<void>(
      future: _loadFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return widget.builder(context);
        }
        if (snapshot.hasError) {
          return _DeferredError(
            message: widget.errorMessage,
            error: snapshot.error,
          );
        }
        return const Scaffold(
          body: Center(
            child: CircularProgressIndicator(),
          ),
        );
      },
    );
  }
}

class _DeferredError extends StatelessWidget {
  const _DeferredError({this.message, this.error});

  final String? message;
  final Object? error;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.error_outline,
                size: 48,
                color: theme.colorScheme.error,
              ),
              const SizedBox(height: 16),
              Text(
                message ?? 'Không thể tải màn hình này.',
                textAlign: TextAlign.center,
                style: theme.textTheme.titleMedium,
              ),
              if (error != null) ...[
                const SizedBox(height: 12),
                Text(
                  '$error',
                  textAlign: TextAlign.center,
                  style: theme.textTheme.bodySmall,
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

class FlashSaleDeferredScreen extends StatelessWidget {
  const FlashSaleDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: flash_sale.loadLibrary,
      builder: (_) => flash_sale.FlashSaleScreen(),
      errorMessage: 'Không thể tải Flash Sale.',
    );
  }
}

class DataNetworkServiceDeferredScreen extends StatelessWidget {
  const DataNetworkServiceDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: data_network_service.loadLibrary,
      builder: (_) => data_network_service.DataNetworkServiceScreen(),
      errorMessage: 'Không thể tải dịch vụ data.',
    );
  }
}

class PaymentWebViewDeferredScreen extends StatelessWidget {
  const PaymentWebViewDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: payment_web_view.loadLibrary,
      builder: (_) => payment_web_view.PaymentWebViewScreen(),
      errorMessage: 'Không thể tải trang thanh toán.',
    );
  }
}

class AffiliateTabDeferredScreen extends StatelessWidget {
  const AffiliateTabDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: affiliate_tab.loadLibrary,
      builder: (_) => affiliate_tab.AffiliateTabScreen(),
      errorMessage: 'Không thể tải chiến dịch Affiliate.',
    );
  }
}

class HistoryPointDeferredScreen extends StatelessWidget {
  const HistoryPointDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: history_point.loadLibrary,
      builder: (_) => history_point.HistoryPointScreen(),
      errorMessage: 'Không thể tải lịch sử điểm.',
    );
  }
}

class BankAccountManagerDeferredScreen extends StatelessWidget {
  const BankAccountManagerDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: bank_account_manager.loadLibrary,
      builder: (_) => bank_account_manager.BankAccountManagerScreen(),
      errorMessage: 'Không thể tải quản lý tài khoản ngân hàng.',
    );
  }
}

class VplayGameCenterDeferredScreen extends StatelessWidget {
  const VplayGameCenterDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: vplay_game_center.loadLibrary,
      builder: (_) => vplay_game_center.VplayGameCenterScreen(),
      errorMessage: 'Không thể tải Vplay Game Center.',
    );
  }
}

class HealthBookDeferredScreen extends StatelessWidget {
  const HealthBookDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: health_book.loadLibrary,
      builder: (_) => health_book.HealthBookScreen(),
      errorMessage: 'Không thể tải Sổ sức khỏe.',
    );
  }
}

class SurveyQuestionDeferredScreen extends StatelessWidget {
  const SurveyQuestionDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: survey_question.loadLibrary,
      builder: (_) => survey_question.SurveyQuestionScreen(),
      errorMessage: 'Không thể tải khảo sát.',
    );
  }
}

class DeviceManagerDeferredScreen extends StatelessWidget {
  const DeviceManagerDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: device_manager.loadLibrary,
      builder: (_) => device_manager.DeviceManagerScreen(),
      errorMessage: 'Không thể tải quản lý thiết bị.',
    );
  }
}

class AchievementListDeferredScreen extends StatelessWidget {
  const AchievementListDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: achievement_list.loadLibrary,
      builder: (_) => achievement_list.AchievementListScreen(),
      errorMessage: 'Không thể tải thành tích.',
    );
  }
}

class InviteFriendDeferredScreen extends StatelessWidget {
  const InviteFriendDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: invite_friend.loadLibrary,
      builder: (_) => invite_friend.InviteFriendCampaignScreen(),
      errorMessage: 'Không thể tải chiến dịch giới thiệu.',
    );
  }
}

class OrderMenuDeferredScreen extends StatelessWidget {
  const OrderMenuDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: order_menu.loadLibrary,
      builder: (_) => order_menu.OrderMenuScreen(),
      errorMessage: 'Không thể tải đặt món.',
    );
  }
}

class LocationAddressDeferredScreen extends StatelessWidget {
  const LocationAddressDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: location_address.loadLibrary,
      builder: (_) => location_address.LocationAddressScreen(),
      errorMessage: 'Không thể tải địa chỉ.',
    );
  }
}

class MembershipDeferredScreen extends StatelessWidget {
  const MembershipDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: membership.loadLibrary,
      builder: (_) => membership.MembershipScreen(),
      errorMessage: 'Không thể tải hạng thành viên.',
    );
  }
}

class ProductMobileCardDeferredScreen extends StatelessWidget {
  const ProductMobileCardDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: product_mobile_card.loadLibrary,
      builder: (_) => product_mobile_card.ProductMobileCardScreen(),
      errorMessage: 'Không thể tải thẻ điện thoại.',
    );
  }
}

class HistoryPointCashBackDeferredScreen extends StatelessWidget {
  const HistoryPointCashBackDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: history_point_cashback.loadLibrary,
      builder: (_) => history_point_cashback.HistoryPointCashBackScreen(),
      errorMessage: 'Không thể tải hoàn điểm.',
    );
  }
}

class ElectricPaymentDeferredScreen extends StatelessWidget {
  const ElectricPaymentDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: electric_payment.loadLibrary,
      builder: (_) => electric_payment.ElectricPaymentScreen(),
      errorMessage: 'Không thể tải thanh toán điện.',
    );
  }
}

class ElectricPaymentHistoryDeferredScreen extends StatelessWidget {
  const ElectricPaymentHistoryDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: electric_payment_history.loadLibrary,
      builder: (_) => electric_payment_history.ElectricPaymentHistoryScreen(),
      errorMessage: 'Không thể tải lịch sử điện.',
    );
  }
}

class TrafficServiceDeferredScreen extends StatelessWidget {
  const TrafficServiceDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: traffic_service.loadLibrary,
      builder: (_) => traffic_service.TrafficServiceScreen(),
      errorMessage: 'Không thể tải dịch vụ giao thông.',
    );
  }
}

class TrafficServiceDetailDeferredScreen extends StatelessWidget {
  const TrafficServiceDetailDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: traffic_service_detail.loadLibrary,
      builder: (_) => traffic_service_detail.TrafficServiceDetailScreen(),
      errorMessage: 'Không thể tải chi tiết giao thông.',
    );
  }
}

class Campaign7DayDeferredScreen extends StatelessWidget {
  const Campaign7DayDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: campaign_7day.loadLibrary,
      builder: (_) => campaign_7day.Campaign7DayScreen(),
      errorMessage: 'Không thể tải chiến dịch 7 ngày.',
    );
  }
}

class DailyCheckInDeferredScreen extends StatelessWidget {
  const DailyCheckInDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: daily_checkin.loadLibrary,
      builder: (_) => daily_checkin.DailyCheckInScreen(),
      errorMessage: 'Không thể tải điểm danh hằng ngày.',
    );
  }
}

class TransactionHistoryDeferredScreen extends StatelessWidget {
  const TransactionHistoryDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: transactions_history.loadLibrary,
      builder: (_) => transactions_history.TransactionHistoryScreen(),
      errorMessage: 'Không thể tải lịch sử giao dịch.',
    );
  }
}

class NewsListDeferredScreen extends StatelessWidget {
  const NewsListDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: news_list.loadLibrary,
      builder: (_) => news_list.NewsListScreen(),
      errorMessage: 'Không thể tải tin tức.',
    );
  }
}

class QRCodeDeferredScreen extends StatelessWidget {
  const QRCodeDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: qr_code.loadLibrary,
      builder: (_) => qr_code.QRCodeScreen(),
      errorMessage: 'Không thể mở QR Code.',
    );
  }
}

class AffiliateBrandDetailDeferredScreen extends StatelessWidget {
  const AffiliateBrandDetailDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: affiliate_brand_detail.loadLibrary,
      builder: (_) => affiliate_brand_detail.AffiliateBrandDetailScreen(),
      errorMessage: 'Không thể tải chi tiết thương hiệu.',
    );
  }
}

class AffiliateBrandListDeferredScreen extends StatelessWidget {
  const AffiliateBrandListDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: affiliate_brand_list.loadLibrary,
      builder: (_) => affiliate_brand_list.AffiliateBrandListScreen(),
      errorMessage: 'Không thể tải danh sách thương hiệu.',
    );
  }
}

class AffiliateCategoryGridDeferredScreen extends StatelessWidget {
  const AffiliateCategoryGridDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: affiliate_category_grid.loadLibrary,
      builder: (_) => affiliate_category_grid.AffiliateCategoryGridScreen(),
      errorMessage: 'Không thể tải danh mục thương hiệu.',
    );
  }
}

class ContactsListDeferredScreen extends StatelessWidget {
  const ContactsListDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: contacts_list.loadLibrary,
      builder: (_) => contacts_list.ContactsListScreen(),
      errorMessage: 'Không thể tải danh bạ.',
    );
  }
}

class HealthBookCardDetailDeferredScreen extends StatelessWidget {
  const HealthBookCardDetailDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: health_book_card_detail.loadLibrary,
      builder: (_) => health_book_card_detail.HealthBookCardDetail(),
      errorMessage: 'Không thể tải chi tiết sổ sức khỏe.',
    );
  }
}

class InterestCategoriesDeferredScreen extends StatelessWidget {
  const InterestCategoriesDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: interest_categories.loadLibrary,
      builder: (_) => interest_categories.InterestCategoriesScreen(),
      errorMessage: 'Không thể tải danh mục quan tâm.',
    );
  }
}

class SupportDeferredScreen extends StatelessWidget {
  const SupportDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: support.loadLibrary,
      builder: (_) => support.SupportScreen(),
      errorMessage: 'Không thể tải hỗ trợ.',
    );
  }
}

class PhoneTopUpDeferredScreen extends StatelessWidget {
  const PhoneTopUpDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: topup.loadLibrary,
      builder: (_) => topup.PhoneTopUpScreen(),
      errorMessage: 'Không thể tải nạp điện thoại.',
    );
  }
}

class TransactionDetailDeferredScreen extends StatelessWidget {
  const TransactionDetailDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: transaction_detail.loadLibrary,
      builder: (_) => transaction_detail.TransactionDetailScreen(),
      errorMessage: 'Không thể tải chi tiết giao dịch.',
    );
  }
}

class TransactionHistoryDetailDeferredScreen extends StatelessWidget {
  const TransactionHistoryDetailDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: transaction_history_detail.loadLibrary,
      builder: (_) => transaction_history_detail.TransactionHistoryDetailScreen(),
      errorMessage: 'Không thể tải chi tiết lịch sử giao dịch.',
    );
  }
}

class VoucherDetailDeferredScreen extends StatelessWidget {
  const VoucherDetailDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: voucher_detail.loadLibrary,
      builder: (_) => voucher_detail.VoucherDetailScreen(),
      errorMessage: 'Không thể tải chi tiết voucher.',
    );
  }
}

class MyMobileCardListDeferredScreen extends StatelessWidget {
  const MyMobileCardListDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: mobile_card_list.loadLibrary,
      builder: (_) => mobile_card_list.MyMobileCardListScreen(),
      errorMessage: 'Không thể tải thẻ điện thoại của tôi.',
    );
  }
}

class MyMobileCardDetailDeferredScreen extends StatelessWidget {
  const MyMobileCardDetailDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: mobile_card_detail.loadLibrary,
      builder: (_) => mobile_card_detail.MyMobileCardDetailScreen(),
      errorMessage: 'Không thể tải chi tiết thẻ điện thoại.',
    );
  }
}

class MyVoucherListDeferredScreen extends StatelessWidget {
  const MyVoucherListDeferredScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return DeferredScreen(
      loadLibrary: my_voucher_list.loadLibrary,
      builder: (_) => my_voucher_list.MyVoucherListScreen(),
      errorMessage: 'Không thể tải ưu đãi của tôi.',
    );
  }
}
