// ignore_for_file: deprecated_member_use

import 'package:didvan/config/design_config.dart';
import 'package:didvan/views/authentication/authentication_state.dart';
import 'package:didvan/views/authentication/screens/password.dart';
import 'package:didvan/views/authentication/screens/reset_password.dart';
import 'package:didvan/views/authentication/screens/username.dart';
import 'package:didvan/views/authentication/screens/verification.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Authentication extends StatefulWidget {
  final bool isResetPassword;
  const Authentication({Key? key, required this.isResetPassword})
      : super(key: key);

  @override
  State<Authentication> createState() => _AuthenticationState();
}

class _AuthenticationState extends State<Authentication> {
  late final List<Widget> _pages;

  @override
  void initState() {
    if (widget.isResetPassword) {
      _pages = const [
        Verification(),
        ResetPassword(),
      ];
    } else {
      _pages = const [
        UsernameInput(),
        PasswordInput(),
        Verification(),
        ResetPassword(),
      ];
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Consumer<AuthenticationState>(
        builder: (context, state, child) => WillPopScope(
          onWillPop: () async {
             if (state.currentPageIndex == 0) {
              return true;
            }
            // Check if on OTP screen and no password exists
            if (state.currentPageIndex == 2 && !state.hasPassword) {
              state.currentPageIndex = 0; // Go back to username screen
              return false;
            }
            state.currentPageIndex--;
            return false;
          },
          child: AnimatedSwitcher(
            duration: DesignConfig.mediumAnimationDuration,
            child: _pages[state.currentPageIndex],
          ),
        ),
      ),
    );
  }
}
