import 'dart:async';
import 'package:business_panel/presentation/reservation/bloc/reservation_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:business_panel/domain/entities/discount_entity.dart';
import 'package:business_panel/domain/entities/reservation_entity.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';

extension ReservationToDiscount on ReservationEntity {
  DiscountEntity toDiscountEntity() {
    return DiscountEntity(
      id: id,
      name: discount.name,
      shopName: 'فروشگاه',
      images: discount.images.map((img) => img.url).toList(),
      type: discount.typeName, 
      description: 'رزرو شده', 
      price: 0.0, 
      nPrice: 0.0,
      startDate: null,
      endDate: discount.endDate,
    );
  }
}

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

  @override
  State<ReserveManegmment> createState() => _ReserveManegmmentState();
}

class _ReserveManegmmentState extends State<ReserveManegmment> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => ReservationBloc()..add(FetchReservations()),
      child: const _ReserveManegmmentView(),
    );
  }
}

class _ReserveManegmmentView extends StatefulWidget {
  const _ReserveManegmmentView();

  @override
  State<_ReserveManegmmentView> createState() => _ReserveManegmmentViewState();
}

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

  @override
  void initState() {
    super.initState();
  }

  @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<ReservationBloc>().add(SearchReservations(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<ReservationBloc, ReservationState>(
              builder: (context, state) {
                if (state is ReservationError) {
                  return Center(child: Text('خطا: ${state.message}'));
                }

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

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