import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:kmobile/features/auth/controllers/auth_cubit.dart';
import 'package:kmobile/features/auth/controllers/auth_state.dart';

import '../../../l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:kmobile/features/fund_transfer/screens/tpin_otp_screen.dart';
import 'package:kmobile/api/services/change_password_service.dart'; // <-- Add this import
import 'package:kmobile/di/injection.dart'; // <-- Add this import

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

  @override
  State<TpinSetupPromptScreen> createState() => _TpinSetupPromptScreenState();
}

class _TpinSetupPromptScreenState extends State<TpinSetupPromptScreen> {
  int selectedAccountIndex = 0;
  bool _isLoading = false;
  final ChangePasswordService _changePasswordService =
      getIt<ChangePasswordService>();
  Future<void> _getOtp() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final authState = context.read<AuthCubit>().state;
      String mobileNumberToPass = '';
      if (authState is Authenticated) {
        if (selectedAccountIndex >= 0 &&
            selectedAccountIndex < authState.users.length) {
          mobileNumberToPass =
              authState.users[selectedAccountIndex].mobileNo ?? '';
        }
      }
      await _changePasswordService.getOtpTpin(mobileNumber: mobileNumberToPass);
      if (mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (_) => TpinOtpScreen(
                    mobileNumber: mobileNumberToPass,
                  )),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Error: ${e.toString()}')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Scaffold(
      appBar: AppBar(title: Text(AppLocalizations.of(context).setTpin)),
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 100.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.lock_person_rounded,
              size: 60,
              color: theme.colorScheme.primary,
            ),
            const SizedBox(height: 18),
            Text(
              AppLocalizations.of(context).tpinRequired,
              style: theme.textTheme.titleLarge?.copyWith(
                fontWeight: FontWeight.bold,
                color: theme.colorScheme.primary,
              ),
            ),
            const SizedBox(height: 12),
            Text(
              AppLocalizations.of(context).tpinRequiredMessage,
              textAlign: TextAlign.center,
              style: theme.textTheme.bodyMedium?.copyWith(
                color: Colors.grey[700],
              ),
            ),
            const SizedBox(height: 32),
            ElevatedButton.icon(
              icon: _isLoading
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        color: Colors.white,
                        strokeWidth: 2,
                      ),
                    )
                  : const Icon(Icons.arrow_forward_rounded),
              label: Text(
                AppLocalizations.of(context).setTpin,
                style:
                    const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: theme.colorScheme.onPrimary,
                padding: const EdgeInsets.symmetric(
                  vertical: 14,
                  horizontal: 32,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
              onPressed:
                  _isLoading ? null : _getOtp, // <-- Use the new function
            ),
            const SizedBox(height: 18),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 18.0),
              child: Text(
                AppLocalizations.of(context).tpinInfo,
                textAlign: TextAlign.center,
                style: theme.textTheme.bodySmall?.copyWith(
                  color: Colors.grey[600],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
