import 'package:flutter/material.dart';
import 'package:kmobile/features/auth/screens/mpin_screen.dart';
import 'package:kmobile/security/secure_storage.dart';
import 'package:kmobile/di/injection.dart';
import '../../l10n/app_localizations.dart';

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

  @override
  State<ChangeMpinScreen> createState() => _ChangeMpinScreenState();
}

class _ChangeMpinScreenState extends State<ChangeMpinScreen> {
  @override
  void initState() {
    super.initState();
    // Start the flow after the widget is built
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _startChangeMpin();
    });
  }

  void _startChangeMpin() async {
    final loc = AppLocalizations.of(context);

    // Step 1: Verify old PIN
    final oldPinVerified = await Navigator.of(context).push<bool>(
      MaterialPageRoute(
        builder: (_) => MPinScreen(
          mode: MPinMode.enter,
          disableBiometric: true,
          customTitle: loc.enterOldMpin,
          onCompleted: (oldPin) => _verifyOldPin(oldPin),
        ),
      ),
    );

    if (oldPinVerified != true) {
      if (mounted) Navigator.of(context).pop(false);
      return;
    }

    // Step 2 & 3: Set new PIN (which will internally navigate to confirm)
    // The onCompleted will be called after both set and confirm succeed
    final success = await Navigator.of(context).push<bool>(
      MaterialPageRoute(
        builder: (_) => MPinScreen(
          mode: MPinMode.set,
          customTitle: loc.enterNewMpin,
          customConfirmTitle: loc.confirmNewMpin,
          onCompleted: (newPin) async {
            // This is called after confirm succeeds and PIN is saved
            if (context.mounted) {
              Navigator.of(context).pop(true);
            }
          },
        ),
      ),
    );

    if (mounted) {
      Navigator.of(context).pop(success == true);
    }
  }

  Future<void> _verifyOldPin(String oldPin) async {
    final storage = getIt<SecureStorage>();
    final storedPin = await storage.read('mpin');

    if (storedPin == int.tryParse(oldPin)) {
      // Old PIN is correct
      if (mounted) {
        Navigator.of(context).pop(true);
      }
    } else {
      // This shouldn't happen as MPinScreen handles validation
      if (mounted) {
        Navigator.of(context).pop(false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).changeMpin),
        centerTitle: true,
      ),
      body: const Center(
        child: CircularProgressIndicator(),
      ),
    );
  }
}
