import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/logout/logout_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/components/profile_avatar.dart';
import 'package:peasmartcare/pages/auth/register.dart';
import 'package:peasmartcare/widgets/loading.dart';

class LogoutPage extends StatefulWidget {
  @override
  _LogoutPageState createState() => _LogoutPageState();
}

class _LogoutPageState extends State<LogoutPage> {
  @override
  void initState() {
    context.read<LogoutBloc>().add(LogoutOnPressed());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PEAAppBar(
        leading: Stack(
          children: <Widget>[
            ProfileAvatar(),
          ],
        ),
        title: Text("ออกจากระบบ"),
      ),
      body: BodyLayout(
        layoutType: LayoutType.ONLY_CHILD,
        child: Container(
          child: BlocListener<LogoutBloc, LogoutState>(
            listener: (context, state) {
              if (state is LogoutLoaded) {
                if (state.result) {
                  Navigator.of(context).popUntil((route) => route.isFirst);
                  Navigator.pushReplacement(
                    context,
                    // MaterialPageRoute(builder: (context) => LoginPage()),
                    MaterialPageRoute(builder: (context) => RegisterPage()),
                  );
                }
              } else if (state is LogoutErrorUnauthorized) {
                Navigator.of(context).popUntil((route) => route.isFirst);
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(builder: (context) => LogoutPage()),
                );
              }
            },
            child: BlocBuilder<LogoutBloc, LogoutState>(
              builder: (context, state) {
                return Loading();
              },
            ),
          ),
        ),
      ),
    );
  }
}
