import 'dart:async'; // اضافه کردن کتابخانه برای استفاده از Timer
import 'package:business_panel/presentation/home/bloc/home_bloc.dart';
import 'package:business_panel/presentation/widgets/active_discount_card.dart';
import 'package:business_panel/presentation/widgets/custom_app_bar_single.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:business_panel/gen/assets.gen.dart';

class DiscountManegment extends StatefulWidget {
  const DiscountManegment({super.key});

  @override
  State<DiscountManegment> createState() => _DiscountManegmentState();
}

class _DiscountManegmentState extends State<DiscountManegment> {
  final TextEditingController _searchController = TextEditingController();
  Timer? _debounce;

  @override
  void initState() {
    super.initState();
    // Fetch initial discounts when the page loads
    // Note: Using addPostFrameCallback to ensure context is available
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        context.read<HomeBloc>().add(FetchDiscounts());
      }
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    _debounce?.cancel(); // کنسل کردن تایمر برای جلوگیری از نشت حافظه
    super.dispose();
  }

  void _onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) _debounce!.cancel();
    _debounce = Timer(const Duration(milliseconds: 500), () {
      if (mounted) {
        context.read<HomeBloc>().add(SearchDiscounts(query: query));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBarSingle(
        page: "رزرو ها",
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: 'دنبال چی می‌گردی؟',
                hintStyle: TextStyle(color: Color.fromARGB(255, 157, 157, 157)),
                prefixIcon: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: SvgPicture.asset(
                    Assets.icons.riSearch2Line,
                  ),
                ),
                fillColor: Color.fromARGB(255, 244, 244, 244),
                filled: true,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(50),
                  borderSide: BorderSide.none,
                ),
                contentPadding: const EdgeInsets.symmetric(vertical: 0),
              ),
              onChanged: _onSearchChanged, // استفاده از متد جدید
            ),
          ),
          Expanded(
            child: BlocBuilder<HomeBloc, HomeState>(
              builder: (context, state) {
                if (state is HomeError) {
                  return Center(child: Text('خطا: ${state.message}'));
                }

                if (state is HomeLoaded) {
                  if (state.discounts.isEmpty) {
                    return const Center(child: Text("هیچ تخفیفی با این مشخصات یافت نشد."));
                  }
                  return RefreshIndicator(
                    onRefresh: () async {
                      context.read<HomeBloc>().add(FetchDiscounts());
                      _searchController.clear();
                    },
                    child: ListView.builder(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      itemCount: state.discounts.length,
                      itemBuilder: (context, index) {
                        final discount = state.discounts[index];
                        return ActiveDiscountCard(discount: discount);
                      },
                    ),
                  );
                }

                return const Center(child: CircularProgressIndicator());
              },
            ),
          ),
        ],
      ),
    );
  }
}