import 'package:flutter/material.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/widgets/pin_input_field.dart';
import '../../../api/services/change_password_service.dart';

class ChangeTpinOtpScreen extends StatefulWidget {
  final String oldTpin;
  final String newTpin;
  final String mobileNumber;

  const ChangeTpinOtpScreen({
    super.key,
    required this.oldTpin,
    required this.newTpin,
    required this.mobileNumber,
  });

  @override
  State<ChangeTpinOtpScreen> createState() => _ChangeTpinOtpScreenState();
}

class _ChangeTpinOtpScreenState extends State<ChangeTpinOtpScreen> {
  final _otpController = TextEditingController();
  final ChangePasswordService _changePasswordService =
      getIt<ChangePasswordService>();
  bool _isLoading = false;

  void _handleVerifyOtp() async {
    if (_otpController.text.length != 6) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please enter a valid 6-digit OTP')),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      // 1. Validate the OTP first.
      await _changePasswordService.validateOtp(
        otp: _otpController.text,
        mobileNumber: widget.mobileNumber,
      );

      // 2. If OTP is valid, then call validateChangeTpin.
      await _changePasswordService.validateChangeTpin(
        oldTpin: widget.oldTpin,
        newTpin: widget.newTpin,
      );

      // 3. Show success message.
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('TPIN changed successfully!'),
            backgroundColor: Colors.green,
          ),
        );
        // 4. Navigate back to the profile screen or home.
        Navigator.of(context).popUntil((route) => route.isFirst);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('An error occurred: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Verify OTP'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const SizedBox(height: 24),
            const Text(
              'Enter the OTP sent to your registered mobile number.',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 16),
            ),
            const SizedBox(height: 32),
            PinInputField(
              controller: _otpController,
            ),
            const SizedBox(height: 32),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _isLoading ? null : _handleVerifyOtp,
                child: _isLoading
                    ? const SizedBox(
                        height: 24,
                        width: 24,
                        child: CircularProgressIndicator(
                          color: Colors.white,
                          strokeWidth: 2.5,
                        ),
                      )
                    : const Text('Verify & Change TPIN'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
