import 'package:business_panel/presentation/auth/bloc/auth_bloc.dart';
import 'package:business_panel/presentation/home/bloc/home_bloc.dart';
import 'package:business_panel/presentation/pages/home_page.dart';
import 'package:business_panel/presentation/pages/onboarding_page.dart';
import 'package:business_panel/presentation/pages/store_info.dart';
import 'package:business_panel/presentation/store_info/bloc/store_info_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

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

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  @override
  void initState() {
    super.initState();
    context.read<AuthBloc>().add(CheckAuthStatus());
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AuthBloc, AuthState>(
      listener: (context, state) {
        if (state is AuthChecked) {
          if (state.hasToken) {
            context.read<AuthBloc>().add(CheckShopStatus());
          } else {
            Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (_) => const OnboardingPage()),
            );
          }
        }  else if (state is ShopExists) {
          // کاربر هم توکن دارد و هم فروشگاه، به HomePage می‌رود
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(
              builder: (_) => BlocProvider(
                create: (context) => HomeBloc(),
                child: const HomePage(),
              ),
            ),
          );
        } else if (state is NoShop) {
          // کاربر توکن دارد ولی فروشگاه نساخته، به صفحه ساخت فروشگاه می‌رود
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(
              builder: (_) => BlocProvider(
                create: (context) => StoreInfoBloc(),
                child: const StoreInfoPage(),
              ),
            ),
          );
        } else if (state is AuthFailure) {
            // اگر در هر مرحله خطایی رخ داد، کاربر را به صفحه لاگین بفرست
             Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (_) => const OnboardingPage()),
            );
        }
      },
      child: const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      ),
    );
  }
}