import 'package:business_panel/core/config/app_colors.dart';
import 'package:business_panel/gen/assets.gen.dart';
import 'package:business_panel/presentation/home/bloc/home_bloc.dart';
import 'package:business_panel/presentation/pages/add_discount_page.dart';
import 'package:business_panel/presentation/widgets/custom_app_bar.dart';
import 'package:business_panel/presentation/widgets/discount_card.dart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const CustomAppBar(),
      body: BlocBuilder<HomeBloc, HomeState>(
        builder: (context, state) {
          // --- منطق اصلاح‌شده برای مدیریت وضعیت ---
          if (state is HomeError) {
            return Center(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text('خطا: ${state.message}', textAlign: TextAlign.center),
              ),
            );
          }

          if (state is HomeLoaded) {
            if (state.discounts.isEmpty) {
              return _buildEmptyState(context);
            }
            return RefreshIndicator(
              onRefresh: () async {
                context.read<HomeBloc>().add(FetchDiscounts());
              },
              child: ListView.builder(
                padding: const EdgeInsets.all(16),
                itemCount: state.discounts.length + 1,
                itemBuilder: (context, index) {
                  if (index == state.discounts.length) {
                    return _buildAddDiscountButton(context);
                  }
                  final discount = state.discounts[index];
                  return DiscountCard(discount: discount);
                },
              ),
            );
          }

          // برای حالت‌های HomeInitial و HomeLoading
          return const Center(child: CircularProgressIndicator());
        },
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SvgPicture.asset(Assets.icons.emptyHome, height: 300),
          const SizedBox(height: 35),
          const Text("سلام!", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 17)),
          const SizedBox(height: 15),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 24.0),
            child: Column(
              children: [
                _buildAddDiscountButton(context),
                const SizedBox(height: 5),
                _todayState()
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAddDiscountButton(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 16.0),
      child: SizedBox(
        width: double.infinity,
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: AppColors.confirm,
            padding: const EdgeInsets.symmetric(vertical: 14),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(40),
            ),
          ),
          onPressed: () {
            Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const AddDiscountPage()),
            ).then((_) {
              context.read<HomeBloc>().add(FetchDiscounts());
            });
          },
          child: const Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.add, color: Colors.white),
              SizedBox(width: 8),
              Text(
                "تعریف تخفیف جدید",
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.normal,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _todayState() {
    return Padding(
      padding: const EdgeInsets.only(top: 16.0),
      child: SizedBox(
        width: double.infinity,
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: AppColors.active,
            padding: const EdgeInsets.symmetric(vertical: 14),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(40),
            ),
          ),
          onPressed: () {},
          child: const Text(
            "خلاصه عملکرد امروز",
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.normal,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }
}